JSON structured logging with request IDs — aggregate with ELK or Loki for cross-service search.
Centralised Structured Logging
import structlog, uuid
structlog.configure(processors=[
structlog.processors.add_log_level,
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.JSONRenderer()
])
log = structlog.get_logger()
@app.middleware("http")
async def log_middleware(request, call_next):
request_id = str(uuid.uuid4())
with structlog.contextvars.bind_contextvars(
request_id=request_id,
service="user-service"
):
response = await call_next(request)
log.info("request_done", status=response.status_code)
return response
# Output: {"event":"request_done","service":"user-service",
# "request_id":"abc","status":200,"timestamp":"..."}
# Aggregation: Filebeat->Elasticsearch->Kibana
# or: Fluentd->Loki->Grafana