OpenTelemetry FastAPI Instrumentation

0.61b0 · active · verified Sat Mar 28

OpenTelemetry FastAPI Instrumentation provides automatic and manual instrumentation for FastAPI web frameworks. It allows for comprehensive application performance monitoring (APM), distributed tracing, and observability by collecting traces and metrics from HTTP requests, database queries, and external API calls with minimal code changes. The library is currently in beta (version 0.61b0) and is part of the broader `opentelemetry-python-contrib` project, which sees frequent updates across its various instrumentations.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up OpenTelemetry instrumentation for a FastAPI application. It initializes a `TracerProvider` with an `OTLPSpanExporter` to send traces to an OTLP-compatible backend. The `FastAPIInstrumentor.instrument_app(app)` call automatically creates spans for incoming HTTP requests. The OpenTelemetry setup is integrated using FastAPI's `lifespan` events for proper initialization and shutdown, especially crucial for multi-process environments like uvicorn with multiple workers. Make sure an OTLP collector is running at the specified endpoint.

import os
from contextlib import asynccontextmanager

from fastapi import FastAPI
from opentelemetry import trace
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter

# Configure OpenTelemetry SDK
# It is recommended to initialize OpenTelemetry within FastAPI's lifespan events
# when using multi-process servers (e.g., uvicorn --workers > 1 or gunicorn).
# For simple single-process development, top-level initialization is sufficient.

def setup_tracing():
    resource = Resource.create(attributes={
        "service.name": os.environ.get("OTEL_SERVICE_NAME", "my-fastapi-app")
    })
    tracer_provider = TracerProvider(resource=resource)
    
    # Use OTLP HTTP exporter for traces
    # OTLP endpoint can be configured via environment variable OTEL_EXPORTER_OTLP_ENDPOINT
    # Default is http://localhost:4318/v1/traces for HTTP
    otlp_exporter = OTLPSpanExporter(
        endpoint=os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4318/v1/traces")
    )
    span_processor = BatchSpanProcessor(otlp_exporter)
    tracer_provider.add_span_processor(span_processor)
    trace.set_tracer_provider(tracer_provider)

    print("OpenTelemetry tracing initialized.")

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup logic: Initialize OpenTelemetry
    setup_tracing()
    FastAPIInstrumentor.instrument_app(app)
    yield
    # Shutdown logic: Flush and shutdown exporter
    provider = trace.get_tracer_provider()
    if hasattr(provider, 'shutdown'):
        provider.shutdown()
    print("OpenTelemetry tracing shutdown.")

# Initialize FastAPI app with lifespan events
app = FastAPI(lifespan=lifespan)

@app.get("/hello")
async def read_root():
    return {"message": "Hello, World!"}

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id, "message": "Item fetched"}

# To run this application:
# 1. Save it as main.py
# 2. Run from your terminal:
#    OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:4318/v1/traces" OTEL_SERVICE_NAME="my-fastapi-app" uvicorn main:app --port 8000 --reload --lifespan on
#    Note: For production, omit --reload and manage workers via gunicorn post_fork hooks if using multiple workers.
# 3. Access in browser: http://localhost:8000/hello or http://localhost:8000/items/123

view raw JSON →