newduino
newduino

Reputation: 187

Python Open Telemtry - Get Trace Id

Let's say I have a Python app that makes use of Open Telemtry distributed tracing:

from flask import Flask, jsonify, request
import tracer, connector, logger, metricer

app = Flask(__name__)


metricer.instrument(app)
tracer.instrument(app)
logger.instrument(app)


@app.route('/api/v1/participants', methods=["GET"])
def get_participants():

        with tracer.start_span("dbquery"):
            try:
                participants = connector.query()
                return jsonify(participants)
            except:
                logger.log("DB query has failed")
                return "Internal Server Error", 500

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8080, debug=False)

How can I get the trace ID in this case? I want to log it to the logfile.

Thx

Upvotes: 0

Views: 4858

Answers (1)

Srikanth Chekuri
Srikanth Chekuri

Reputation: 2274

You can get span context and then access trace ID. In your case it would be

...
        with tracer.start_span("dbquery") as sp:
            try:
                participants = connector.query()
                return jsonify(participants)
            except:
                logger.log("DB query has failed %s", sp.get_span_context().trace_id)
                return "Internal Server Error", 500
...

On side note if you want to automatically inject info such as trace id, span id in the logs and you use standard python logging module you may want to use https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/logging/logging.html

Upvotes: 1

Related Questions