mirror of
https://github.com/python/cpython.git
synced 2025-11-02 03:01:58 +00:00
gh-92592: Allow logging filters to return a LogRecord. (GH-92591)
This commit is contained in:
parent
70690c7233
commit
296081a7ce
5 changed files with 117 additions and 13 deletions
|
|
@ -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:
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue