open-telemetry / opentelemetry-python-contrib

OpenTelemetry instrumentation for Python modules
https://opentelemetry.io
Apache License 2.0
739 stars 612 forks source link

[FastAPI] exception handler always has span_id is 0 #3007

Open sdg9670f opened 1 week ago

sdg9670f commented 1 week ago

Describe your environment

OS: Ubuntu Python version: 3.12

What happened?

When an exception is raised and handled by the exception_handler, the span_id printed is always 0. However, the span_idprinted in the middleware is correct.

Steps to Reproduce

from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from fastapi.responses import JSONResponse
from fastapi import FastAPI, Request
from opentelemetry.trace import get_current_span
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter

otlp_url = 'http://localhost:4317'

trace.set_tracer_provider(TracerProvider())
span_exporter = OTLPSpanExporter(endpoint=otlp_url)
span_processor = BatchSpanProcessor(span_exporter)
trace.get_tracer_provider().add_span_processor(span_processor)

app = FastAPI()

@app.exception_handler(Exception)
def exception_handler(request: Request, exception: Exception):
    print('exception_handler', get_current_span().get_span_context().span_id)

    return JSONResponse(
        status_code=500,
        content={"message": "Internal server error"},
    )

@app.middleware("http")
async def middleware(request: Request, call_next):
    print('middleware', get_current_span().get_span_context().span_id)

    response = await call_next(request)
    return response

@app.get("/")
def read_root():
    raise Exception("error")

FastAPIInstrumentor.instrument_app(app)

Expected Result

middleware 1234 exception_handler 1234

Actual Result

middleware 1234 exception_handler 0

Additional context

No response

Would you like to implement a fix?

None