Python Open Telemtry - 获取跟踪 ID

问题描述

假设我有一个使用 Open Telemtry 分布式跟踪的 Python 应用程序:

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)

在这种情况下如何获取跟踪 ID?我想把它记录到日志文件中。

谢谢

解决方法

您可以获取跨度上下文,然后访问跟踪 ID。在你的情况下,它会

number

请注意,如果您想在日志中自动注入诸如跟踪 ID、跨度 ID 之类的信息,并且您使用标准的 Python 日志记录模块,您可能需要使用 https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/logging/logging.html