Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
sdg9670f opened this issue Nov 15, 2024 · 0 comments
Open

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

sdg9670f opened this issue Nov 15, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@sdg9670f
Copy link

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

@sdg9670f sdg9670f added the bug Something isn't working label Nov 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant