Python 3.2+loggingfunction
logging.setLogRecordFactory()
records and filters
Replaces the factory loggers use to create records. This is how you add your own field to every record, such as a request id.
Syntax
logging.setLogRecordFactory(factory)
The new factory must call the old one from getLogRecordFactory() and return its result: otherwise you drop other people's additions, and returning None breaks every logging call. The setting is global and affects every logger in the process, unlike a LoggerAdapter, which adds context only to its own calls.
Examples
import logging, sys
old = logging.getLogRecordFactory()
def factory(*args, **kwargs):
record = old(*args, **kwargs)
record.app = 'shop'
return record
logging.setLogRecordFactory(factory)
logging.basicConfig(stream=sys.stdout, format='[%(app)s] %(message)s')
logging.warning('старт') # → [shop] старт
See also
Open in the full glossarydocs.python.orgReport an inaccuracy