all Python 3loggingterm
logging.LoggerAdapter
loggers
A wrapper around a logger that adds context to every record, such as a request id or a user name.
Syntax
adapter = logging.LoggerAdapter(logger, extra=None, merge_extra=False)
The adapter's extra becomes attributes of the record but does not appear in the line by itself: name it in the format, e.g. %(user)s. By default the adapter's extra fully replaces any extra passed to the call, which is silently lost; merge_extra=True (3.13+) merges them. To put the context into the message text itself, override process().
Examples
import logging, sys
h = logging.StreamHandler(sys.stdout)
h.setFormatter(logging.Formatter('[%(user)s] %(message)s'))
base = logging.getLogger('web')
base.addHandler(h)
log = logging.LoggerAdapter(base, {'user': 'anna'})
log.warning('вошла') # → [anna] вошла
log.warning('чужой', extra={'user': 'bob'}) # → [anna] чужой
# Python 3.13+
import logging, sys
h = logging.StreamHandler(sys.stdout)
h.setFormatter(logging.Formatter('%(user)s/%(req)s %(message)s'))
base = logging.getLogger('api')
base.addHandler(h)
log = logging.LoggerAdapter(base, {'user': 'anna'}, merge_extra=True)
log.warning('ok', extra={'req': 7}) # → anna/7 ok
See also
Open in the full glossarydocs.python.orgReport an inaccuracy