【问题标题】:Python Open Telemtry - Get Trace IdPython Opentelemetry - 获取跟踪 ID
【发布时间】:2021-05-10 13:42:11
【问题描述】:

假设我有一个使用 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?我想把它记录到日志文件中。

谢谢

【问题讨论】:

    标签: python flask open-telemetry


    【解决方案1】:

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

    ...
            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
    ...
    
    

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

    【讨论】:

      猜你喜欢
      • 2022-07-03
      • 2022-08-05
      • 2016-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-02
      • 2021-05-27
      • 1970-01-01
      相关资源
      最近更新 更多