The project uses structlog for structured logging and python-json-logger for JSON output in non‑development environments.
- In development, logs are formatted as human‑readable console output.
- In production/staging, logs are JSON objects compatible with log aggregators (e.g. ELK, Datadog).
Two logging middlewares are active:
-
CorrelationIDMiddleware
- Reads
X-Correlation-IDheader or generates a UUID. - Attaches the ID to the request state and response header.
- Reads
-
RequestLoggingMiddleware
- Logs every request with method, path, status code, duration, and correlation ID.
- Uses
structlogunder the hood.
Use LogContext to temporarily bind key‑value pairs to all log messages emitted within a block:
from app.logging.context import LogContext
with LogContext(user_id=42, action="update"):
logger.info("User update started")Import the logger:
import structlog
logger = structlog.get_logger(__name__)
logger.info("Something happened", extra_field="value")