summaryrefslogtreecommitdiffstats
path: root/Doc/howto
diff options
context:
space:
mode:
authorAdrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>2022-06-07 15:53:57 (GMT)
committerGitHub <noreply@github.com>2022-06-07 15:53:57 (GMT)
commit296081a7cedc032232efc823b7b238710677a9df (patch)
treed1e55ace6a60e2448da199451e1d7368bdabf2f2 /Doc/howto
parent70690c7233aaad4431660a64daef81b5220e2ac1 (diff)
downloadcpython-296081a7cedc032232efc823b7b238710677a9df.zip
cpython-296081a7cedc032232efc823b7b238710677a9df.tar.gz
cpython-296081a7cedc032232efc823b7b238710677a9df.tar.bz2
gh-92592: Allow logging filters to return a LogRecord. (GH-92591)
Diffstat (limited to 'Doc/howto')
-rw-r--r--Doc/howto/logging-cookbook.rst26
1 files changed, 26 insertions, 0 deletions
diff --git a/Doc/howto/logging-cookbook.rst b/Doc/howto/logging-cookbook.rst
index 2b5eb8f..8b42383 100644
--- a/Doc/howto/logging-cookbook.rst
+++ b/Doc/howto/logging-cookbook.rst
@@ -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: