Script Valley
FastAPI: Build Production Python APIs
Production DeploymentLesson 6.3

How to add structured logging to a FastAPI application

Python logging module, structlog, request ID middleware, log levels, JSON log format, uvicorn access logs, middleware logging, correlation IDs

Structured Logging in FastAPI

Production logs must be machine-readable. JSON logging lets tools like Datadog, Loki, and CloudWatch parse and filter log fields without regex.

Middleware that logs every request

import logging
import time
import uuid
from fastapi import FastAPI, Request

logging.basicConfig(
    level=logging.INFO,
    format='{"time": "%(asctime)s", "level": "%(levelname)s", "message": "%(message)s"}'
)
logger = logging.getLogger(__name__)

app = FastAPI()

@app.middleware("http")
async def log_requests(request: Request, call_next):
    request_id = str(uuid.uuid4())[:8]
    start = time.time()
    response = await call_next(request)
    duration = round(time.time() - start, 4)
    logger.info(
        f"request_id={request_id} method={request.method} "
        f"path={request.url.path} status={response.status_code} "
        f"duration={duration}s"
    )
    return response

Add request_id to log entries so you can trace a full request chain across services. Include it in the response as a header too: response.headers["X-Request-Id"] = request_id.

For full JSON structured logging, use the structlog library which supports context binding, processor pipelines, and multiple output formats with minimal configuration.

Up next

How to add health check and readiness endpoints to FastAPI

Sign in to track progress

How to add structured logging to a FastAPI application โ€” Production Deployment โ€” FastAPI: Build Production Python APIs โ€” Script Valley โ€” Script Valley