open-telemetry / open-telemetry/opentelemetry-python-contrib

[FastAPI] exception handler always has span_id is 0

Open
#3,007 3 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
1.1k
Forks
1.1k
Avg merge
4d 15h
Merged PRs (30d)
16

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the FastAPIInstrumentor instrumentation and reproduce the issue using the provided exception_handler and middleware example. Compare the active span context at both points and trace how exception handling affects it; done means the handler reports the same nonzero span_id as the middleware.

Written by the indexing model from the issue text.

Assessment

Tech stack
fastapi, python
Domain
observability
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.