gh-92592: Allow logging filters to return a LogRecord. (GH-92591)

This commit is contained in:
Adrian Garcia Badaracco 2022-06-07 08:53:57 -07:00 committed by GitHub
parent 70690c7233
commit 296081a7ce
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 117 additions and 13 deletions

View file

@ -714,6 +714,32 @@ which, when run, produces something like:
2010-09-06 22:38:15,301 d.e.f DEBUG IP: 123.231.231.123 User: fred A message at DEBUG level with 2 parameters
2010-09-06 22:38:15,301 d.e.f INFO IP: 123.231.231.123 User: fred A message at INFO level with 2 parameters
Imparting contextual information in handlers
--------------------------------------------
Each :class:`~Handler` has its own chain of filters.
If you want to add contextual information to a :class:`LogRecord` without leaking
it to other handlers, you can use a filter that returns
a new :class:`~LogRecord` instead of modifying it in-place, as shown in the following script::
import copy
import logging
def filter(record: logging.LogRecord):
record = copy.copy(record)
record.user = 'jim'
return record
if __name__ == '__main__':
logger = logging.getLogger()
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
formatter = logging.Formatter('%(message)s from %(user)-8s')
handler.setFormatter(formatter)
handler.addFilter(filter)
logger.addHandler(handler)
logger.info('A log message')
.. _multiple-processes: