Avoid using log filter to modify/enrich log record
See original GitHub issueThe current implementation provides log filter classes which can be used to enrich the log records with correlation IDs. This is a surprising use of a filter since it has a side effect and modifies a log record. For example, when attaching the filter to one handler, another handler may see the modified log record.
According to the documentation (just below https://docs.python.org/3/library/logging.html?highlight=logrecord#logging.LogRecord.getMessage), the intended pattern for custom log record generation is to use a modified log record factory function like this:
old_factory = logging.getLogRecordFactory()
def record_factory(*args, **kwargs):
record = old_factory(*args, **kwargs)
record.custom_attribute = 0xdecafbad
return record
logging.setLogRecordFactory(record_factory)
The only annoying thing here is that this one-off setting of the factory cannot be done using logging.config
.
Short of asking app developers to bootstrap the record factory, manually, there may be an alternative whereby the ASGI middleware could be responsible for this. When using a class-based middleware implementation, the middleware’s __init__()
constructor may be able to set the log record factory?
Issue Analytics
- State:
- Created a year ago
- Comments:11 (11 by maintainers)
I will still find some time to play with the log record factory. Just to see if we can simplify the log setup.
I guess I’m just thinking out loud whether we can do better than the pragmatic approach of wiring up filters like this…