python - 在响应 header 中从 Jaeger 返回跟踪 ID

标签 python fastapi jaeger open-telemetry opentracing

我在我的 python FastAPI 应用程序中使用 opentelemetry。 它将痕迹发送回 Jaeger。 每个跟踪都有一个唯一的跟踪 ID,我也可以在 Jaeger UI 搜索栏中搜索。

我想在响应 header 中返回跟踪 ID,以便稍后我可以查找特定请求的跟踪(只需从 header 中获取跟踪 ID 并在 Jaeger UI 中搜索它)。

我尝试在 FastAPI 中添加一个中间件来添加跟踪 ID -

class EnrichOpenTelemetryId(BaseHTTPMiddleware):
    def __init__(self, app):
        super().__init__(app)

    async def dispatch(self, request: Request, call_next):
        with tracer.start_span("dummy-span") as span:
            trace_id = str(span.get_span_context().trace_id)

        response = await call_next(request)
        response.headers["X-Trace-Id"] = trace_id

        return response   

每个请求中都有一个包含一些跟踪 ID 的新 header (例如 - 149906749482483391829634904508866243046),但它不是 Jaeger 使用的 header ...(意味着我无法搜索该跟踪 ID)。 Jaeger 跟踪 ID 看起来像这样 - 8eddc793de380fa76c54557af09538e3。

那么如何获取 Jaeger 跟踪 ID?

最佳答案

从 Jaeger 项目 github 获得帮助 - https://github.com/jaegertracing/jaeger/discussions/3783 。 问题是我没有将跟踪 ID(整数)转换为十六进制值。 下面是一个工作片段 -

class CaptureTraceId(BaseHTTPMiddleware):
    def __init__(self, app):
        super().__init__(app)

    async def dispatch(self, request: Request, call_next):
        trace_id = trace.get_current_span().get_span_context().trace_id
        response = await call_next(request)
        response.headers["X-Trace-Id"] = format(trace_id, 'x')

        return response

关于python - 在响应 header 中从 Jaeger 返回跟踪 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72697787/

相关文章:

python - 循环根据多列条件过滤行 pandas python

python - Pandas 列提取

fastapi - CryptContext 散列如何知道使用什么 secret ?

spring-boot - 如何在 Kubernetes GKE 上部署 Jaeger

python - 如何在 excel 或 python 中提取单词周围的文本?

python - CryptographyDeprecationWarning : int_from_bytes is deprecated, 改为使用 int.from_bytes

python - 上传多个文件 UploadFiles FastAPI

elasticsearch - 如何在没有docker的Jaeger中配置 Elasticsearch

spring-boot - 如何使用 Spring Boot 的应用程序日志(由 slf4j 生成)丰富 Jaeger opentracing 数据?

python - UTF-8 列的 SQLAlchemy 结果是 'str' 类型,为什么?