Lab: Structured Logs with Request IDs
Build a FastAPI logging setup that writes one JSON line per event, carries a request ID into outbound calls and background jobs, survives exceptions, and redacts secrets as a safety net.
Contentsand lesson path
On this page
- Lab overview and setup
- Log level discipline in production systems
- Step 1: Correlation ID context and ASGI middleware
- Step 2: JSON formatter and redaction safety net
- Step 3: Request IDs in outbound calls and background jobs
- Step 4: Verify with pytest and a demo run
- Check your understanding
- Apply it
- Review prompt
Lessons of Error Handling & Structured Logging
- Expected Errors, Bugs and Outages Concept · 15 min
- One Place to Turn Exceptions into Responses Worked example · 25 min
- When the Database or an Upstream API Fails Concept · 20 min
- Lab: Structured Logs with Request IDs Lab · 25 min
- Check: Triage an Incident from the Logs Knowledge check · 6 questions
What you will learn
- Emit structured JSON logs carrying a request ID across the request, outbound calls and background jobs, at suitable levels and without secrets or personal data.
Prerequisites: FastAPI Fundamentals
01. Lab overview and setup
A busy service handles many requests at once, and in async Python their log lines interleave on one event loop. A text line such as 2026-10-27 ERROR order failed for user 42 does not say which request it belongs to, and a log platform such as Grafana Loki, Datadog or OpenSearch can only filter it with fragile regular expressions.
In this lab you build a logging setup in which:
- every request gets an ID, taken from a trusted upstream
X-Request-IDheader or generated, and echoed in the response; - every log line is one JSON object with the timestamp, level, logger, message, request ID and your own fields;
- the ID travels into outbound HTTP calls and background jobs, so one search finds the whole story;
logger.exception()produces a JSON line with the traceback instead of crashing the formatter;- likely secrets are redacted, including nested fields and card-like numbers, as a last line of defence;
- a pytest suite checks all of the above.
You need Python 3.11 or newer. The code was tested with Python 3.13, FastAPI 0.163.1, Starlette 1.10.0, httpx 0.28.1, httpx2 2.16.2 and pytest 9.2.0. The fastapi[standard] extra installs both httpx (used by the app) and httpx2, which Starlette 1.10's TestClient prefers; with httpx alone the tests still pass but print a StarletteDeprecationWarning. Create this layout: app/__init__.py (empty), app/logging_context.py, app/json_logger.py, app/main.py, tests/test_logging.py and demo.py, then install the packages from the project root. The install pins the tested versions, so your output matches the lab.
mkdir -p logging-lab/app logging-lab/tests && cd logging-lab
touch app/__init__.py
python3 -m venv .venv && . .venv/bin/activate
pip install "fastapi[standard]==0.163.1" pydantic==2.14.3 starlette==1.10.0 \
httpx==0.28.1 httpx2==2.16.2 pytest==9.2.002. Log level discipline in production systems
Agree on levels before writing code. Too much noise fills storage and hides incidents; too little leaves you blind. A common convention:
- DEBUG: detail for local development or a short, deliberate investigation. It is normally off in production, and it is never a place for raw payloads with personal data.
- INFO: business events and state changes ("order ord_88192 placed", "worker started"). Many teams also emit one summary line per request with method, path, status and duration.
- WARNING: something unexpected that the service handled ("retry 2 of 4 to the payments API", "rate limit at 80%").
- ERROR: an operation failed for a request or job ("payment declined by gateway", "transaction rolled back"). An unhandled exception behind a 5xx response should be logged at ERROR with its traceback.
- CRITICAL: the service as a whole cannot work ("primary database unreachable").
03. Step 1: Correlation ID context and ASGI middleware
In async frameworks such as FastAPI, many requests share one thread, so threading.local cannot hold per-request data: when one coroutine awaits, another request runs on the same thread and would see or overwrite the value. contextvars.ContextVar keeps a separate value per task, and asyncio.create_task and asyncio.to_thread copy the current context into the new task or thread.
The middleware accepts an incoming ID only if it is at most 64 characters of ASCII letters, digits and hyphens. A client-supplied value ends up in every log line and in outbound headers, so an unchecked one could inject fake lines or huge strings, and a non-ASCII one would make httpx fail when it copies the ID into an outbound header.
import contextvars
import uuid
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
# One value per request, visible in every coroutine that request awaits
request_id_ctx: contextvars.ContextVar[str] = contextvars.ContextVar(
"request_id",
default="-",
)
class RequestIdMiddleware(BaseHTTPMiddleware):
"""Reuses an incoming X-Request-ID or creates one, and echoes it back."""
async def dispatch(self, request: Request, call_next) -> Response:
incoming = request.headers.get("X-Request-ID", "")
# Accept only short ASCII IDs of letters, digits and hyphens; else make one
simple = incoming.isascii() and incoming.replace("-", "").isalnum()
ok = simple and 0 < len(incoming) <= 64
req_id = incoming if ok else str(uuid.uuid4())
token = request_id_ctx.set(req_id)
try:
response = await call_next(request)
response.headers["X-Request-ID"] = req_id
return response
finally:
request_id_ctx.reset(token)request_id_ctx.reset(token) in the finally block restores the previous value when the request ends, even if the handler raised, so the ID does not leak into whatever runs next in that context. Check that the module imports and that code outside a request sees the default:
python -c "from app.logging_context import request_id_ctx; print(request_id_ctx.get())"-04. Step 2: JSON formatter and redaction safety net
The formatter turns each logging.LogRecord into one JSON line. Three details matter:
- Only your fields are copied. Values passed with
extra=become attributes of the record, next to standard ones such asmsg,args,pathnameandexc_info. Those standard fields are set on each instance, so they do not appear inlogging.LogRecord.__dict__(the class). The formatter therefore buildsRESERVEDfrom a real record and skips those names. - An exception does not break the log line.
exc_infois a tuple that holds a traceback object, whichjson.dumpscannot encode. The formatter writes the formatted traceback to anexceptionfield, anddefault=strturns any other odd value into text instead of raising. - Redaction is a safety net, not a licence. Log chosen fields, never whole payloads or header dictionaries. The
redactfunction catches mistakes: any key that contains a sensitive word (sopayment_tokenandsession_cookiematch), keys inside nested dictionaries and lists, and 13 to 19 digit runs that look like card numbers in strings. It cannot recognise every secret, for example a password inside free text, so it does not make dumping payloads safe.
import json
import logging
import re
import sys
from datetime import datetime, timezone
from app.logging_context import request_id_ctx
# Every attribute a plain LogRecord has; anything else came from extra=
RESERVED = set(vars(logging.LogRecord("", 0, "", 0, "", (), None)))
RESERVED |= {"message", "asctime", "taskName"}
SENSITIVE = (
"password", "secret", "token", "authorization", "api_key", "cookie", "card",
)
CARD_NUMBER = re.compile(r"\b(?:\d[ -]?){12,18}\d\b")
def redact(key: str, value):
if any(word in key.lower() for word in SENSITIVE):
return "[REDACTED]"
if isinstance(value, dict):
return {k: redact(str(k), v) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [redact(key, v) for v in value]
if isinstance(value, str):
return CARD_NUMBER.sub("[REDACTED]", value)
return value
class JsonLogFormatter(logging.Formatter):
"""Formats each record as one line of JSON with the request ID."""
def format(self, record: logging.LogRecord) -> str:
created = datetime.fromtimestamp(record.created, timezone.utc)
log_data = {
"timestamp": created.isoformat(),
"level": record.levelname,
"logger": record.name,
"message": redact("message", record.getMessage()),
"request_id": request_id_ctx.get(),
}
for key, value in vars(record).items():
if key not in RESERVED and not key.startswith("_"):
log_data[key] = redact(key, value)
if record.exc_info:
log_data["exception"] = self.formatException(record.exc_info)
# default=str: an odd value must never make the log line disappear
return json.dumps(log_data, default=str)
def setup_logging(level: str = "INFO") -> None:
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonLogFormatter())
root_logger = logging.getLogger()
root_logger.handlers = [handler]
root_logger.setLevel(level.upper())
# httpx logs every URL at INFO; URLs can carry tokens, so keep it quieter
logging.getLogger("httpx").setLevel("WARNING")python -c "from app.json_logger import redact; \
print(redact('p', {'user': {'password': 'pw'}, 'note': 'card 4111 1111 1111 1111'}))"{'user': {'password': '[REDACTED]'}, 'note': 'card [REDACTED]'}05. Step 3: Request IDs in outbound calls and background jobs
The objective asks for the request ID across the request, its outbound calls and its background jobs. The app below does all three:
- Outbound calls: an httpx
requestevent hook copies the current ID into anX-Request-IDheader, so the payments service can log the same ID. - Background jobs: the job payload carries
request_id, and the job sets the ContextVar at its start and resets it at the end. This is the pattern for real queues such as Celery, RQ or arq, where the job runs in another process that never sees your ContextVar. - Threads: work handed to
loop.run_in_executor()does not copy the context, so logs from that thread show the default-. Useasyncio.to_thread(), which copies it, or pass the ID explicitly.
Note that the route logs product and quantity but never passes payment_token to the logger.
import logging
import os
import httpx
from fastapi import BackgroundTasks, FastAPI
from pydantic import BaseModel
from app.json_logger import setup_logging
from app.logging_context import RequestIdMiddleware, request_id_ctx
setup_logging(os.environ.get("LOG_LEVEL", "INFO"))
logger = logging.getLogger("app.orders")
PAYMENTS_URL = os.environ.get("PAYMENTS_URL", "https://payments.example")
payments_transport = None # tests replace this with httpx.MockTransport
app = FastAPI(title="Checkout API")
app.add_middleware(RequestIdMiddleware)
async def add_request_id(request: httpx.Request) -> None:
# Outbound calls carry the same ID, so the next service can log it too
request.headers["X-Request-ID"] = request_id_ctx.get()
class OrderPayload(BaseModel):
product_id: str
quantity: int
payment_token: str
def send_receipt(job: dict) -> None:
"""Background job: restore the request ID that travelled in the payload."""
token = request_id_ctx.set(job["request_id"])
try:
logging.getLogger("app.worker").info(
"Receipt sent", extra={"order_id": job["order_id"]}
)
finally:
request_id_ctx.reset(token)
@app.post("/v1/orders")
async def create_order(payload: OrderPayload, jobs: BackgroundTasks):
# Log chosen fields only; payment_token is never passed to the logger
logger.info(
"Processing customer order",
extra={"product_id": payload.product_id, "quantity": payload.quantity},
)
# One client per request keeps the lab short; a real service shares one
async with httpx.AsyncClient(
base_url=PAYMENTS_URL,
transport=payments_transport,
event_hooks={"request": [add_request_id]},
) as client:
charge = await client.post("/charges", json={"token": payload.payment_token})
logger.info("Payment authorised", extra={"upstream_status": charge.status_code})
# A real queue works the same way: put the request ID in the job payload
job = {"order_id": "ord_88192", "request_id": request_id_ctx.get()}
jobs.add_task(send_receipt, job)
return {"status": "created", "order_id": "ord_88192"}python -c "from app.main import app; print(sorted(r.path for r in app.routes))"['/docs', '/docs/oauth2-redirect', '/openapi.json', '/redoc', '/v1/orders']06. Step 4: Verify with pytest and a demo run
Run the tests with python -m pytest from the project root. The tests use capsys, which captures what the handler writes to stdout. pytest's caplog would bypass your formatter, so it cannot show that the JSON is right. Each test calls setup_logging() first, so the handler writes to the stdout that capsys has just replaced. An httpx.MockTransport stands in for the payments service and records the headers it receives.
import json
import logging
import httpx
import pytest
from fastapi.testclient import TestClient
from app import main
from app.json_logger import setup_logging
@pytest.fixture
def upstream_headers(monkeypatch):
seen = []
def payments(request: httpx.Request) -> httpx.Response:
seen.append(request.headers)
return httpx.Response(201, json={"charge": "ch_1"})
monkeypatch.setattr(main, "payments_transport", httpx.MockTransport(payments))
return seen
def json_lines(capsys):
return [json.loads(line) for line in capsys.readouterr().out.splitlines()]
def test_request_id_reaches_logs_upstream_and_job(capsys, upstream_headers):
setup_logging() # attach the handler to the stdout that capsys captures
body = {"product_id": "prod_4091", "quantity": 2, "payment_token": "tok_live"}
with TestClient(main.app) as client:
resp = client.post(
"/v1/orders", json=body, headers={"X-Request-ID": "test-trace-99"}
)
assert resp.headers["X-Request-ID"] == "test-trace-99"
assert upstream_headers[0]["X-Request-ID"] == "test-trace-99"
logs = [log for log in json_lines(capsys) if log["logger"].startswith("app.")]
assert {log["logger"] for log in logs} == {"app.orders", "app.worker"}
assert {log["request_id"] for log in logs} == {"test-trace-99"}
assert "tok_live" not in json.dumps(logs)
def test_unsafe_client_ids_are_replaced(capsys, upstream_headers):
setup_logging()
body = {"product_id": "p", "quantity": 1, "payment_token": "t"}
with TestClient(main.app) as client:
for bad in ("x\nFAKE LOG LINE", "ê", "a" * 65):
headers = {"X-Request-ID": bad.encode("latin-1")} # raw header bytes
resp = client.post("/v1/orders", json=body, headers=headers)
assert len(resp.headers["X-Request-ID"]) == 36 # a fresh UUID4
def test_nested_secrets_and_card_numbers_are_redacted(capsys):
setup_logging()
logging.getLogger("t").info(
"card 4111 1111 1111 1111 declined",
extra={"payment_token": "tok_1", "payload": {"user": {"password": "pw"}}},
)
(log,) = json_lines(capsys)
assert log["payment_token"] == "[REDACTED]"
assert log["payload"] == {"user": {"password": "[REDACTED]"}}
assert log["message"] == "card [REDACTED] declined"
assert "args" not in log and "pathname" not in log # no LogRecord internals
def test_exception_logs_one_json_line(capsys):
setup_logging()
try:
1 / 0
except ZeroDivisionError:
logging.getLogger("t").exception("Unhandled error")
(log,) = json_lines(capsys)
assert log["level"] == "ERROR"
assert "ZeroDivisionError" in log["exception"]$ python -m pytest -q tests
.... [100%]
4 passed in 0.70sTo see the log lines themselves, run the demo. It captures the JSON lines and pretty-prints them; in production each record is one line on stdout.
import io
import json
import logging
import httpx
from fastapi.testclient import TestClient
from app import main
def payments(request: httpx.Request) -> httpx.Response:
print("upstream saw X-Request-ID:", request.headers["X-Request-ID"])
return httpx.Response(201, json={"charge": "ch_1"})
main.payments_transport = httpx.MockTransport(payments)
captured = io.StringIO()
logging.getLogger().handlers[0].setStream(captured) # keep the JSON lines
body = {"product_id": "prod_4091", "quantity": 2, "payment_token": "tok_live"}
with TestClient(main.app) as client:
resp = client.post("/v1/orders", json=body, headers={"X-Request-ID": "demo-42"})
print("response X-Request-ID:", resp.headers["X-Request-ID"])
for line in captured.getvalue().splitlines():
if not json.loads(line)["logger"].startswith("app."):
continue # skip the test client's own log line
print(json.dumps(json.loads(line), indent=2)) # one JSON line, pretty-printed$ python demo.py
upstream saw X-Request-ID: demo-42
response X-Request-ID: demo-42
{
"timestamp": "2026-10-30T07:58:25.801035+00:00",
"level": "INFO",
"logger": "app.orders",
"message": "Processing customer order",
"request_id": "demo-42",
"product_id": "prod_4091",
"quantity": 2
}
{
"timestamp": "2026-10-30T07:58:25.802314+00:00",
"level": "INFO",
"logger": "app.orders",
"message": "Payment authorised",
"request_id": "demo-42",
"upstream_status": 201
}
{
"timestamp": "2026-10-30T07:58:25.806544+00:00",
"level": "INFO",
"logger": "app.worker",
"message": "Receipt sent",
"request_id": "demo-42",
"order_id": "ord_88192"
}All three app log lines, the upstream request and the background job share demo-42. The order line contains product_id and quantity as separate fields, so a log platform can filter on them directly, and no LogRecord internals such as args or pathname appear.
07. Check your understanding
08. Apply it
Add this setup to the service you are building for the skill project:
- Register the fallback exception handler from the global exception handlers lesson and check that a forced 5xx produces one ERROR line with an
exceptionfield and the request ID. - Forward
X-Request-IDfrom every outbound client you use, not only httpx, and putrequest_idin every queued job. - Add one INFO summary line per request with method, path, status and duration.
- Configure your collector (for example Fluent Bit or Vector) to read stdout and keep each JSON line as one event.
09. Review prompt
Without looking back, explain why threading.local fails in async Python and how a ContextVar fixes it, then name the two places where the request ID must be passed on by hand. Describe what the formatter does with extra fields, with exc_info and with values JSON cannot encode, and explain why redaction does not make it safe to log whole request payloads.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.