@@ -30,13 +30,53 @@ is that all Python modules can participate in logging, so your application log
30
30
can include your own messages integrated with messages from third-party
31
31
modules.
32
32
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 *:
34
59
35
60
.. code-block :: none
36
61
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.
40
80
41
81
The module provides a lot of functionality and flexibility. If you are
42
82
unfamiliar with logging, the best way to get to grips with it is to view the
@@ -1138,89 +1178,31 @@ functions.
1138
1178
1139
1179
.. function :: debug(msg, *args, **kwargs)
1140
1180
1141
- Logs a message with level :const: `DEBUG ` on the root logger. The *msg * is the
1142
- message format string, and the *args * are the arguments which are merged into
1143
- *msg * using the string formatting operator. (Note that this means that you can
1144
- use keywords in the format string, together with a single dictionary argument.)
1145
-
1146
- There are three keyword arguments in *kwargs * which are inspected: *exc_info *
1147
- which, if it does not evaluate as false, causes exception information to be
1148
- added to the logging message. If an exception tuple (in the format returned by
1149
- :func: `sys.exc_info `) or an exception instance is provided, it is used;
1150
- otherwise, :func: `sys.exc_info ` is called to get the exception information.
1151
-
1152
- The second optional keyword argument is *stack_info *, which defaults to
1153
- ``False ``. If true, stack information is added to the logging
1154
- message, including the actual logging call. Note that this is not the same
1155
- stack information as that displayed through specifying *exc_info *: The
1156
- former is stack frames from the bottom of the stack up to the logging call
1157
- in the current thread, whereas the latter is information about stack frames
1158
- which have been unwound, following an exception, while searching for
1159
- exception handlers.
1160
-
1161
- You can specify *stack_info * independently of *exc_info *, e.g. to just show
1162
- how you got to a certain point in your code, even when no exceptions were
1163
- raised. The stack frames are printed following a header line which says:
1164
-
1165
- .. code-block :: none
1181
+ This is a convenience function that calls :meth: `Logger.debug `, on the root
1182
+ logger. The handling of the arguments is in every way identical
1183
+ to what is described in that method.
1166
1184
1167
- Stack (most recent call last):
1185
+ The only difference is that if the root logger has no handlers, then
1186
+ :func: `basicConfig ` is called, prior to calling ``debug `` on the root logger.
1168
1187
1169
- This mimics the ``Traceback (most recent call last): `` which is used when
1170
- displaying exception frames.
1188
+ For very short scripts or quick demonstrations of ``logging `` facilities,
1189
+ ``debug `` and the other module-level functions may be convenient. However,
1190
+ most programs will want to carefully and explicitly control the logging
1191
+ configuration, and should therefore prefer creating a module-level logger and
1192
+ calling :meth: `Logger.debug ` (or other level-specific methods) on it, as
1193
+ described at the beginnning of this documentation.
1171
1194
1172
- The third optional keyword argument is *extra * which can be used to pass a
1173
- dictionary which is used to populate the __dict__ of the LogRecord created for
1174
- the logging event with user-defined attributes. These custom attributes can then
1175
- be used as you like. For example, they could be incorporated into logged
1176
- messages. For example::
1177
-
1178
- FORMAT = '%(asctime)s %(clientip)-15s %(user)-8s %(message)s'
1179
- logging.basicConfig(format=FORMAT)
1180
- d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
1181
- logging.warning('Protocol problem: %s', 'connection reset', extra=d)
1182
-
1183
- would print something like:
1184
-
1185
- .. code-block :: none
1186
-
1187
- 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1188
-
1189
- The keys in the dictionary passed in *extra * should not clash with the keys used
1190
- by the logging system. (See the :class: `Formatter ` documentation for more
1191
- information on which keys are used by the logging system.)
1192
-
1193
- If you choose to use these attributes in logged messages, you need to exercise
1194
- some care. In the above example, for instance, the :class: `Formatter ` has been
1195
- set up with a format string which expects 'clientip' and 'user' in the attribute
1196
- dictionary of the LogRecord. If these are missing, the message will not be
1197
- logged because a string formatting exception will occur. So in this case, you
1198
- always need to pass the *extra * dictionary with these keys.
1199
-
1200
- While this might be annoying, this feature is intended for use in specialized
1201
- circumstances, such as multi-threaded servers where the same code executes in
1202
- many contexts, and interesting conditions which arise are dependent on this
1203
- context (such as remote client IP address and authenticated user name, in the
1204
- above example). In such circumstances, it is likely that specialized
1205
- :class: `Formatter `\ s would be used with particular :class: `Handler `\ s.
1206
-
1207
- This function (as well as :func: `info `, :func: `warning `, :func: `error ` and
1208
- :func: `critical `) will call :func: `basicConfig ` if the root logger doesn't
1209
- have any handler attached.
1210
-
1211
- .. versionchanged :: 3.2
1212
- The *stack_info * parameter was added.
1213
1195
1214
1196
.. function :: info(msg, *args, **kwargs)
1215
1197
1216
- Logs a message with level :const: `INFO ` on the root logger. The arguments are
1217
- interpreted as for :func: `debug `.
1198
+ Logs a message with level :const: `INFO ` on the root logger. The arguments and behavior
1199
+ are otherwise the same as for :func: `debug `.
1218
1200
1219
1201
1220
1202
.. function :: warning(msg, *args, **kwargs)
1221
1203
1222
- Logs a message with level :const: `WARNING ` on the root logger. The arguments
1223
- are interpreted as for :func: `debug `.
1204
+ Logs a message with level :const: `WARNING ` on the root logger. The arguments and behavior
1205
+ are otherwise the same as for :func: `debug `.
1224
1206
1225
1207
.. note :: There is an obsolete function ``warn`` which is functionally
1226
1208
identical to ``warning ``. As ``warn `` is deprecated, please do not use
@@ -1229,26 +1211,26 @@ functions.
1229
1211
1230
1212
.. function :: error(msg, *args, **kwargs)
1231
1213
1232
- Logs a message with level :const: `ERROR ` on the root logger. The arguments are
1233
- interpreted as for :func: `debug `.
1214
+ Logs a message with level :const: `ERROR ` on the root logger. The arguments and behavior
1215
+ are otherwise the same as for :func: `debug `.
1234
1216
1235
1217
1236
1218
.. function :: critical(msg, *args, **kwargs)
1237
1219
1238
- Logs a message with level :const: `CRITICAL ` on the root logger. The arguments
1239
- are interpreted as for :func: `debug `.
1220
+ Logs a message with level :const: `CRITICAL ` on the root logger. The arguments and behavior
1221
+ are otherwise the same as for :func: `debug `.
1240
1222
1241
1223
1242
1224
.. function :: exception(msg, *args, **kwargs)
1243
1225
1244
- Logs a message with level :const: `ERROR ` on the root logger. The arguments are
1245
- interpreted as for :func: `debug `. Exception info is added to the logging
1226
+ Logs a message with level :const: `ERROR ` on the root logger. The arguments and behavior
1227
+ are otherwise the same as for :func: `debug `. Exception info is added to the logging
1246
1228
message. This function should only be called from an exception handler.
1247
1229
1248
1230
.. function :: log(level, msg, *args, **kwargs)
1249
1231
1250
- Logs a message with level *level * on the root logger. The other arguments are
1251
- interpreted as for :func: `debug `.
1232
+ Logs a message with level *level * on the root logger. The arguments and behavior
1233
+ are otherwise the same as for :func: `debug `.
1252
1234
1253
1235
.. function :: disable(level=CRITICAL)
1254
1236
0 commit comments