diff --git a/Doc/library/logging.rst b/Doc/library/logging.rst index 6985f5251a0..800ad62b615 100644 --- a/Doc/library/logging.rst +++ b/Doc/library/logging.rst @@ -1137,6 +1137,52 @@ This example uses console and file handlers, but you can use any number and combination of handlers you choose. +.. _context-info: + +Adding contextual information to your logging output +---------------------------------------------------- + +Sometimes you want logging output to contain contextual information in +addition to the parameters passed to the logging call. For example, in a +networked application, it may be desirable to log client-specific information +in the log (e.g. remote client's username, or IP address). Although you could +use the *extra* parameter to achieve this, it's not always convenient to pass +the information in this way. While it might be tempting to create +:class:`Logger` instances on a per-connection basis, this is not a good idea +because these instances are not garbage collected. While this is not a problem +in practice, when the number of :class:`Logger` instances is dependent on the +level of granularity you want to use in logging an application, it could +be hard to manage if the number of :class:`Logger` instances becomes +effectively unbounded. + +There are a number of other ways you can pass contextual information to be +output along with logging event information. + +* Use an adapter class which has access to the contextual information and + which defines methods :meth:`debug`, :meth:`info` etc. with the same + signatures as used by :class:`Logger`. You instantiate the adapter with a + name, which will be used to create an underlying :class:`Logger` with that + name. In each adpater method, the passed-in message is modified to include + whatever contextual information you want. + +* Use something other than a string to pass the message. Although normally + the first argument to a logger method such as :meth:`debug`, :meth:`info` + etc. is usually a string, it can in fact be any object. This object is the + argument to a :func:`str()` call which is made, in + :meth:`LogRecord.getMessage`, to obtain the actual message string. You can + use this behavior to pass an instance which may be initialized with a + logging message, which redefines :meth:__str__ to return a modified version + of that message with the contextual information added. + +* Use a specialized :class:`Formatter` subclass to add additional information + to the formatted output. The subclass could, for instance, merge some thread + local contextual information (or contextual information obtained in some + other way) with the output generated by the base :class:`Formatter`. + +In each of these three approaches, thread locals can sometimes be a useful way +of passing contextual information without undue coupling between different +parts of your code. + .. _network-logging: Sending and receiving logging events across a network