Files
routesapi/app/core/log_context.py
2026-06-22 17:40:08 +05:30

31 lines
897 B
Python

"""
Per-request logging context.
Carries the request id (the same one `RequestIDMiddleware` puts on the
`X-Request-ID` header) into every log record via a ContextVar + logging.Filter,
so a whole request's log lines can be grepped by one id — essential when
watching the live API.
"""
import contextvars
import logging
# Default "-" so non-request logs (startup, background agents) still format cleanly.
_request_id: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="-")
def set_request_id(request_id: str) -> None:
_request_id.set(request_id or "-")
def get_request_id() -> str:
return _request_id.get()
class RequestIdFilter(logging.Filter):
"""Injects `request_id` onto every LogRecord so the format string can use it."""
def filter(self, record: logging.LogRecord) -> bool:
record.request_id = _request_id.get()
return True