python 35 lines · 7 steps

Adding correlation IDs to Flask logs

Tag every request with a correlation ID that flows through logs and back out in the response header.

Explained by highlit
1import logging
2import uuid
3from flask import Flask, request, g
4 
5app = Flask(__name__)
6 
7 
8class CorrelationIdFilter(logging.Filter):
9 def filter(self, record):
10 record.correlation_id = getattr(g, "correlation_id", "-")
11 return True
12 
13 
14handler = logging.StreamHandler()
15handler.setFormatter(
16 logging.Formatter(
17 "%(asctime)s [%(levelname)s] [cid=%(correlation_id)s] %(name)s: %(message)s"
18 )
19)
20handler.addFilter(CorrelationIdFilter())
21 
22app.logger.handlers = [handler]
23app.logger.setLevel(logging.INFO)
24 
25 
26@app.before_request
27def assign_correlation_id():
28 g.correlation_id = request.headers.get("X-Correlation-ID") or uuid.uuid4().hex
29 app.logger.info("%s %s", request.method, request.path)
30 
31 
32@app.after_request
33def propagate_correlation_id(response):
34 response.headers["X-Correlation-ID"] = getattr(g, "correlation_id", "-")
35 return response
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A logging filter can inject per-request context into every log record without changing call sites.
  2. 2Flask's g object gives you a safe place to stash request-scoped state that hooks and filters can share.
  3. 3Echoing an incoming correlation ID back in the response lets clients trace a request end to end.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Adding correlation IDs to Flask logs — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code