pythonfastapijaegeropen-telemetryopentracing

Return trace id from Jaeger in response header


I am using opentelemetry in my python FastAPI application. It sends traces back to Jaeger. Each trace has a unique trace id I can also search for in the Jaeger UI search bar.

I want to return in the response headers that trace id so that later on I can look a trace for a specific request (just take the trace id from the header and search for it in Jaeger UI).

I tried adding a middleware in FastAPI that adds the trace id like that -

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   

There is a new header containing some trace id (e.g - 149906749482483391829634904508866243046) in each request but it's not the one Jaeger uses... (meaning I cannot search on that trace id). Jaeger trace id looks something like that - 8eddc793de380fa76c54557af09538e3.

So how do I get Jaeger trace id?


Solution

  • Got help from the Jaeger project github - https://github.com/jaegertracing/jaeger/discussions/3783. The issue was that I didn't convert the trace id (integer) to hex value. Here is a working snippet following that -

    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