← Back to FastAPI, page 3

fastapi-0049 · Hard senior

How do you add observability to a FastAPI service: structured logs with a request ID, metrics and tracing?

Use a middleware that creates or accepts a request ID, stores it in a contextvar so every log line includes it, and logs one structured JSON line per request with method, path template, status and duration. Expose metrics (request count and latency histogram labelled by route template, not raw URL) for Prometheus, and use OpenTelemetry for distributed traces that propagate trace context to downstream calls. Keep log volume, label cardinality and personal data under control.

Full answer

Three signals, used together:

Logs: what happened. Make them structured (JSON) so tools can filter by fields, and correlate them with a request ID.

  • Middleware reads X-Request-ID (or generates a UUID), puts it in a contextvars.ContextVar, returns it in the response header, and a logging filter adds it to every record, including logs from libraries and services deep in the call stack. Contextvars flow correctly across await.
  • Log once per request at the end: method, route template (/students/{roll_no}), status, duration, user ID (not names or tokens). Do not log request bodies with passwords, tokens or personal data.
  • Log unexpected exceptions with stack traces and the request ID; keep expected 4xx at info or warning.
  • Write to stdout; let the platform ship it.

Metrics: how the system behaves over time. Prometheus style:

  • Counter http_requests_total{method, route, status} and histogram http_request_duration_seconds{route}.
  • Label with the route template from request.scope["route"].path, never the raw path; /students/1, /students/2... would create unbounded label values and overload the metrics store (high cardinality).
  • Add business and dependency metrics: database pool usage, queue depth, outbound call latency.
  • Watch the "golden signals": latency (p95, p99), traffic, errors, saturation.

Traces: where time went across services. OpenTelemetry instrumentation (opentelemetry-instrumentation-fastapi, -httpx, -sqlalchemy) creates spans and propagates the traceparent header. Put the trace ID in logs to jump from a log line to the trace.

Health: separate liveness and readiness endpoints; exclude them from noisy logs and latency alerts.

Alerts should be on symptoms users feel (error rate, p95 latency), with dashboards for diagnosis.

python
import contextvars
import io
import json
import logging
import time
import uuid
from collections import Counter

from fastapi import FastAPI, Request
from fastapi.testclient import TestClient

request_id_var = contextvars.ContextVar("request_id", default="-")
stream = io.StringIO()


class JsonFormatter(logging.Formatter):
    def format(self, record):
        payload = {"level": record.levelname, "msg": record.getMessage(), "request_id": request_id_var.get()}
        payload.update(getattr(record, "extra_fields", {}))
        return json.dumps(payload, sort_keys=True)


handler = logging.StreamHandler(stream)
handler.setFormatter(JsonFormatter())
log = logging.getLogger("campus")
log.addHandler(handler)
log.setLevel(logging.INFO)
log.propagate = False

REQUESTS = Counter()          # a prometheus_client Counter/Histogram in a real service

app = FastAPI()


@app.middleware("http")
async def observe(request: Request, call_next):
    rid = request.headers.get("X-Request-ID") or str(uuid.uuid4())
    token = request_id_var.set(rid)
    start = time.perf_counter()
    try:
        response = await call_next(request)
        return_value = finish(request, response, rid, start)
    finally:
        request_id_var.reset(token)
    return return_value


def finish(request: Request, response, rid: str, start: float):
    route = request.scope.get("route")
    template = route.path if route else "unmatched"
    REQUESTS[(request.method, template, response.status_code)] += 1
    response.headers["X-Request-ID"] = rid
    log.info("request", extra={"extra_fields": {"method": request.method, "route": template,
                                                  "status": response.status_code,
                                                  "duration_s": int(time.perf_counter() - start)}})
    return response


def check_fees(roll_no: str):
    log.info("fee lookup")            # deep in service code: still carries the request ID


@app.get("/students/{roll_no}")
def student(roll_no: str):
    check_fees(roll_no)
    return {"roll_no": roll_no}


c = TestClient(app)
c.get("/students/BCA-17", headers={"X-Request-ID": "req-abc"})
c.get("/students/BCA-18", headers={"X-Request-ID": "req-def"})
c.get("/nowhere")
for line in stream.getvalue().splitlines()[:2]:
    print(line)
print(dict(REQUESTS))

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Duration is logged in whole seconds in the log line so the output is identical on every run. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {"level": "INFO", "msg": "fee lookup", "request_id": "req-abc"} {"duration_s": 0, "level": "INFO", "method": "GET", "msg": "request", "request_id": "req-abc", "route": "/students/{roll_no}", "status": 200} {('GET', '/students/{roll_no}', 200): 2, ('GET', 'unmatched', 404): 1}

Key points

  • Request ID in a contextvar, added to every log record
  • One structured log line per request with route template and duration
  • Metrics labelled by route template, not raw URL
  • OpenTelemetry for traces and context propagation
  • Never log secrets or personal data

Common mistakes

  • Using raw URL paths as metric labels and exploding cardinality
  • Logging request bodies with passwords or personal data
  • Passing the request ID through every function argument instead of a contextvar
  • Printing unstructured text that cannot be filtered
  • Alerting on every 4xx instead of user-visible error rates

Follow-ups

  • How do you propagate a trace across an HTTP call to another service?
  • What is metric cardinality and why does it matter?
  • How would you sample traces on a high-traffic service?

Tips

  • Explain the contextvar approach and why it survives await
  • Say route template, not raw path, for metrics
  • Link logs, metrics and traces by IDs