Skip to content

FastAPI and Python OpenTelemetry Logging Without Multi-Line Sprawl

AI startups often run Next.js frontends backed by Python FastAPI or Celery workers. Default Python tracebacks print 35 separate lines to stdout, wrecking log search and inflating event bills.

Exla Engineering··5 min read

35 -> 1

Traceback lines collapsed to 1 OTLP event

FastAPI + Celery

Shared trace_id & tenant_id context

Python 3.10+

Standard OTLP/HTTP exporter

Key takeaway

Attach OpenTelemetry's LoggingHandler to Python's root logger (or structlog) so every FastAPI exception exports over OTLP/HTTP as one structured event with full traceback, trace_id, and tenant_id.

Why default uvicorn and gunicorn stdout breaks production debugging

When FastAPI raises a Pydantic ValidationError or httpx ReadTimeoutError, container runtimes split the multi-line Python traceback into dozens of disconnected log records.

In Datadog that multiplies your per-event indexing bill by 30x; in CloudWatch it strips the tenant_id printed on line 1 from the exception message on line 34.

Drop-in Python OTLP LoggingHandler for FastAPI

Wire opentelemetry-sdk and opentelemetry-exporter-otlp-proto-http once at FastAPI startup so standard logging.error(..., exc_info=True) ships structured records directly to Libra Logs.

app/telemetry.py
import logging, os
from opentelemetry._logs import set_logger_provider
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from opentelemetry.sdk.resources import Resource

def configure_logging() -> None:
    provider = LoggerProvider(resource=Resource.create({
        "service.name": os.getenv("OTEL_SERVICE_NAME", "fastapi-worker"),
        "deployment.environment": os.getenv("ENVIRONMENT", "production"),
    }))
    exporter = OTLPLogExporter(
        endpoint=os.getenv("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", "https://libra-logs-api.fly.dev/logs/api/v1/logs"),
        headers={"Authorization": f"Bearer {os.getenv('LIBRA_LOGS_INGEST_KEY', '')}"},
    )
    provider.add_log_record_processor(BatchLogRecordProcessor(exporter))
    set_logger_provider(provider)
    logging.getLogger().addHandler(LoggingHandler(level=logging.INFO, logger_provider=provider))

One workspace for your Next.js frontend and Python AI workers

Send Next.js and FastAPI OTLP logs into the same Libra Logs workspace ($20/mo up to 25 GB for 1-2 employees; $150/mo up to 100 GB for 3-9 employees) so failed AI runs group by customer and flow straight into Claude Code or Cursor.

Simple pricing · 30-day free trial

Stop paying per indexed log event. Group bugs by customer instead.

$20/mo

1-2 employees · up to 25 GB

$150/mo

3-9 employees · up to 100 GB + Slack alerts

10+ staff

We beat your Datadog/Sentry bill

Talk to sales

FAQ

Common engineering questions

Does npx libra-logs work in Python FastAPI and Django repositories?

Yes. Running npx libra-logs (or pasting the setup prompt into Claude Code or Cursor) creates your workspace ingest key and configures Python OpenTelemetry export on a clean branch.

Should Celery or Modal workers flush logs on task shutdown?

Call provider.force_flush(timeout_millis=3000) in worker shutdown hooks for short-lived serverless containers so the final batch always delivers.