Advertisement
Intermediate Python, Logging

How do you include structured context (like a request ID) in every log message using LoggerAdapter or extra?

Short answer

The extra parameter passes custom key-value data into a LogRecord for use in a custom Formatter string, while LoggerAdapter wraps a logger to automatically inject the same contextual data (e.g., request_id, user_id) into every call without repeating extra= at each call site --…

Save Python mock interview
Advertisement
AModel answer
The extra parameter passes custom key-value data into a LogRecord for use in a custom Formatter string, while LoggerAdapter wraps a logger to automatically inject the same contextual data (e.g., request_id, user_id) into every call without repeating extra= at each call site -- useful for correlating logs across a single request's lifecycle.
import logging

logger = logging.getLogger('app')
adapter = logging.LoggerAdapter(logger, {'request_id': 'abc-123'})
adapter.info('Processing request')  # includes request_id in every call automatically
Real-world example
A web API creates a LoggerAdapter per incoming request carrying its unique request_id, so every log line during that request's handling can be filtered and correlated in log aggregation tools.
Likely follow-ups
  • How does extra interact with reserved LogRecord attribute names?
  • What's the alternative using contextvars for async code?
Related topics