Skip to content

Instantly share code, notes, and snippets.

@tonybaloney
Last active March 25, 2024 23:52
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonybaloney/2ad886bc2f70935d38a7d1c8f5e29b54 to your computer and use it in GitHub Desktop.
Save tonybaloney/2ad886bc2f70935d38a7d1c8f5e29b54 to your computer and use it in GitHub Desktop.
FastAPI with OpenTelemetry
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from opentelemetry.context import get_current as get_current_context
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.sdk.trace import TracerProvider, _Span
from opentelemetry.sdk.trace.export import (BatchSpanProcessor,
ConsoleSpanExporter,
SimpleSpanProcessor)
from starlette.exceptions import HTTPException as StarletteHTTPException
from .models import Settings
app = FastAPI()
settings = Settings(_env_file=".env")
tracer = TracerProvider()
import .routes # NOQA
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc):
span_key = list(get_current_context().keys())[0]
span = get_current_context().get(span_key)
assert isinstance(span, _Span)
return JSONResponse(
{
"message": str(exc.detail),
"trace_id": span.context.trace_id,
"span_id": span.context.span_id
},
status_code=exc.status_code
)
@app.on_event("startup")
def startup_event():
if settings.verbose_tracing: # Prints all traces on console
tracer.add_span_processor(
SimpleSpanProcessor(ConsoleSpanExporter())
)
# Example of an external exporter, see https://opentelemetry.io/registry/?language=python
if settings.app_insights_connection_string:
exporter = AzureMonitorTraceExporter.from_connection_string(
settings.app_insights_connection_string
)
tracer.add_span_processor(
BatchSpanProcessor(exporter)
)
FastAPIInstrumentor.instrument_app(app, tracer_provider=tracer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment