Initial commit
This commit is contained in:
30
app/core/log_context.py
Normal file
30
app/core/log_context.py
Normal file
@@ -0,0 +1,30 @@
|
||||
"""
|
||||
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
|
||||
Reference in New Issue
Block a user