Skip to content

Commit 039fd9e

Browse files
[3.11] gh-98731: Improvements to the logging documentation (GH-101618) (GH-116733)
(cherry picked from commit 7f418fb)
1 parent f292b07 commit 039fd9e

File tree

2 files changed

+108
-162
lines changed

2 files changed

+108
-162
lines changed

Doc/howto/logging.rst

Lines changed: 41 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,12 @@ or *severity*.
2222
When to use logging
2323
^^^^^^^^^^^^^^^^^^^
2424

25-
Logging provides a set of convenience functions for simple logging usage. These
26-
are :func:`debug`, :func:`info`, :func:`warning`, :func:`error` and
27-
:func:`critical`. To determine when to use logging, see the table below, which
28-
states, for each of a set of common tasks, the best tool to use for it.
25+
You can access logging functionality by creating a logger via ``logger =
26+
getLogger(__name__)``, and then calling the logger's :meth:`~Logger.debug`,
27+
:meth:`~Logger.info`, :meth:`~Logger.warning`, :meth:`~Logger.error` and
28+
:meth:`~Logger.critical` methods. To determine when to use logging, and to see
29+
which logger methods to use when, see the table below. It states, for each of a
30+
set of common tasks, the best tool to use for that task.
2931

3032
+-------------------------------------+--------------------------------------+
3133
| Task you want to perform | The best tool for the task |
@@ -34,8 +36,8 @@ states, for each of a set of common tasks, the best tool to use for it.
3436
| usage of a command line script or | |
3537
| program | |
3638
+-------------------------------------+--------------------------------------+
37-
| Report events that occur during | :func:`logging.info` (or |
38-
| normal operation of a program (e.g. | :func:`logging.debug` for very |
39+
| Report events that occur during | A logger's :meth:`~Logger.info` (or |
40+
| normal operation of a program (e.g. | :meth:`~Logger.debug` method for very|
3941
| for status monitoring or fault | detailed output for diagnostic |
4042
| investigation) | purposes) |
4143
+-------------------------------------+--------------------------------------+
@@ -44,22 +46,23 @@ states, for each of a set of common tasks, the best tool to use for it.
4446
| | the client application should be |
4547
| | modified to eliminate the warning |
4648
| | |
47-
| | :func:`logging.warning` if there is |
48-
| | nothing the client application can do|
49-
| | about the situation, but the event |
50-
| | should still be noted |
49+
| | A logger's :meth:`~Logger.warning` |
50+
| | method if there is nothing the client|
51+
| | application can do about the |
52+
| | situation, but the event should still|
53+
| | be noted |
5154
+-------------------------------------+--------------------------------------+
5255
| Report an error regarding a | Raise an exception |
5356
| particular runtime event | |
5457
+-------------------------------------+--------------------------------------+
55-
| Report suppression of an error | :func:`logging.error`, |
56-
| without raising an exception (e.g. | :func:`logging.exception` or |
57-
| error handler in a long-running | :func:`logging.critical` as |
58+
| Report suppression of an error | A logger's :meth:`~Logger.error`, |
59+
| without raising an exception (e.g. | :meth:`~Logger.exception` or |
60+
| error handler in a long-running | :meth:`~Logger.critical` method as |
5861
| server process) | appropriate for the specific error |
5962
| | and application domain |
6063
+-------------------------------------+--------------------------------------+
6164

62-
The logging functions are named after the level or severity of the events
65+
The logger methods are named after the level or severity of the events
6366
they are used to track. The standard levels and their applicability are
6467
described below (in increasing order of severity):
6568

@@ -113,12 +116,18 @@ If you type these lines into a script and run it, you'll see:
113116
WARNING:root:Watch out!
114117
115118
printed out on the console. The ``INFO`` message doesn't appear because the
116-
default level is ``WARNING``. The printed message includes the indication of
117-
the level and the description of the event provided in the logging call, i.e.
118-
'Watch out!'. Don't worry about the 'root' part for now: it will be explained
119-
later. The actual output can be formatted quite flexibly if you need that;
120-
formatting options will also be explained later.
121-
119+
default level is ``WARNING``. The printed message includes the indication of the
120+
level and the description of the event provided in the logging call, i.e.
121+
'Watch out!'. The actual output can be formatted quite flexibly if you need
122+
that; formatting options will also be explained later.
123+
124+
Notice that in this example, we use functions directly on the ``logging``
125+
module, like ``logging.debug``, rather than creating a logger and calling
126+
functions on it. These functions operation on the root logger, but can be useful
127+
as they will call :func:`~logging.basicConfig` for you if it has not been called yet, like in
128+
this example. In larger programs you'll usually want to control the logging
129+
configuration explicitly however - so for that reason as well as others, it's
130+
better to create loggers and call their methods.
122131

123132
Logging to a file
124133
^^^^^^^^^^^^^^^^^
@@ -128,11 +137,12 @@ look at that next. Be sure to try the following in a newly started Python
128137
interpreter, and don't just continue from the session described above::
129138

130139
import logging
140+
logger = logging.getLogger(__name__)
131141
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
132-
logging.debug('This message should go to the log file')
133-
logging.info('So should this')
134-
logging.warning('And this, too')
135-
logging.error('And non-ASCII stuff, too, like Øresund and Malmö')
142+
logger.debug('This message should go to the log file')
143+
logger.info('So should this')
144+
logger.warning('And this, too')
145+
logger.error('And non-ASCII stuff, too, like Øresund and Malmö')
136146

137147
.. versionchanged:: 3.9
138148
The *encoding* argument was added. In earlier Python versions, or if not
@@ -146,10 +156,10 @@ messages:
146156

147157
.. code-block:: none
148158
149-
DEBUG:root:This message should go to the log file
150-
INFO:root:So should this
151-
WARNING:root:And this, too
152-
ERROR:root:And non-ASCII stuff, too, like Øresund and Malmö
159+
DEBUG:__main__:This message should go to the log file
160+
INFO:__main__:So should this
161+
WARNING:__main__:And this, too
162+
ERROR:__main__:And non-ASCII stuff, too, like Øresund and Malmö
153163
154164
This example also shows how you can set the logging level which acts as the
155165
threshold for tracking. In this case, because we set the threshold to
@@ -178,11 +188,9 @@ following example::
178188
raise ValueError('Invalid log level: %s' % loglevel)
179189
logging.basicConfig(level=numeric_level, ...)
180190

181-
The call to :func:`basicConfig` should come *before* any calls to
182-
:func:`debug`, :func:`info`, etc. Otherwise, those functions will call
183-
:func:`basicConfig` for you with the default options. As it's intended as a
184-
one-off simple configuration facility, only the first call will actually do
185-
anything: subsequent calls are effectively no-ops.
191+
The call to :func:`basicConfig` should come *before* any calls to a logger's
192+
methods such as :meth:`~Logger.debug`, :meth:`~Logger.info`, etc. Otherwise,
193+
that logging event may not be handled in the desired manner.
186194

187195
If you run the above script several times, the messages from successive runs
188196
are appended to the file *example.log*. If you want each run to start afresh,
@@ -195,50 +203,6 @@ The output will be the same as before, but the log file is no longer appended
195203
to, so the messages from earlier runs are lost.
196204

197205

198-
Logging from multiple modules
199-
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
200-
201-
If your program consists of multiple modules, here's an example of how you
202-
could organize logging in it::
203-
204-
# myapp.py
205-
import logging
206-
import mylib
207-
208-
def main():
209-
logging.basicConfig(filename='myapp.log', level=logging.INFO)
210-
logging.info('Started')
211-
mylib.do_something()
212-
logging.info('Finished')
213-
214-
if __name__ == '__main__':
215-
main()
216-
217-
::
218-
219-
# mylib.py
220-
import logging
221-
222-
def do_something():
223-
logging.info('Doing something')
224-
225-
If you run *myapp.py*, you should see this in *myapp.log*:
226-
227-
.. code-block:: none
228-
229-
INFO:root:Started
230-
INFO:root:Doing something
231-
INFO:root:Finished
232-
233-
which is hopefully what you were expecting to see. You can generalize this to
234-
multiple modules, using the pattern in *mylib.py*. Note that for this simple
235-
usage pattern, you won't know, by looking in the log file, *where* in your
236-
application your messages came from, apart from looking at the event
237-
description. If you want to track the location of your messages, you'll need
238-
to refer to the documentation beyond the tutorial level -- see
239-
:ref:`logging-advanced-tutorial`.
240-
241-
242206
Logging variable data
243207
^^^^^^^^^^^^^^^^^^^^^
244208

Doc/library/logging.rst

Lines changed: 67 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,53 @@ is that all Python modules can participate in logging, so your application log
3030
can include your own messages integrated with messages from third-party
3131
modules.
3232

33-
The simplest example:
33+
Here's a simple example of idiomatic usage: ::
34+
35+
# myapp.py
36+
import logging
37+
import mylib
38+
logger = logging.getLogger(__name__)
39+
40+
def main():
41+
logging.basicConfig(filename='myapp.log', level=logging.INFO)
42+
logger.info('Started')
43+
mylib.do_something()
44+
logger.info('Finished')
45+
46+
if __name__ == '__main__':
47+
main()
48+
49+
::
50+
51+
# mylib.py
52+
import logging
53+
logger = logging.getLogger(__name__)
54+
55+
def do_something():
56+
logger.info('Doing something')
57+
58+
If you run *myapp.py*, you should see this in *myapp.log*:
3459

3560
.. code-block:: none
3661
37-
>>> import logging
38-
>>> logging.warning('Watch out!')
39-
WARNING:root:Watch out!
62+
INFO:__main__:Started
63+
INFO:mylib:Doing something
64+
INFO:__main__:Finished
65+
66+
The key features of this idiomatic usage is that the majority of code is simply
67+
creating a module level logger with ``getLogger(__name__)``, and using that
68+
logger to do any needed logging. This is concise while allowing downstream code
69+
fine grained control if needed. Logged messages to the module-level logger get
70+
forwarded up to handlers of loggers in higher-level modules, all the way up to
71+
the root logger; for this reason this approach is known as hierarchical logging.
72+
73+
For logging to be useful, it needs to be configured: setting the levels and
74+
destinations for each logger, potentially changing how specific modules log,
75+
often based on command-line arguments or application configuration. In most
76+
cases, like the one above, only the root logger needs to be so configured, since
77+
all the lower level loggers at module level eventually forward their messages to
78+
its handlers. :func:`~logging.basicConfig` provides a quick way to configure
79+
the root logger that handles many use cases.
4080

4181
The module provides a lot of functionality and flexibility. If you are
4282
unfamiliar with logging, the best way to get to grips with it is to view the
@@ -1117,89 +1157,31 @@ functions.
11171157

11181158
.. function:: debug(msg, *args, **kwargs)
11191159

1120-
Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
1121-
message format string, and the *args* are the arguments which are merged into
1122-
*msg* using the string formatting operator. (Note that this means that you can
1123-
use keywords in the format string, together with a single dictionary argument.)
1124-
1125-
There are three keyword arguments in *kwargs* which are inspected: *exc_info*
1126-
which, if it does not evaluate as false, causes exception information to be
1127-
added to the logging message. If an exception tuple (in the format returned by
1128-
:func:`sys.exc_info`) or an exception instance is provided, it is used;
1129-
otherwise, :func:`sys.exc_info` is called to get the exception information.
1130-
1131-
The second optional keyword argument is *stack_info*, which defaults to
1132-
``False``. If true, stack information is added to the logging
1133-
message, including the actual logging call. Note that this is not the same
1134-
stack information as that displayed through specifying *exc_info*: The
1135-
former is stack frames from the bottom of the stack up to the logging call
1136-
in the current thread, whereas the latter is information about stack frames
1137-
which have been unwound, following an exception, while searching for
1138-
exception handlers.
1139-
1140-
You can specify *stack_info* independently of *exc_info*, e.g. to just show
1141-
how you got to a certain point in your code, even when no exceptions were
1142-
raised. The stack frames are printed following a header line which says:
1143-
1144-
.. code-block:: none
1160+
This is a convenience function that calls :meth:`Logger.debug`, on the root
1161+
logger. The handling of the arguments is in every way identical
1162+
to what is described in that method.
11451163

1146-
Stack (most recent call last):
1164+
The only difference is that if the root logger has no handlers, then
1165+
:func:`basicConfig` is called, prior to calling ``debug`` on the root logger.
11471166

1148-
This mimics the ``Traceback (most recent call last):`` which is used when
1149-
displaying exception frames.
1167+
For very short scripts or quick demonstrations of ``logging`` facilities,
1168+
``debug`` and the other module-level functions may be convenient. However,
1169+
most programs will want to carefully and explicitly control the logging
1170+
configuration, and should therefore prefer creating a module-level logger and
1171+
calling :meth:`Logger.debug` (or other level-specific methods) on it, as
1172+
described at the beginnning of this documentation.
11501173

1151-
The third optional keyword argument is *extra* which can be used to pass a
1152-
dictionary which is used to populate the __dict__ of the LogRecord created for
1153-
the logging event with user-defined attributes. These custom attributes can then
1154-
be used as you like. For example, they could be incorporated into logged
1155-
messages. For example::
1156-
1157-
FORMAT = '%(asctime)s %(clientip)-15s %(user)-8s %(message)s'
1158-
logging.basicConfig(format=FORMAT)
1159-
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
1160-
logging.warning('Protocol problem: %s', 'connection reset', extra=d)
1161-
1162-
would print something like:
1163-
1164-
.. code-block:: none
1165-
1166-
2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1167-
1168-
The keys in the dictionary passed in *extra* should not clash with the keys used
1169-
by the logging system. (See the :class:`Formatter` documentation for more
1170-
information on which keys are used by the logging system.)
1171-
1172-
If you choose to use these attributes in logged messages, you need to exercise
1173-
some care. In the above example, for instance, the :class:`Formatter` has been
1174-
set up with a format string which expects 'clientip' and 'user' in the attribute
1175-
dictionary of the LogRecord. If these are missing, the message will not be
1176-
logged because a string formatting exception will occur. So in this case, you
1177-
always need to pass the *extra* dictionary with these keys.
1178-
1179-
While this might be annoying, this feature is intended for use in specialized
1180-
circumstances, such as multi-threaded servers where the same code executes in
1181-
many contexts, and interesting conditions which arise are dependent on this
1182-
context (such as remote client IP address and authenticated user name, in the
1183-
above example). In such circumstances, it is likely that specialized
1184-
:class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1185-
1186-
This function (as well as :func:`info`, :func:`warning`, :func:`error` and
1187-
:func:`critical`) will call :func:`basicConfig` if the root logger doesn't
1188-
have any handler attached.
1189-
1190-
.. versionchanged:: 3.2
1191-
The *stack_info* parameter was added.
11921174

11931175
.. function:: info(msg, *args, **kwargs)
11941176

1195-
Logs a message with level :const:`INFO` on the root logger. The arguments are
1196-
interpreted as for :func:`debug`.
1177+
Logs a message with level :const:`INFO` on the root logger. The arguments and behavior
1178+
are otherwise the same as for :func:`debug`.
11971179

11981180

11991181
.. function:: warning(msg, *args, **kwargs)
12001182

1201-
Logs a message with level :const:`WARNING` on the root logger. The arguments
1202-
are interpreted as for :func:`debug`.
1183+
Logs a message with level :const:`WARNING` on the root logger. The arguments and behavior
1184+
are otherwise the same as for :func:`debug`.
12031185

12041186
.. note:: There is an obsolete function ``warn`` which is functionally
12051187
identical to ``warning``. As ``warn`` is deprecated, please do not use
@@ -1208,26 +1190,26 @@ functions.
12081190

12091191
.. function:: error(msg, *args, **kwargs)
12101192

1211-
Logs a message with level :const:`ERROR` on the root logger. The arguments are
1212-
interpreted as for :func:`debug`.
1193+
Logs a message with level :const:`ERROR` on the root logger. The arguments and behavior
1194+
are otherwise the same as for :func:`debug`.
12131195

12141196

12151197
.. function:: critical(msg, *args, **kwargs)
12161198

1217-
Logs a message with level :const:`CRITICAL` on the root logger. The arguments
1218-
are interpreted as for :func:`debug`.
1199+
Logs a message with level :const:`CRITICAL` on the root logger. The arguments and behavior
1200+
are otherwise the same as for :func:`debug`.
12191201

12201202

12211203
.. function:: exception(msg, *args, **kwargs)
12221204

1223-
Logs a message with level :const:`ERROR` on the root logger. The arguments are
1224-
interpreted as for :func:`debug`. Exception info is added to the logging
1205+
Logs a message with level :const:`ERROR` on the root logger. The arguments and behavior
1206+
are otherwise the same as for :func:`debug`. Exception info is added to the logging
12251207
message. This function should only be called from an exception handler.
12261208

12271209
.. function:: log(level, msg, *args, **kwargs)
12281210

1229-
Logs a message with level *level* on the root logger. The other arguments are
1230-
interpreted as for :func:`debug`.
1211+
Logs a message with level *level* on the root logger. The arguments and behavior
1212+
are otherwise the same as for :func:`debug`.
12311213

12321214
.. function:: disable(level=CRITICAL)
12331215

0 commit comments

Comments
 (0)