TL;DR
- OpenTelemetry structured logging in FastAPI has two context sources. Bind a local request ID and approved identity fields with Structlog’s context variables. Read the active trace and span IDs when each event is logged. A nested database or downstream request should keep the trace ID while reporting its own span ID.
- Emit one JSON object per line to stdout. Keep event names stable, use a defined field schema, and map the trace ID field into the log backend’s correlation feature. Test real links from a log record to a trace across services. Confirm that the viewer explains missing or unsampled traces gracefully.
- Draw a boundary around request context. Clear it when an HTTP request starts, and bind actor or tenant identifiers only after authentication. Give queue jobs independent context and pass approved correlation fields explicitly. Verify that parallel requests and background work carry the intended identities.
Why request logs lose their context
During an incident, an API owner has a failed request ID from support. The API logs a validation error, an upstream dependency reports a timeout, and a worker later retries related work. Each process has its own logger and wall clock. Searching for a text fragment can find similar errors, while it leaves open whether those lines came from the same request or from unrelated traffic. A trace identifies the distributed interaction. The active span identifies the operation in which an application event occurred.
A line of plain text can carry useful information. At scale, consistent structure determines whether a collector can extract and filter it. If each handler embeds the tenant ID differently, retention policy, dashboards, and route-level searches become dependent on regular expressions. If a traceback is printed over several physical lines, the collector may ingest each frame as an independent message. An application process emitting line-delimited JSON gives the collector a stable record boundary and typed fields. You can achieve that with Structlog or a standard-library formatter.
Request IDs, trace IDs, and span IDs answer different queries. A request ID gives support a short handle for the request through its retry or error response policy. A trace ID spans multiple processes that participate in propagation. A span ID identifies a particular unit of operation and can change several times within one handler. Copying a server span ID into a request global produces plausible-looking logs whose most valuable detail, the local operation, becomes inaccurate as soon as a child span is active.
Start with a concrete diagnostic: from one application error, find the affected request, open the trace, and tell which external operation occupied most wall time. Add privacy and delivery constraints alongside it. A route, timestamp, error class, and policy-approved opaque IDs usually answer that question. Authorization headers, cookies, raw bodies, and unredacted SQL bind parameters generally make the incident more expensive without improving that query.
OpenTelemetry structured logging architecture
Keep transport propagation and event enrichment separate
Instrument the FastAPI service and relevant downstream clients. The W3C traceparent header carries shared trace context across service boundaries. An inbound header describes the upstream parent. Use the local active OpenTelemetry span as the source for this service’s log event fields, which may describe a server span or a child operation. Leave parsing and validation of propagation headers to the instrumented stack. W3C Trace Context specification.
Write trace_id and span_id as fixed-width lowercase hexadecimal strings, with 32 and 16 characters respectively. OpenTelemetry’s compatibility guidance places them at the top level of JSON records along with optional trace_flags. JSON output remains usable in a backend that has yet to enable trace linking. When moving to native OTLP logs, map these values into the log record’s context fields, following the ingestion contract. OpenTelemetry trace context in non-OTLP log formats.
Assign request fields at the authentication boundary
At HTTP entry, generate an opaque request ID and attach it to the response. If an ingress already assigns public request IDs, define whether it can supply that field. Validate its format and length and discard public duplicates before reusing it. Once authentication resolves an actor and tenant, bind only identifiers allowed by telemetry policy. Those fields help an investigator locate the operation. The authorization decision comes from the verified application identity and policy.
Bind request context in a pure ASGI middleware. It can hold state in local variables while messages move through the same request scope. When a synchronous dependency or a different task binds its own context, mutations may not be visible to the parent. Test async handlers, thread-pool work and any background jobs explicitly. The Structlog context variables documentation describes the isolation caveat in hybrid Starlette applications.
Agree on stable event names such as request_completed and report_snapshot_loaded. Backends can index those names cheaply compared with arbitrary full messages. Trace and request IDs belong in log attributes for lookup. Promoting unique IDs to metric labels or log stream labels can create a distinct series or stream for each request, with a corresponding ingestion and query cost. Reserve dimensions such as service, environment, and outcome for aggregate dashboards.
Implement JSON logging in FastAPI
Read the active span in a Structlog processor
The following module targets Python 3.12 and uses structlog, opentelemetry-api, and the application’s normal logging level configuration. It configures Structlog application events. Uvicorn and third-party logging remain separate until explicitly bridged. Set all three ID fields from the active span or omit them, so a caller cannot accidentally supply stale context fields.
# json_logging.py — Python 3.12
import logging
import os
import sys
import structlog
from opentelemetry import trace
def add_trace_context(_logger, _method, event):
for key in ("trace_id", "span_id", "trace_flags"):
event.pop(key, None)
context = trace.get_current_span().get_span_context()
if context.is_valid:
# An unsampled span may still have valid correlation IDs.
event["trace_id"] = trace.format_trace_id(context.trace_id)
event["span_id"] = trace.format_span_id(context.span_id)
event["trace_flags"] = f"{int(context.trace_flags):02x}"
return event
def configure_logging() -> None:
level_name = os.environ.get("LOG_LEVEL", "INFO").upper()
levels = logging.getLevelNamesMapping()
if level_name not in levels:
raise ValueError(f"invalid LOG_LEVEL: {level_name}")
structlog.configure(
processors=[
structlog.contextvars.merge_contextvars,
structlog.processors.add_log_level,
structlog.processors.TimeStamper(fmt="iso", utc=True),
add_trace_context,
structlog.processors.JSONRenderer(),
],
wrapper_class=structlog.make_filtering_bound_logger(levels[level_name]),
logger_factory=structlog.WriteLoggerFactory(file=sys.stdout),
cache_logger_on_first_use=True,
)
The span lookup happens synchronously while the application emits an event. If you add a logging queue, capture trace and request context before crossing to the consumer. Choose a bounded queue and define how it behaves when the collector or stdout destination backs up. If you need to ignore DEBUG events at high volume, filter before processor work and measure serialization overhead per request.
Bind the request ID and instrument the service
Install a compatible lock set for fastapi, uvicorn, structlog, opentelemetry-sdk, opentelemetry-instrumentation-fastapi and opentelemetry-exporter-otlp-proto-grpc. The example registers SDK tracing and instruments FastAPI directly. Use one instrumentation path per process. Start worker processes in your usual deployment entry point and configure proxy trust there. OpenTelemetry FastAPI instrumentation guide.
# app.py — Python 3.12
from time import perf_counter
from uuid import uuid4
import structlog
from fastapi import FastAPI
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from starlette.datastructures import MutableHeaders
from starlette.types import ASGIApp, Receive, Scope, Send
from json_logging import configure_logging
configure_logging()
provider = TracerProvider()
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(provider)
log = structlog.get_logger()
tracer = trace.get_tracer(__name__)
class RequestContext:
def __init__(self, app: ASGIApp):
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
structlog.contextvars.clear_contextvars()
request_id = uuid4().hex
started = perf_counter()
status_code = None
async def send_with_id(message):
nonlocal status_code
if message["type"] == "http.response.start":
status_code = message["status"]
MutableHeaders(scope=message)["X-Request-ID"] = request_id
await send(message)
with structlog.contextvars.bound_contextvars(request_id=request_id):
try:
await self.app(scope, receive, send_with_id)
except Exception as error:
log.error("request_failed", error_type=type(error).__name__,
status_code=status_code)
raise
else:
route = getattr(scope.get("route"), "path", "unmatched")
log.info("request_completed", route=route, status_code=status_code,
duration_ms=round((perf_counter() - started) * 1000, 2))
app = FastAPI()
app.add_middleware(RequestContext)
FastAPIInstrumentor.instrument_app(app)
@app.get("/report")
async def report():
with tracer.start_as_current_span("reports.snapshot"):
# Bind approved identity context here after real authorization.
log.info("report_snapshot_loaded", source="snapshot")
return {"ready": True}
Run with the following environment variables. In this example the collector is listening for OTLP gRPC on a private network. Its endpoint uses plaintext inside that example boundary. Use TLS and the required exporter credentials on networks where transport protection is required. Configure collector export and shutdown behavior for the actual deployment. OpenTelemetry SDK environment variables.
export LOG_LEVEL=INFO
export OTEL_SERVICE_NAME=report-api
export OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=staging
export OTEL_TRACES_SAMPLER=parentbased_traceidratio
export OTEL_TRACES_SAMPLER_ARG=0.10
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://otel-collector:4317
uvicorn app:app --host 0.0.0.0 --port 8000
For a local correlation test, set sampling to always on, issue a request to /report, and find the returned request ID in stdout. Compare the two events after JSON decoding. When middleware and tracer instrumentation share context, the trace ID is identical and the child span ID differs from the enclosing request span. Then test a return path, an exception before response start, and an exception during streaming. A framework-generated error response may bypass your wrapped sender when the middleware is inside the framework’s error handler. If all browser responses must expose a request ID, implement that requirement at an outer ASGI or ingress boundary and independently test where this service records the active span.
Verify the same event after ingestion. A container runtime can wrap stdout in its own line format, so the collector may need to decode that envelope before parsing the application JSON. In Grafana with Loki and Tempo, use a derived field to capture the trace ID and link it to the Tempo data source. If raw JSON reaches Loki, test the capture pattern "trace_id"\s*:\s*"([0-9a-f]{32})" against an ingested line. For CloudWatch Logs Insights, confirm whether trace_id is discovered or whether the ingestion path requires explicit extraction. These are different backends using the same application fields. Grafana trace correlation setup · CloudWatch discovered field reference.
Failure modes during rollout
Context disappears after a worker handoff
Logs from a queued task still display the original HTTP actor or contain no trace IDs. A queue message needs its own approved job attributes and explicit tracing propagation if cross-process correlation is required. Extract the trace context from the queue envelope, create the worker span, clear local logging context, and bind job fields for the task duration. Avoid copying the whole HTTP request context into detached work.
The backend cannot open a trace for a valid-looking ID
First check the formatting and the backend’s correlation mapping. Then check trace flags, trace retention, and exporter failures. An unsampled trace can carry valid IDs without producing stored spans. A sampled trace can also be unavailable if export or storage failed. One healthy staging trace and one unsampled event make a better smoke test than verifying field presence alone.
Two collectors duplicate the same events
The team adds a native logs exporter while the existing file or container-tail path still forwards stdout. The log platform now receives two records per application event. Choose a routing owner while migrating signals, or isolate destinations until you compare volume and fidelity. Uvicorn access events may already cover request completion, so decide which version supplies the operational schema before enabling both.
An error exposes request data
A vendor exception message can contain a URL with query parameters, a storage path, or SQL values. Field-level allowlists help, but data can also appear inside long strings. With controlled test data, assert that tokens, emails, and secrets stay out of both logs and spans. Use a route pattern and exception class for ordinary diagnostics, and keep any richer details in a restricted channel.
When to choose a different log pipeline
Standard-library JSON logging works for teams that already configure a common logging.LogRecord pipeline. Add a formatter or record factory that enriches events with current context, and check that third-party events retain their existing levels and namespace. Structlog provides ergonomic event dictionaries and processing, while the important dependency is a common schema throughout the service.
Native OTLP log records are a good fit when the organization already runs collector infrastructure, owns the exporter lifecycle, and needs resource attributes and trace linkage across languages. Container stdout is convenient when the platform already collects it and needs to preserve process-level events during startup or shutdown. Test the chosen boundary for queue overflow and graceful shutdown.
Trace-only diagnostics can serve a small, fully instrumented service with aligned retention and sampling. Separate logs remain important when startup failures, unsampled requests, customer-supplied request IDs, or compliance events require independent retrieval.
Estimate logging volume before enabling every event
In a hypothetical service at 250 requests per second, three records per request at 550 bytes each produce about 412.5 KB/s, or 35.64 GB/day using decimal units. The estimate excludes transport framing, compression, collector enrichment, and other application events. Dropping one routine success event per request reduces the estimate by 11.88 GB/day. This is a capacity calculation, without extrapolation from a client deployment.
Measure actual bytes per severity, events per route, ingestion lag, and the fraction of error records whose trace link opens a stored trace. Run the same load with logging enabled and suppressed to estimate added CPU and p95 endpoint latency. Compare serialization and collector costs separately. Keep useful error and security signals when thinning high-volume informational events.
Frequently asked questions
How do I add a trace ID to Structlog logs in FastAPI?
Add a Structlog processor that calls OpenTelemetry’s current span API and reads the span context when each event is emitted. When the context is valid, write the trace ID and span ID as lowercase hexadecimal fields. Configure FastAPI instrumentation and the tracer provider before serving traffic, and test a nested span.
Why are the trace IDs present when the trace cannot be found?
A valid span context can exist even when the trace is unsampled or an exporter cannot deliver the spans. Inspect the trace flags, exporter health, retention, and the log backend’s correlation mapping. Verify the lookup using a known sampled request in staging and confirm that the same trace ID arrives at both storage systems.
How should I prevent request context from leaking between requests?
Clear Structlog context at the request boundary, then bind the request ID and approved identity keys for the life of the request. Keep request data in context-local storage, and reset scoped binds when work finishes. For tasks that outlive the request or cross processes, establish explicit job context independently and test concurrent requests.
Further reading
- Managing per-tenant capacity in a worker pool
- Tracing evidence selection in production RAG evaluation
- OpenTelemetry Python instrumentation reference
Make incident evidence easier to follow
If you’re rolling out OpenTelemetry structured logging, talk to our engineering team about event schemas, sampling, or tracing a request across your services.
