How to include trace id in response header?
npuichigo opened this issue · 4 comments
npuichigo commented
I tried to add one middleware like
class CaptureTraceIdInResponse(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"] = trace.format_trace_id(trace_id)
return response
but failed. Could you help to give some guidance?
npuichigo commented
It seems that I need to add middleware before calling setting otlp. It works for me now, but I have no idea why should it be that.
blueswen commented
Not sure what error you got. Following middleware code is work for me:
from fastapi import FastAPI, Request, Response
from opentelemetry import trace
from opentelemetry.propagate import inject
from starlette.middleware.base import BaseHTTPMiddleware
class CustomHeaderMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
response = await call_next(request)
inject(response.headers) # leverage inject function
span = trace.get_current_span()
trace_id = trace.format_trace_id(span.get_span_context().trace_id)
response.headers["My-Trace-Id"] = trace_id # only retrieve trace ID
return response
The response header looks like:
npuichigo commented
I add this middleware after setting otlp so it failed to show correct trace id
blueswen commented
Try my middleware from the previous reply, or provide logs of your application, responses from the application, and trace data screenshots on Grafana for more drill-down discussion.