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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A logging filter can inject per-request context into every log record without changing call sites.
- 2Flask's g object gives you a safe place to stash request-scoped state that hooks and filters can share.
- 3Echoing an incoming correlation ID back in the response lets clients trace a request end to end.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/adding-correlation-ids-to-flask-logs-explained-python-0853/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.