summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Flogging.html
blob: a2f97d3bb870ff9f57b7dbc7e555d7e340498455 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
 <span id="logging-logging-facility-for-python"></span><h1>logging — Logging facility for Python</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/logging/__init__.py">Lib/logging/__init__.py</a></p> <aside class="sidebar" id="index-0"> <p class="sidebar-title">Important</p> <p>This page contains the API reference information. For tutorial information and discussion of more advanced topics, see</p> <ul class="simple"> <li><a class="reference internal" href="../howto/logging#logging-basic-tutorial"><span class="std std-ref">Basic Tutorial</span></a></li> <li><a class="reference internal" href="../howto/logging#logging-advanced-tutorial"><span class="std std-ref">Advanced Tutorial</span></a></li> <li><a class="reference internal" href="../howto/logging-cookbook#logging-cookbook"><span class="std std-ref">Logging Cookbook</span></a></li> </ul> </aside>  <p>This module defines functions and classes which implement a flexible event logging system for applications and libraries.</p> <p>The key benefit of having the logging API provided by a standard library module is that all Python modules can participate in logging, so your application log can include your own messages integrated with messages from third-party modules.</p> <p>The simplest example:</p> <pre data-language="none">&gt;&gt;&gt; import logging
&gt;&gt;&gt; logging.warning('Watch out!')
WARNING:root:Watch out!
</pre> <p>The module provides a lot of functionality and flexibility. If you are unfamiliar with logging, the best way to get to grips with it is to view the tutorials (<strong>see the links above and on the right</strong>).</p> <p>The basic classes defined by the module, together with their functions, are listed below.</p> <ul class="simple"> <li>Loggers expose the interface that application code directly uses.</li> <li>Handlers send the log records (created by loggers) to the appropriate destination.</li> <li>Filters provide a finer grained facility for determining which log records to output.</li> <li>Formatters specify the layout of log records in the final output.</li> </ul> <section id="logger-objects"> <span id="logger"></span><h2>Logger Objects</h2> <p>Loggers have the following attributes and methods. Note that Loggers should <em>NEVER</em> be instantiated directly, but always through the module-level function <code>logging.getLogger(name)</code>. Multiple calls to <a class="reference internal" href="#logging.getLogger" title="logging.getLogger"><code>getLogger()</code></a> with the same name will always return a reference to the same Logger object.</p> <p>The <code>name</code> is potentially a period-separated hierarchical value, like <code>foo.bar.baz</code> (though it could also be just plain <code>foo</code>, for example). Loggers that are further down in the hierarchical list are children of loggers higher up in the list. For example, given a logger with a name of <code>foo</code>, loggers with names of <code>foo.bar</code>, <code>foo.bar.baz</code>, and <code>foo.bam</code> are all descendants of <code>foo</code>. The logger name hierarchy is analogous to the Python package hierarchy, and identical to it if you organise your loggers on a per-module basis using the recommended construction <code>logging.getLogger(__name__)</code>. That’s because in a module, <code>__name__</code> is the module’s name in the Python package namespace.</p> <dl class="py class"> <dt class="sig sig-object py" id="logging.Logger">
<code>class logging.Logger</code> </dt> <dd>
<dl class="py attribute"> <dt class="sig sig-object py" id="logging.Logger.propagate">
<code>propagate</code> </dt> <dd>
<p>If this attribute evaluates to true, events logged to this logger will be passed to the handlers of higher level (ancestor) loggers, in addition to any handlers attached to this logger. Messages are passed directly to the ancestor loggers’ handlers - neither the level nor filters of the ancestor loggers in question are considered.</p> <p>If this evaluates to false, logging messages are not passed to the handlers of ancestor loggers.</p> <p>Spelling it out with an example: If the propagate attribute of the logger named <code>A.B.C</code> evaluates to true, any event logged to <code>A.B.C</code> via a method call such as <code>logging.getLogger('A.B.C').error(...)</code> will [subject to passing that logger’s level and filter settings] be passed in turn to any handlers attached to loggers named <code>A.B</code>, <code>A</code> and the root logger, after first being passed to any handlers attached to <code>A.B.C</code>. If any logger in the chain <code>A.B.C</code>, <code>A.B</code>, <code>A</code> has its <code>propagate</code> attribute set to false, then that is the last logger whose handlers are offered the event to handle, and propagation stops at that point.</p> <p>The constructor sets this attribute to <code>True</code>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>If you attach a handler to a logger <em>and</em> one or more of its ancestors, it may emit the same record multiple times. In general, you should not need to attach a handler to more than one logger - if you just attach it to the appropriate logger which is highest in the logger hierarchy, then it will see all events logged by all descendant loggers, provided that their propagate setting is left set to <code>True</code>. A common scenario is to attach handlers only to the root logger, and to let propagation take care of the rest.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.setLevel">
<code>setLevel(level)</code> </dt> <dd>
<p>Sets the threshold for this logger to <em>level</em>. Logging messages which are less severe than <em>level</em> will be ignored; logging messages which have severity <em>level</em> or higher will be emitted by whichever handler or handlers service this logger, unless a handler’s level has been set to a higher severity level than <em>level</em>.</p> <p>When a logger is created, the level is set to <a class="reference internal" href="#logging.NOTSET" title="logging.NOTSET"><code>NOTSET</code></a> (which causes all messages to be processed when the logger is the root logger, or delegation to the parent when the logger is a non-root logger). Note that the root logger is created with level <a class="reference internal" href="#logging.WARNING" title="logging.WARNING"><code>WARNING</code></a>.</p> <p>The term ‘delegation to the parent’ means that if a logger has a level of NOTSET, its chain of ancestor loggers is traversed until either an ancestor with a level other than NOTSET is found, or the root is reached.</p> <p>If an ancestor is found with a level other than NOTSET, then that ancestor’s level is treated as the effective level of the logger where the ancestor search began, and is used to determine how a logging event is handled.</p> <p>If the root is reached, and it has a level of NOTSET, then all messages will be processed. Otherwise, the root’s level will be used as the effective level.</p> <p>See <a class="reference internal" href="#levels"><span class="std std-ref">Logging Levels</span></a> for a list of levels.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>The <em>level</em> parameter now accepts a string representation of the level such as ‘INFO’ as an alternative to the integer constants such as <a class="reference internal" href="#logging.INFO" title="logging.INFO"><code>INFO</code></a>. Note, however, that levels are internally stored as integers, and methods such as e.g. <a class="reference internal" href="#logging.Logger.getEffectiveLevel" title="logging.Logger.getEffectiveLevel"><code>getEffectiveLevel()</code></a> and <a class="reference internal" href="#logging.Logger.isEnabledFor" title="logging.Logger.isEnabledFor"><code>isEnabledFor()</code></a> will return/expect to be passed integers.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.isEnabledFor">
<code>isEnabledFor(level)</code> </dt> <dd>
<p>Indicates if a message of severity <em>level</em> would be processed by this logger. This method checks first the module-level level set by <code>logging.disable(level)</code> and then the logger’s effective level as determined by <a class="reference internal" href="#logging.Logger.getEffectiveLevel" title="logging.Logger.getEffectiveLevel"><code>getEffectiveLevel()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.getEffectiveLevel">
<code>getEffectiveLevel()</code> </dt> <dd>
<p>Indicates the effective level for this logger. If a value other than <a class="reference internal" href="#logging.NOTSET" title="logging.NOTSET"><code>NOTSET</code></a> has been set using <a class="reference internal" href="#logging.Logger.setLevel" title="logging.Logger.setLevel"><code>setLevel()</code></a>, it is returned. Otherwise, the hierarchy is traversed towards the root until a value other than <a class="reference internal" href="#logging.NOTSET" title="logging.NOTSET"><code>NOTSET</code></a> is found, and that value is returned. The value returned is an integer, typically one of <a class="reference internal" href="#logging.DEBUG" title="logging.DEBUG"><code>logging.DEBUG</code></a>, <a class="reference internal" href="#logging.INFO" title="logging.INFO"><code>logging.INFO</code></a> etc.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.getChild">
<code>getChild(suffix)</code> </dt> <dd>
<p>Returns a logger which is a descendant to this logger, as determined by the suffix. Thus, <code>logging.getLogger('abc').getChild('def.ghi')</code> would return the same logger as would be returned by <code>logging.getLogger('abc.def.ghi')</code>. This is a convenience method, useful when the parent logger is named using e.g. <code>__name__</code> rather than a literal string.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.getChildren">
<code>getChildren()</code> </dt> <dd>
<p>Returns a set of loggers which are immediate children of this logger. So for example <code>logging.getLogger().getChildren()</code> might return a set containing loggers named <code>foo</code> and <code>bar</code>, but a logger named <code>foo.bar</code> wouldn’t be included in the set. Likewise, <code>logging.getLogger('foo').getChildren()</code> might return a set including a logger named <code>foo.bar</code>, but it wouldn’t include one named <code>foo.bar.baz</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.debug">
<code>debug(msg, *args, **kwargs)</code> </dt> <dd>
<p>Logs a message with level <a class="reference internal" href="#logging.DEBUG" title="logging.DEBUG"><code>DEBUG</code></a> on this logger. The <em>msg</em> is the message format string, and the <em>args</em> are the arguments which are merged into <em>msg</em> using the string formatting operator. (Note that this means that you can use keywords in the format string, together with a single dictionary argument.) No % formatting operation is performed on <em>msg</em> when no <em>args</em> are supplied.</p> <p>There are four keyword arguments in <em>kwargs</em> which are inspected: <em>exc_info</em>, <em>stack_info</em>, <em>stacklevel</em> and <em>extra</em>.</p> <p>If <em>exc_info</em> does not evaluate as false, it causes exception information to be added to the logging message. If an exception tuple (in the format returned by <a class="reference internal" href="sys#sys.exc_info" title="sys.exc_info"><code>sys.exc_info()</code></a>) or an exception instance is provided, it is used; otherwise, <a class="reference internal" href="sys#sys.exc_info" title="sys.exc_info"><code>sys.exc_info()</code></a> is called to get the exception information.</p> <p>The second optional keyword argument is <em>stack_info</em>, which defaults to <code>False</code>. If true, stack information is added to the logging message, including the actual logging call. Note that this is not the same stack information as that displayed through specifying <em>exc_info</em>: The former is stack frames from the bottom of the stack up to the logging call in the current thread, whereas the latter is information about stack frames which have been unwound, following an exception, while searching for exception handlers.</p> <p>You can specify <em>stack_info</em> independently of <em>exc_info</em>, e.g. to just show how you got to a certain point in your code, even when no exceptions were raised. The stack frames are printed following a header line which says:</p> <pre data-language="none">Stack (most recent call last):
</pre> <p>This mimics the <code>Traceback (most recent call last):</code> which is used when displaying exception frames.</p> <p>The third optional keyword argument is <em>stacklevel</em>, which defaults to <code>1</code>. If greater than 1, the corresponding number of stack frames are skipped when computing the line number and function name set in the <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> created for the logging event. This can be used in logging helpers so that the function name, filename and line number recorded are not the information for the helper function/method, but rather its caller. The name of this parameter mirrors the equivalent one in the <a class="reference internal" href="warnings#module-warnings" title="warnings: Issue warning messages and control their disposition."><code>warnings</code></a> module.</p> <p>The fourth keyword argument is <em>extra</em> which can be used to pass a dictionary which is used to populate the __dict__ of the <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> created for the logging event with user-defined attributes. These custom attributes can then be used as you like. For example, they could be incorporated into logged messages. For example:</p> <pre data-language="python">FORMAT = '%(asctime)s %(clientip)-15s %(user)-8s %(message)s'
logging.basicConfig(format=FORMAT)
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logger = logging.getLogger('tcpserver')
logger.warning('Protocol problem: %s', 'connection reset', extra=d)
</pre> <p>would print something like</p> <pre data-language="none">2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset
</pre> <p>The keys in the dictionary passed in <em>extra</em> should not clash with the keys used by the logging system. (See the section on <a class="reference internal" href="#logrecord-attributes"><span class="std std-ref">LogRecord attributes</span></a> for more information on which keys are used by the logging system.)</p> <p>If you choose to use these attributes in logged messages, you need to exercise some care. In the above example, for instance, the <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code>Formatter</code></a> has been set up with a format string which expects ‘clientip’ and ‘user’ in the attribute dictionary of the <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a>. If these are missing, the message will not be logged because a string formatting exception will occur. So in this case, you always need to pass the <em>extra</em> dictionary with these keys.</p> <p>While this might be annoying, this feature is intended for use in specialized circumstances, such as multi-threaded servers where the same code executes in many contexts, and interesting conditions which arise are dependent on this context (such as remote client IP address and authenticated user name, in the above example). In such circumstances, it is likely that specialized <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code>Formatter</code></a>s would be used with particular <a class="reference internal" href="#logging.Handler" title="logging.Handler"><code>Handler</code></a>s.</p> <p>If no handler is attached to this logger (or any of its ancestors, taking into account the relevant <a class="reference internal" href="#logging.Logger.propagate" title="logging.Logger.propagate"><code>Logger.propagate</code></a> attributes), the message will be sent to the handler set on <a class="reference internal" href="#logging.lastResort" title="logging.lastResort"><code>lastResort</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>The <em>stack_info</em> parameter was added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The <em>exc_info</em> parameter can now accept exception instances.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>The <em>stacklevel</em> parameter was added.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.info">
<code>info(msg, *args, **kwargs)</code> </dt> <dd>
<p>Logs a message with level <a class="reference internal" href="#logging.INFO" title="logging.INFO"><code>INFO</code></a> on this logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code>debug()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.warning">
<code>warning(msg, *args, **kwargs)</code> </dt> <dd>
<p>Logs a message with level <a class="reference internal" href="#logging.WARNING" title="logging.WARNING"><code>WARNING</code></a> on this logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code>debug()</code></a>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>There is an obsolete method <code>warn</code> which is functionally identical to <code>warning</code>. As <code>warn</code> is deprecated, please do not use it - use <code>warning</code> instead.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.error">
<code>error(msg, *args, **kwargs)</code> </dt> <dd>
<p>Logs a message with level <a class="reference internal" href="#logging.ERROR" title="logging.ERROR"><code>ERROR</code></a> on this logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code>debug()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.critical">
<code>critical(msg, *args, **kwargs)</code> </dt> <dd>
<p>Logs a message with level <a class="reference internal" href="#logging.CRITICAL" title="logging.CRITICAL"><code>CRITICAL</code></a> on this logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code>debug()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.log">
<code>log(level, msg, *args, **kwargs)</code> </dt> <dd>
<p>Logs a message with integer level <em>level</em> on this logger. The other arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code>debug()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.exception">
<code>exception(msg, *args, **kwargs)</code> </dt> <dd>
<p>Logs a message with level <a class="reference internal" href="#logging.ERROR" title="logging.ERROR"><code>ERROR</code></a> on this logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code>debug()</code></a>. Exception info is added to the logging message. This method should only be called from an exception handler.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.addFilter">
<code>addFilter(filter)</code> </dt> <dd>
<p>Adds the specified filter <em>filter</em> to this logger.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.removeFilter">
<code>removeFilter(filter)</code> </dt> <dd>
<p>Removes the specified filter <em>filter</em> from this logger.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.filter">
<code>filter(record)</code> </dt> <dd>
<p>Apply this logger’s filters to the record and return <code>True</code> if the record is to be processed. The filters are consulted in turn, until one of them returns a false value. If none of them return a false value, the record will be processed (passed to handlers). If one returns a false value, no further processing of the record occurs.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.addHandler">
<code>addHandler(hdlr)</code> </dt> <dd>
<p>Adds the specified handler <em>hdlr</em> to this logger.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.removeHandler">
<code>removeHandler(hdlr)</code> </dt> <dd>
<p>Removes the specified handler <em>hdlr</em> from this logger.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.findCaller">
<code>findCaller(stack_info=False, stacklevel=1)</code> </dt> <dd>
<p>Finds the caller’s source filename and line number. Returns the filename, line number, function name and stack information as a 4-element tuple. The stack information is returned as <code>None</code> unless <em>stack_info</em> is <code>True</code>.</p> <p>The <em>stacklevel</em> parameter is passed from code calling the <a class="reference internal" href="#logging.debug" title="logging.debug"><code>debug()</code></a> and other APIs. If greater than 1, the excess is used to skip stack frames before determining the values to be returned. This will generally be useful when calling logging APIs from helper/wrapper code, so that the information in the event log refers not to the helper/wrapper code, but to the code that calls it.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.handle">
<code>handle(record)</code> </dt> <dd>
<p>Handles a record by passing it to all handlers associated with this logger and its ancestors (until a false value of <em>propagate</em> is found). This method is used for unpickled records received from a socket, as well as those created locally. Logger-level filtering is applied using <a class="reference internal" href="#logging.Logger.filter" title="logging.Logger.filter"><code>filter()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.makeRecord">
<code>makeRecord(name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)</code> </dt> <dd>
<p>This is a factory method which can be overridden in subclasses to create specialized <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> instances.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Logger.hasHandlers">
<code>hasHandlers()</code> </dt> <dd>
<p>Checks to see if this logger has any handlers configured. This is done by looking for handlers in this logger and its parents in the logger hierarchy. Returns <code>True</code> if a handler was found, else <code>False</code>. The method stops searching up the hierarchy whenever a logger with the ‘propagate’ attribute set to false is found - that will be the last logger which is checked for the existence of handlers.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
</dl> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Loggers can now be pickled and unpickled.</p> </div> </dd>
</dl> </section> <section id="logging-levels"> <span id="levels"></span><h2>Logging Levels</h2> <p>The numeric values of logging levels are given in the following table. These are primarily of interest if you want to define your own levels, and need them to have specific values relative to the predefined levels. If you define a level with the same numeric value, it overwrites the predefined value; the predefined name is lost.</p> <table class="docutils align-default">  <thead> <tr>
<th class="head"><p>Level</p></th> <th class="head"><p>Numeric value</p></th> <th class="head"><p>What it means / When to use it</p></th> </tr> </thead>  <tr>
<td>
<dl class="py data"> <dt class="sig sig-object py" id="logging.NOTSET">
<code>logging.NOTSET</code> </dt> <dd></dd>
</dl> </td> <td><p>0</p></td> <td><p>When set on a logger, indicates that ancestor loggers are to be consulted to determine the effective level. If that still resolves to <code>NOTSET</code>, then all events are logged. When set on a handler, all events are handled.</p></td> </tr> <tr>
<td>
<dl class="py data"> <dt class="sig sig-object py" id="logging.DEBUG">
<code>logging.DEBUG</code> </dt> <dd></dd>
</dl> </td> <td><p>10</p></td> <td><p>Detailed information, typically only of interest to a developer trying to diagnose a problem.</p></td> </tr> <tr>
<td>
<dl class="py data"> <dt class="sig sig-object py" id="logging.INFO">
<code>logging.INFO</code> </dt> <dd></dd>
</dl> </td> <td><p>20</p></td> <td><p>Confirmation that things are working as expected.</p></td> </tr> <tr>
<td>
<dl class="py data"> <dt class="sig sig-object py" id="logging.WARNING">
<code>logging.WARNING</code> </dt> <dd></dd>
</dl> </td> <td><p>30</p></td> <td><p>An indication that something unexpected happened, or that a problem might occur in the near future (e.g. ‘disk space low’). The software is still working as expected.</p></td> </tr> <tr>
<td>
<dl class="py data"> <dt class="sig sig-object py" id="logging.ERROR">
<code>logging.ERROR</code> </dt> <dd></dd>
</dl> </td> <td><p>40</p></td> <td><p>Due to a more serious problem, the software has not been able to perform some function.</p></td> </tr> <tr>
<td>
<dl class="py data"> <dt class="sig sig-object py" id="logging.CRITICAL">
<code>logging.CRITICAL</code> </dt> <dd></dd>
</dl> </td> <td><p>50</p></td> <td><p>A serious error, indicating that the program itself may be unable to continue running.</p></td> </tr>  </table> </section> <section id="handler-objects"> <span id="handler"></span><h2>Handler Objects</h2> <p>Handlers have the following attributes and methods. Note that <a class="reference internal" href="#logging.Handler" title="logging.Handler"><code>Handler</code></a> is never instantiated directly; this class acts as a base for more useful subclasses. However, the <code>__init__()</code> method in subclasses needs to call <a class="reference internal" href="#logging.Handler.__init__" title="logging.Handler.__init__"><code>Handler.__init__()</code></a>.</p> <dl class="py class"> <dt class="sig sig-object py" id="logging.Handler">
<code>class logging.Handler</code> </dt> <dd>
<dl class="py method"> <dt class="sig sig-object py" id="logging.Handler.__init__">
<code>__init__(level=NOTSET)</code> </dt> <dd>
<p>Initializes the <a class="reference internal" href="#logging.Handler" title="logging.Handler"><code>Handler</code></a> instance by setting its level, setting the list of filters to the empty list and creating a lock (using <a class="reference internal" href="#logging.Handler.createLock" title="logging.Handler.createLock"><code>createLock()</code></a>) for serializing access to an I/O mechanism.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Handler.createLock">
<code>createLock()</code> </dt> <dd>
<p>Initializes a thread lock which can be used to serialize access to underlying I/O functionality which may not be threadsafe.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Handler.acquire">
<code>acquire()</code> </dt> <dd>
<p>Acquires the thread lock created with <a class="reference internal" href="#logging.Handler.createLock" title="logging.Handler.createLock"><code>createLock()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Handler.release">
<code>release()</code> </dt> <dd>
<p>Releases the thread lock acquired with <a class="reference internal" href="#logging.Handler.acquire" title="logging.Handler.acquire"><code>acquire()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Handler.setLevel">
<code>setLevel(level)</code> </dt> <dd>
<p>Sets the threshold for this handler to <em>level</em>. Logging messages which are less severe than <em>level</em> will be ignored. When a handler is created, the level is set to <a class="reference internal" href="#logging.NOTSET" title="logging.NOTSET"><code>NOTSET</code></a> (which causes all messages to be processed).</p> <p>See <a class="reference internal" href="#levels"><span class="std std-ref">Logging Levels</span></a> for a list of levels.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>The <em>level</em> parameter now accepts a string representation of the level such as ‘INFO’ as an alternative to the integer constants such as <a class="reference internal" href="#logging.INFO" title="logging.INFO"><code>INFO</code></a>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Handler.setFormatter">
<code>setFormatter(fmt)</code> </dt> <dd>
<p>Sets the <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code>Formatter</code></a> for this handler to <em>fmt</em>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Handler.addFilter">
<code>addFilter(filter)</code> </dt> <dd>
<p>Adds the specified filter <em>filter</em> to this handler.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Handler.removeFilter">
<code>removeFilter(filter)</code> </dt> <dd>
<p>Removes the specified filter <em>filter</em> from this handler.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Handler.filter">
<code>filter(record)</code> </dt> <dd>
<p>Apply this handler’s filters to the record and return <code>True</code> if the record is to be processed. The filters are consulted in turn, until one of them returns a false value. If none of them return a false value, the record will be emitted. If one returns a false value, the handler will not emit the record.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Handler.flush">
<code>flush()</code> </dt> <dd>
<p>Ensure all logging output has been flushed. This version does nothing and is intended to be implemented by subclasses.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Handler.close">
<code>close()</code> </dt> <dd>
<p>Tidy up any resources used by the handler. This version does no output but removes the handler from an internal list of handlers which is closed when <a class="reference internal" href="#logging.shutdown" title="logging.shutdown"><code>shutdown()</code></a> is called. Subclasses should ensure that this gets called from overridden <a class="reference internal" href="#logging.Handler.close" title="logging.Handler.close"><code>close()</code></a> methods.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Handler.handle">
<code>handle(record)</code> </dt> <dd>
<p>Conditionally emits the specified logging record, depending on filters which may have been added to the handler. Wraps the actual emission of the record with acquisition/release of the I/O thread lock.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Handler.handleError">
<code>handleError(record)</code> </dt> <dd>
<p>This method should be called from handlers when an exception is encountered during an <a class="reference internal" href="#logging.Handler.emit" title="logging.Handler.emit"><code>emit()</code></a> call. If the module-level attribute <code>raiseExceptions</code> is <code>False</code>, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The specified record is the one which was being processed when the exception occurred. (The default value of <code>raiseExceptions</code> is <code>True</code>, as that is more useful during development).</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Handler.format">
<code>format(record)</code> </dt> <dd>
<p>Do formatting for a record - if a formatter is set, use it. Otherwise, use the default formatter for the module.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Handler.emit">
<code>emit(record)</code> </dt> <dd>
<p>Do whatever it takes to actually log the specified logging record. This version is intended to be implemented by subclasses and so raises a <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a>.</p> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>This method is called after a handler-level lock is acquired, which is released after this method returns. When you override this method, note that you should be careful when calling anything that invokes other parts of the logging API which might do locking, because that might result in a deadlock. Specifically:</p> <ul class="simple"> <li>Logging configuration APIs acquire the module-level lock, and then individual handler-level locks as those handlers are configured.</li> <li>Many logging APIs lock the module-level lock. If such an API is called from this method, it could cause a deadlock if a configuration call is made on another thread, because that thread will try to acquire the module-level lock <em>before</em> the handler-level lock, whereas this thread tries to acquire the module-level lock <em>after</em> the handler-level lock (because in this method, the handler-level lock has already been acquired).</li> </ul> </div> </dd>
</dl> </dd>
</dl> <p>For a list of handlers included as standard, see <a class="reference internal" href="logging.handlers#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code>logging.handlers</code></a>.</p> </section> <section id="formatter-objects"> <span id="id1"></span><h2>Formatter Objects</h2> <dl class="py class"> <dt class="sig sig-object py" id="logging.Formatter">
<code>class logging.Formatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)</code> </dt> <dd>
<p>Responsible for converting a <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> to an output string to be interpreted by a human or external system.</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd">
<ul class="simple"> <li>
<strong>fmt</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a>) – A format string in the given <em>style</em> for the logged output as a whole. The possible mapping keys are drawn from the <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> object’s <a class="reference internal" href="#logrecord-attributes"><span class="std std-ref">LogRecord attributes</span></a>. If not specified, <code>'%(message)s'</code> is used, which is just the logged message.</li> <li>
<strong>datefmt</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a>) – A format string in the given <em>style</em> for the date/time portion of the logged output. If not specified, the default described in <a class="reference internal" href="#logging.Formatter.formatTime" title="logging.Formatter.formatTime"><code>formatTime()</code></a> is used.</li> <li>
<strong>style</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a>) – Can be one of <code>'%'</code>, <code>'{'</code> or <code>'$'</code> and determines how the format string will be merged with its data: using one of <a class="reference internal" href="stdtypes#old-string-formatting"><span class="std std-ref">printf-style String Formatting</span></a> (<code>%</code>), <a class="reference internal" href="stdtypes#str.format" title="str.format"><code>str.format()</code></a> (<code>{</code>) or <a class="reference internal" href="string#string.Template" title="string.Template"><code>string.Template</code></a> (<code>$</code>). This only applies to <em>fmt</em> and <em>datefmt</em> (e.g. <code>'%(message)s'</code> versus <code>'{message}'</code>), not to the actual log messages passed to the logging methods. However, there are <a class="reference internal" href="../howto/logging-cookbook#formatting-styles"><span class="std std-ref">other ways</span></a> to use <code>{</code>- and <code>$</code>-formatting for log messages.</li> <li>
<strong>validate</strong> (<a class="reference internal" href="functions#bool" title="bool">bool</a>) – If <code>True</code> (the default), incorrect or mismatched <em>fmt</em> and <em>style</em> will raise a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a>; for example, <code>logging.Formatter('%(asctime)s - %(message)s', style='{')</code>.</li> <li>
<strong>defaults</strong> (<a class="reference internal" href="stdtypes#dict" title="dict">dict</a><em>[</em><a class="reference internal" href="stdtypes#str" title="str">str</a><em>, </em><em>Any</em><em>]</em>) – A dictionary with default values to use in custom fields. For example, <code>logging.Formatter('%(ip)s %(message)s', defaults={"ip": None})</code>
</li> </ul> </dd> </dl> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2: </span>The <em>style</em> parameter.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8: </span>The <em>validate</em> parameter.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10: </span>The <em>defaults</em> parameter.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="logging.Formatter.format">
<code>format(record)</code> </dt> <dd>
<p>The record’s attribute dictionary is used as the operand to a string formatting operation. Returns the resulting string. Before formatting the dictionary, a couple of preparatory steps are carried out. The <em>message</em> attribute of the record is computed using <em>msg</em> % <em>args</em>. If the formatting string contains <code>'(asctime)'</code>, <a class="reference internal" href="#logging.Formatter.formatTime" title="logging.Formatter.formatTime"><code>formatTime()</code></a> is called to format the event time. If there is exception information, it is formatted using <a class="reference internal" href="#logging.Formatter.formatException" title="logging.Formatter.formatException"><code>formatException()</code></a> and appended to the message. Note that the formatted exception information is cached in attribute <em>exc_text</em>. This is useful because the exception information can be pickled and sent across the wire, but you should be careful if you have more than one <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code>Formatter</code></a> subclass which customizes the formatting of exception information. In this case, you will have to clear the cached value (by setting the <em>exc_text</em> attribute to <code>None</code>) after a formatter has done its formatting, so that the next formatter to handle the event doesn’t use the cached value, but recalculates it afresh.</p> <p>If stack information is available, it’s appended after the exception information, using <a class="reference internal" href="#logging.Formatter.formatStack" title="logging.Formatter.formatStack"><code>formatStack()</code></a> to transform it if necessary.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Formatter.formatTime">
<code>formatTime(record, datefmt=None)</code> </dt> <dd>
<p>This method should be called from <a class="reference internal" href="functions#format" title="format"><code>format()</code></a> by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behavior is as follows: if <em>datefmt</em> (a string) is specified, it is used with <a class="reference internal" href="time#time.strftime" title="time.strftime"><code>time.strftime()</code></a> to format the creation time of the record. Otherwise, the format ‘%Y-%m-%d %H:%M:%S,uuu’ is used, where the uuu part is a millisecond value and the other letters are as per the <a class="reference internal" href="time#time.strftime" title="time.strftime"><code>time.strftime()</code></a> documentation. An example time in this format is <code>2003-01-23 00:29:50,411</code>. The resulting string is returned.</p> <p>This function uses a user-configurable function to convert the creation time to a tuple. By default, <a class="reference internal" href="time#time.localtime" title="time.localtime"><code>time.localtime()</code></a> is used; to change this for a particular formatter instance, set the <code>converter</code> attribute to a function with the same signature as <a class="reference internal" href="time#time.localtime" title="time.localtime"><code>time.localtime()</code></a> or <a class="reference internal" href="time#time.gmtime" title="time.gmtime"><code>time.gmtime()</code></a>. To change it for all formatters, for example if you want all logging times to be shown in GMT, set the <code>converter</code> attribute in the <code>Formatter</code> class.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Previously, the default format was hard-coded as in this example: <code>2010-09-06 22:38:15,292</code> where the part before the comma is handled by a strptime format string (<code>'%Y-%m-%d %H:%M:%S'</code>), and the part after the comma is a millisecond value. Because strptime does not have a format placeholder for milliseconds, the millisecond value is appended using another format string, <code>'%s,%03d'</code> — and both of these format strings have been hardcoded into this method. With the change, these strings are defined as class-level attributes which can be overridden at the instance level when desired. The names of the attributes are <code>default_time_format</code> (for the strptime format string) and <code>default_msec_format</code> (for appending the millisecond value).</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>The <code>default_msec_format</code> can be <code>None</code>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Formatter.formatException">
<code>formatException(exc_info)</code> </dt> <dd>
<p>Formats the specified exception information (a standard exception tuple as returned by <a class="reference internal" href="sys#sys.exc_info" title="sys.exc_info"><code>sys.exc_info()</code></a>) as a string. This default implementation just uses <a class="reference internal" href="traceback#traceback.print_exception" title="traceback.print_exception"><code>traceback.print_exception()</code></a>. The resulting string is returned.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.Formatter.formatStack">
<code>formatStack(stack_info)</code> </dt> <dd>
<p>Formats the specified stack information (a string as returned by <a class="reference internal" href="traceback#traceback.print_stack" title="traceback.print_stack"><code>traceback.print_stack()</code></a>, but with the last newline removed) as a string. This default implementation just returns the input value.</p> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="logging.BufferingFormatter">
<code>class logging.BufferingFormatter(linefmt=None)</code> </dt> <dd>
<p>A base formatter class suitable for subclassing when you want to format a number of records. You can pass a <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code>Formatter</code></a> instance which you want to use to format each line (that corresponds to a single record). If not specified, the default formatter (which just outputs the event message) is used as the line formatter.</p> <dl class="py method"> <dt class="sig sig-object py" id="logging.BufferingFormatter.formatHeader">
<code>formatHeader(records)</code> </dt> <dd>
<p>Return a header for a list of <em>records</em>. The base implementation just returns the empty string. You will need to override this method if you want specific behaviour, e.g. to show the count of records, a title or a separator line.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.BufferingFormatter.formatFooter">
<code>formatFooter(records)</code> </dt> <dd>
<p>Return a footer for a list of <em>records</em>. The base implementation just returns the empty string. You will need to override this method if you want specific behaviour, e.g. to show the count of records or a separator line.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.BufferingFormatter.format">
<code>format(records)</code> </dt> <dd>
<p>Return formatted text for a list of <em>records</em>. The base implementation just returns the empty string if there are no records; otherwise, it returns the concatenation of the header, each record formatted with the line formatter, and the footer.</p> </dd>
</dl> </dd>
</dl> </section> <section id="filter-objects"> <span id="filter"></span><h2>Filter Objects</h2> <p><code>Filters</code> can be used by <code>Handlers</code> and <code>Loggers</code> for more sophisticated filtering than is provided by levels. The base filter class only allows events which are below a certain point in the logger hierarchy. For example, a filter initialized with ‘A.B’ will allow events logged by loggers ‘A.B’, ‘A.B.C’, ‘A.B.C.D’, ‘A.B.D’ etc. but not ‘A.BB’, ‘B.A.B’ etc. If initialized with the empty string, all events are passed.</p> <dl class="py class"> <dt class="sig sig-object py" id="logging.Filter">
<code>class logging.Filter(name='')</code> </dt> <dd>
<p>Returns an instance of the <a class="reference internal" href="#logging.Filter" title="logging.Filter"><code>Filter</code></a> class. If <em>name</em> is specified, it names a logger which, together with its children, will have its events allowed through the filter. If <em>name</em> is the empty string, allows every event.</p> <dl class="py method"> <dt class="sig sig-object py" id="logging.Filter.filter">
<code>filter(record)</code> </dt> <dd>
<p>Is the specified record to be logged? Returns false for no, true for yes. Filters can either modify log records in-place or return a completely different record instance which will replace the original log record in any future processing of the event.</p> </dd>
</dl> </dd>
</dl> <p>Note that filters attached to handlers are consulted before an event is emitted by the handler, whereas filters attached to loggers are consulted whenever an event is logged (using <a class="reference internal" href="#logging.debug" title="logging.debug"><code>debug()</code></a>, <a class="reference internal" href="#logging.info" title="logging.info"><code>info()</code></a>, etc.), before sending an event to handlers. This means that events which have been generated by descendant loggers will not be filtered by a logger’s filter setting, unless the filter has also been applied to those descendant loggers.</p> <p>You don’t actually need to subclass <code>Filter</code>: you can pass any instance which has a <code>filter</code> method with the same semantics.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>You don’t need to create specialized <code>Filter</code> classes, or use other classes with a <code>filter</code> method: you can use a function (or other callable) as a filter. The filtering logic will check to see if the filter object has a <code>filter</code> attribute: if it does, it’s assumed to be a <code>Filter</code> and its <a class="reference internal" href="#logging.Filter.filter" title="logging.Filter.filter"><code>filter()</code></a> method is called. Otherwise, it’s assumed to be a callable and called with the record as the single parameter. The returned value should conform to that returned by <a class="reference internal" href="#logging.Filter.filter" title="logging.Filter.filter"><code>filter()</code></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>You can now return a <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> instance from filters to replace the log record rather than modifying it in place. This allows filters attached to a <a class="reference internal" href="#logging.Handler" title="logging.Handler"><code>Handler</code></a> to modify the log record before it is emitted, without having side effects on other handlers.</p> </div> <p>Although filters are used primarily to filter records based on more sophisticated criteria than levels, they get to see every record which is processed by the handler or logger they’re attached to: this can be useful if you want to do things like counting how many records were processed by a particular logger or handler, or adding, changing or removing attributes in the <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> being processed. Obviously changing the LogRecord needs to be done with some care, but it does allow the injection of contextual information into logs (see <a class="reference internal" href="../howto/logging-cookbook#filters-contextual"><span class="std std-ref">Using Filters to impart contextual information</span></a>).</p> </section> <section id="logrecord-objects"> <span id="log-record"></span><h2>LogRecord Objects</h2> <p><a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> instances are created automatically by the <a class="reference internal" href="#logging.Logger" title="logging.Logger"><code>Logger</code></a> every time something is logged, and can be created manually via <a class="reference internal" href="#logging.makeLogRecord" title="logging.makeLogRecord"><code>makeLogRecord()</code></a> (for example, from a pickled event received over the wire).</p> <dl class="py class"> <dt class="sig sig-object py" id="logging.LogRecord">
<code>class logging.LogRecord(name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None)</code> </dt> <dd>
<p>Contains all the information pertinent to the event being logged.</p> <p>The primary information is passed in <em>msg</em> and <em>args</em>, which are combined using <code>msg % args</code> to create the <code>message</code> attribute of the record.</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd">
<ul class="simple"> <li>
<strong>name</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a>) – The name of the logger used to log the event represented by this <code>LogRecord</code>. Note that the logger name in the <code>LogRecord</code> will always have this value, even though it may be emitted by a handler attached to a different (ancestor) logger.</li> <li>
<strong>level</strong> (<a class="reference internal" href="functions#int" title="int">int</a>) – The <a class="reference internal" href="#levels"><span class="std std-ref">numeric level</span></a> of the logging event (such as <code>10</code> for <code>DEBUG</code>, <code>20</code> for <code>INFO</code>, etc). Note that this is converted to <em>two</em> attributes of the LogRecord: <code>levelno</code> for the numeric value and <code>levelname</code> for the corresponding level name.</li> <li>
<strong>pathname</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a>) – The full string path of the source file where the logging call was made.</li> <li>
<strong>lineno</strong> (<a class="reference internal" href="functions#int" title="int">int</a>) – The line number in the source file where the logging call was made.</li> <li>
<strong>msg</strong> (<a class="reference internal" href="typing#typing.Any" title="typing.Any">Any</a>) – The event description message, which can be a %-format string with placeholders for variable data, or an arbitrary object (see <a class="reference internal" href="../howto/logging#arbitrary-object-messages"><span class="std std-ref">Using arbitrary objects as messages</span></a>).</li> <li>
<strong>args</strong> (<a class="reference internal" href="stdtypes#tuple" title="tuple">tuple</a><em> | </em><a class="reference internal" href="stdtypes#dict" title="dict">dict</a><em>[</em><a class="reference internal" href="stdtypes#str" title="str">str</a><em>, </em><a class="reference internal" href="typing#typing.Any" title="typing.Any">Any</a><em>]</em>) – Variable data to merge into the <em>msg</em> argument to obtain the event description.</li> <li>
<strong>exc_info</strong> (<a class="reference internal" href="stdtypes#tuple" title="tuple">tuple</a><em>[</em><a class="reference internal" href="functions#type" title="type">type</a><em>[</em><a class="reference internal" href="exceptions#BaseException" title="BaseException">BaseException</a><em>]</em><em>, </em><a class="reference internal" href="exceptions#BaseException" title="BaseException">BaseException</a><em>, </em><a class="reference internal" href="types#types.TracebackType" title="types.TracebackType">types.TracebackType</a><em>] </em><em>| </em><em>None</em>) – An exception tuple with the current exception information, as returned by <a class="reference internal" href="sys#sys.exc_info" title="sys.exc_info"><code>sys.exc_info()</code></a>, or <code>None</code> if no exception information is available.</li> <li>
<strong>func</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a><em> | </em><em>None</em>) – The name of the function or method from which the logging call was invoked.</li> <li>
<strong>sinfo</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a><em> | </em><em>None</em>) – A text string representing stack information from the base of the stack in the current thread, up to the logging call.</li> </ul> </dd> </dl> <dl class="py method"> <dt class="sig sig-object py" id="logging.LogRecord.getMessage">
<code>getMessage()</code> </dt> <dd>
<p>Returns the message for this <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> instance after merging any user-supplied arguments with the message. If the user-supplied message argument to the logging call is not a string, <a class="reference internal" href="stdtypes#str" title="str"><code>str()</code></a> is called on it to convert it to a string. This allows use of user-defined classes as messages, whose <code>__str__</code> method can return the actual format string to be used.</p> </dd>
</dl> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>The creation of a <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> has been made more configurable by providing a factory which is used to create the record. The factory can be set using <a class="reference internal" href="#logging.getLogRecordFactory" title="logging.getLogRecordFactory"><code>getLogRecordFactory()</code></a> and <a class="reference internal" href="#logging.setLogRecordFactory" title="logging.setLogRecordFactory"><code>setLogRecordFactory()</code></a> (see this for the factory’s signature).</p> </div> <p>This functionality can be used to inject your own values into a <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> at creation time. You can use the following pattern:</p> <pre data-language="python">old_factory = logging.getLogRecordFactory()

def record_factory(*args, **kwargs):
    record = old_factory(*args, **kwargs)
    record.custom_attribute = 0xdecafbad
    return record

logging.setLogRecordFactory(record_factory)
</pre> <p>With this pattern, multiple factories could be chained, and as long as they don’t overwrite each other’s attributes or unintentionally overwrite the standard attributes listed above, there should be no surprises.</p> </dd>
</dl> </section> <section id="logrecord-attributes"> <span id="id2"></span><h2>LogRecord attributes</h2> <p>The LogRecord has a number of attributes, most of which are derived from the parameters to the constructor. (Note that the names do not always correspond exactly between the LogRecord constructor parameters and the LogRecord attributes.) These attributes can be used to merge data from the record into the format string. The following table lists (in alphabetical order) the attribute names, their meanings and the corresponding placeholder in a %-style format string.</p> <p>If you are using {}-formatting (<a class="reference internal" href="stdtypes#str.format" title="str.format"><code>str.format()</code></a>), you can use <code>{attrname}</code> as the placeholder in the format string. If you are using $-formatting (<a class="reference internal" href="string#string.Template" title="string.Template"><code>string.Template</code></a>), use the form <code>${attrname}</code>. In both cases, of course, replace <code>attrname</code> with the actual attribute name you want to use.</p> <p>In the case of {}-formatting, you can specify formatting flags by placing them after the attribute name, separated from it with a colon. For example: a placeholder of <code>{msecs:03.0f}</code> would format a millisecond value of <code>4</code> as <code>004</code>. Refer to the <a class="reference internal" href="stdtypes#str.format" title="str.format"><code>str.format()</code></a> documentation for full details on the options available to you.</p> <table class="docutils align-default">  <thead> <tr>
<th class="head"><p>Attribute name</p></th> <th class="head"><p>Format</p></th> <th class="head"><p>Description</p></th> </tr> </thead>  <tr>
<td><p>args</p></td> <td><p>You shouldn’t need to format this yourself.</p></td> <td><p>The tuple of arguments merged into <code>msg</code> to produce <code>message</code>, or a dict whose values are used for the merge (when there is only one argument, and it is a dictionary).</p></td> </tr> <tr>
<td><p>asctime</p></td> <td><p><code>%(asctime)s</code></p></td> <td><p>Human-readable time when the <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> was created. By default this is of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma are millisecond portion of the time).</p></td> </tr> <tr>
<td><p>created</p></td> <td><p><code>%(created)f</code></p></td> <td><p>Time when the <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> was created (as returned by <a class="reference internal" href="time#time.time" title="time.time"><code>time.time()</code></a>).</p></td> </tr> <tr>
<td><p>exc_info</p></td> <td><p>You shouldn’t need to format this yourself.</p></td> <td><p>Exception tuple (à la <code>sys.exc_info</code>) or, if no exception has occurred, <code>None</code>.</p></td> </tr> <tr>
<td><p>filename</p></td> <td><p><code>%(filename)s</code></p></td> <td><p>Filename portion of <code>pathname</code>.</p></td> </tr> <tr>
<td><p>funcName</p></td> <td><p><code>%(funcName)s</code></p></td> <td><p>Name of function containing the logging call.</p></td> </tr> <tr>
<td><p>levelname</p></td> <td><p><code>%(levelname)s</code></p></td> <td><p>Text logging level for the message (<code>'DEBUG'</code>, <code>'INFO'</code>, <code>'WARNING'</code>, <code>'ERROR'</code>, <code>'CRITICAL'</code>).</p></td> </tr> <tr>
<td><p>levelno</p></td> <td><p><code>%(levelno)s</code></p></td> <td><p>Numeric logging level for the message (<a class="reference internal" href="#logging.DEBUG" title="logging.DEBUG"><code>DEBUG</code></a>, <a class="reference internal" href="#logging.INFO" title="logging.INFO"><code>INFO</code></a>, <a class="reference internal" href="#logging.WARNING" title="logging.WARNING"><code>WARNING</code></a>, <a class="reference internal" href="#logging.ERROR" title="logging.ERROR"><code>ERROR</code></a>, <a class="reference internal" href="#logging.CRITICAL" title="logging.CRITICAL"><code>CRITICAL</code></a>).</p></td> </tr> <tr>
<td><p>lineno</p></td> <td><p><code>%(lineno)d</code></p></td> <td><p>Source line number where the logging call was issued (if available).</p></td> </tr> <tr>
<td><p>message</p></td> <td><p><code>%(message)s</code></p></td> <td><p>The logged message, computed as <code>msg %
args</code>. This is set when <a class="reference internal" href="#logging.Formatter.format" title="logging.Formatter.format"><code>Formatter.format()</code></a> is invoked.</p></td> </tr> <tr>
<td><p>module</p></td> <td><p><code>%(module)s</code></p></td> <td><p>Module (name portion of <code>filename</code>).</p></td> </tr> <tr>
<td><p>msecs</p></td> <td><p><code>%(msecs)d</code></p></td> <td><p>Millisecond portion of the time when the <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> was created.</p></td> </tr> <tr>
<td><p>msg</p></td> <td><p>You shouldn’t need to format this yourself.</p></td> <td><p>The format string passed in the original logging call. Merged with <code>args</code> to produce <code>message</code>, or an arbitrary object (see <a class="reference internal" href="../howto/logging#arbitrary-object-messages"><span class="std std-ref">Using arbitrary objects as messages</span></a>).</p></td> </tr> <tr>
<td><p>name</p></td> <td><p><code>%(name)s</code></p></td> <td><p>Name of the logger used to log the call.</p></td> </tr> <tr>
<td><p>pathname</p></td> <td><p><code>%(pathname)s</code></p></td> <td><p>Full pathname of the source file where the logging call was issued (if available).</p></td> </tr> <tr>
<td><p>process</p></td> <td><p><code>%(process)d</code></p></td> <td><p>Process ID (if available).</p></td> </tr> <tr>
<td><p>processName</p></td> <td><p><code>%(processName)s</code></p></td> <td><p>Process name (if available).</p></td> </tr> <tr>
<td><p>relativeCreated</p></td> <td><p><code>%(relativeCreated)d</code></p></td> <td><p>Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.</p></td> </tr> <tr>
<td><p>stack_info</p></td> <td><p>You shouldn’t need to format this yourself.</p></td> <td><p>Stack frame information (where available) from the bottom of the stack in the current thread, up to and including the stack frame of the logging call which resulted in the creation of this record.</p></td> </tr> <tr>
<td><p>thread</p></td> <td><p><code>%(thread)d</code></p></td> <td><p>Thread ID (if available).</p></td> </tr> <tr>
<td><p>threadName</p></td> <td><p><code>%(threadName)s</code></p></td> <td><p>Thread name (if available).</p></td> </tr> <tr>
<td><p>taskName</p></td> <td><p><code>%(taskName)s</code></p></td> <td><p><a class="reference internal" href="asyncio-task#asyncio.Task" title="asyncio.Task"><code>asyncio.Task</code></a> name (if available).</p></td> </tr>  </table> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.1: </span><em>processName</em> was added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span><em>taskName</em> was added.</p> </div> </section> <section id="loggeradapter-objects"> <span id="logger-adapter"></span><h2>LoggerAdapter Objects</h2> <p><a class="reference internal" href="#logging.LoggerAdapter" title="logging.LoggerAdapter"><code>LoggerAdapter</code></a> instances are used to conveniently pass contextual information into logging calls. For a usage example, see the section on <a class="reference internal" href="../howto/logging-cookbook#context-info"><span class="std std-ref">adding contextual information to your logging output</span></a>.</p> <dl class="py class"> <dt class="sig sig-object py" id="logging.LoggerAdapter">
<code>class logging.LoggerAdapter(logger, extra)</code> </dt> <dd>
<p>Returns an instance of <a class="reference internal" href="#logging.LoggerAdapter" title="logging.LoggerAdapter"><code>LoggerAdapter</code></a> initialized with an underlying <a class="reference internal" href="#logging.Logger" title="logging.Logger"><code>Logger</code></a> instance and a dict-like object.</p> <dl class="py method"> <dt class="sig sig-object py" id="logging.LoggerAdapter.process">
<code>process(msg, kwargs)</code> </dt> <dd>
<p>Modifies the message and/or keyword arguments passed to a logging call in order to insert contextual information. This implementation takes the object passed as <em>extra</em> to the constructor and adds it to <em>kwargs</em> using key ‘extra’. The return value is a (<em>msg</em>, <em>kwargs</em>) tuple which has the (possibly modified) versions of the arguments passed in.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="logging.LoggerAdapter.manager">
<code>manager</code> </dt> <dd>
<p>Delegates to the underlying <code>manager`</code> on <em>logger</em>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="logging.LoggerAdapter._log">
<code>_log</code> </dt> <dd>
<p>Delegates to the underlying <code>_log`()</code> method on <em>logger</em>.</p> </dd>
</dl> <p>In addition to the above, <a class="reference internal" href="#logging.LoggerAdapter" title="logging.LoggerAdapter"><code>LoggerAdapter</code></a> supports the following methods of <a class="reference internal" href="#logging.Logger" title="logging.Logger"><code>Logger</code></a>: <a class="reference internal" href="#logging.Logger.debug" title="logging.Logger.debug"><code>debug()</code></a>, <a class="reference internal" href="#logging.Logger.info" title="logging.Logger.info"><code>info()</code></a>, <a class="reference internal" href="#logging.Logger.warning" title="logging.Logger.warning"><code>warning()</code></a>, <a class="reference internal" href="#logging.Logger.error" title="logging.Logger.error"><code>error()</code></a>, <a class="reference internal" href="#logging.Logger.exception" title="logging.Logger.exception"><code>exception()</code></a>, <a class="reference internal" href="#logging.Logger.critical" title="logging.Logger.critical"><code>critical()</code></a>, <a class="reference internal" href="#logging.Logger.log" title="logging.Logger.log"><code>log()</code></a>, <a class="reference internal" href="#logging.Logger.isEnabledFor" title="logging.Logger.isEnabledFor"><code>isEnabledFor()</code></a>, <a class="reference internal" href="#logging.Logger.getEffectiveLevel" title="logging.Logger.getEffectiveLevel"><code>getEffectiveLevel()</code></a>, <a class="reference internal" href="#logging.Logger.setLevel" title="logging.Logger.setLevel"><code>setLevel()</code></a> and <a class="reference internal" href="#logging.Logger.hasHandlers" title="logging.Logger.hasHandlers"><code>hasHandlers()</code></a>. These methods have the same signatures as their counterparts in <a class="reference internal" href="#logging.Logger" title="logging.Logger"><code>Logger</code></a>, so you can use the two types of instances interchangeably.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>The <a class="reference internal" href="#logging.Logger.isEnabledFor" title="logging.Logger.isEnabledFor"><code>isEnabledFor()</code></a>, <a class="reference internal" href="#logging.Logger.getEffectiveLevel" title="logging.Logger.getEffectiveLevel"><code>getEffectiveLevel()</code></a>, <a class="reference internal" href="#logging.Logger.setLevel" title="logging.Logger.setLevel"><code>setLevel()</code></a> and <a class="reference internal" href="#logging.Logger.hasHandlers" title="logging.Logger.hasHandlers"><code>hasHandlers()</code></a> methods were added to <a class="reference internal" href="#logging.LoggerAdapter" title="logging.LoggerAdapter"><code>LoggerAdapter</code></a>. These methods delegate to the underlying logger.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>Attribute <code>manager</code> and method <code>_log()</code> were added, which delegate to the underlying logger and allow adapters to be nested.</p> </div> </dd>
</dl> </section> <section id="thread-safety"> <h2>Thread Safety</h2> <p>The logging module is intended to be thread-safe without any special work needing to be done by its clients. It achieves this though using threading locks; there is one lock to serialize access to the module’s shared data, and each handler also creates a lock to serialize access to its underlying I/O.</p> <p>If you are implementing asynchronous signal handlers using the <a class="reference internal" href="signal#module-signal" title="signal: Set handlers for asynchronous events."><code>signal</code></a> module, you may not be able to use logging from within such handlers. This is because lock implementations in the <a class="reference internal" href="threading#module-threading" title="threading: Thread-based parallelism."><code>threading</code></a> module are not always re-entrant, and so cannot be invoked from such signal handlers.</p> </section> <section id="module-level-functions"> <h2>Module-Level Functions</h2> <p>In addition to the classes described above, there are a number of module-level functions.</p> <dl class="py function"> <dt class="sig sig-object py" id="logging.getLogger">
<code>logging.getLogger(name=None)</code> </dt> <dd>
<p>Return a logger with the specified name or, if name is <code>None</code>, return a logger which is the root logger of the hierarchy. If specified, the name is typically a dot-separated hierarchical name like <em>‘a’</em>, <em>‘a.b’</em> or <em>‘a.b.c.d’</em>. Choice of these names is entirely up to the developer who is using logging.</p> <p>All calls to this function with a given name return the same logger instance. This means that logger instances never need to be passed between different parts of an application.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.getLoggerClass">
<code>logging.getLoggerClass()</code> </dt> <dd>
<p>Return either the standard <a class="reference internal" href="#logging.Logger" title="logging.Logger"><code>Logger</code></a> class, or the last class passed to <a class="reference internal" href="#logging.setLoggerClass" title="logging.setLoggerClass"><code>setLoggerClass()</code></a>. This function may be called from within a new class definition, to ensure that installing a customized <a class="reference internal" href="#logging.Logger" title="logging.Logger"><code>Logger</code></a> class will not undo customizations already applied by other code. For example:</p> <pre data-language="python">class MyLogger(logging.getLoggerClass()):
    # ... override behaviour here
</pre> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.getLogRecordFactory">
<code>logging.getLogRecordFactory()</code> </dt> <dd>
<p>Return a callable which is used to create a <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2: </span>This function has been provided, along with <a class="reference internal" href="#logging.setLogRecordFactory" title="logging.setLogRecordFactory"><code>setLogRecordFactory()</code></a>, to allow developers more control over how the <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> representing a logging event is constructed.</p> </div> <p>See <a class="reference internal" href="#logging.setLogRecordFactory" title="logging.setLogRecordFactory"><code>setLogRecordFactory()</code></a> for more information about the how the factory is called.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.debug">
<code>logging.debug(msg, *args, **kwargs)</code> </dt> <dd>
<p>Logs a message with level <a class="reference internal" href="#logging.DEBUG" title="logging.DEBUG"><code>DEBUG</code></a> on the root logger. The <em>msg</em> is the message format string, and the <em>args</em> are the arguments which are merged into <em>msg</em> using the string formatting operator. (Note that this means that you can use keywords in the format string, together with a single dictionary argument.)</p> <p>There are three keyword arguments in <em>kwargs</em> which are inspected: <em>exc_info</em> which, if it does not evaluate as false, causes exception information to be added to the logging message. If an exception tuple (in the format returned by <a class="reference internal" href="sys#sys.exc_info" title="sys.exc_info"><code>sys.exc_info()</code></a>) or an exception instance is provided, it is used; otherwise, <a class="reference internal" href="sys#sys.exc_info" title="sys.exc_info"><code>sys.exc_info()</code></a> is called to get the exception information.</p> <p>The second optional keyword argument is <em>stack_info</em>, which defaults to <code>False</code>. If true, stack information is added to the logging message, including the actual logging call. Note that this is not the same stack information as that displayed through specifying <em>exc_info</em>: The former is stack frames from the bottom of the stack up to the logging call in the current thread, whereas the latter is information about stack frames which have been unwound, following an exception, while searching for exception handlers.</p> <p>You can specify <em>stack_info</em> independently of <em>exc_info</em>, e.g. to just show how you got to a certain point in your code, even when no exceptions were raised. The stack frames are printed following a header line which says:</p> <pre data-language="none">Stack (most recent call last):
</pre> <p>This mimics the <code>Traceback (most recent call last):</code> which is used when displaying exception frames.</p> <p>The third optional keyword argument is <em>extra</em> which can be used to pass a dictionary which is used to populate the __dict__ of the LogRecord created for the logging event with user-defined attributes. These custom attributes can then be used as you like. For example, they could be incorporated into logged messages. For example:</p> <pre data-language="python">FORMAT = '%(asctime)s %(clientip)-15s %(user)-8s %(message)s'
logging.basicConfig(format=FORMAT)
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logging.warning('Protocol problem: %s', 'connection reset', extra=d)
</pre> <p>would print something like:</p> <pre data-language="none">2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset
</pre> <p>The keys in the dictionary passed in <em>extra</em> should not clash with the keys used by the logging system. (See the <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code>Formatter</code></a> documentation for more information on which keys are used by the logging system.)</p> <p>If you choose to use these attributes in logged messages, you need to exercise some care. In the above example, for instance, the <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code>Formatter</code></a> has been set up with a format string which expects ‘clientip’ and ‘user’ in the attribute dictionary of the LogRecord. If these are missing, the message will not be logged because a string formatting exception will occur. So in this case, you always need to pass the <em>extra</em> dictionary with these keys.</p> <p>While this might be annoying, this feature is intended for use in specialized circumstances, such as multi-threaded servers where the same code executes in many contexts, and interesting conditions which arise are dependent on this context (such as remote client IP address and authenticated user name, in the above example). In such circumstances, it is likely that specialized <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code>Formatter</code></a>s would be used with particular <a class="reference internal" href="#logging.Handler" title="logging.Handler"><code>Handler</code></a>s.</p> <p>This function (as well as <a class="reference internal" href="#logging.info" title="logging.info"><code>info()</code></a>, <a class="reference internal" href="#logging.warning" title="logging.warning"><code>warning()</code></a>, <a class="reference internal" href="#logging.error" title="logging.error"><code>error()</code></a> and <a class="reference internal" href="#logging.critical" title="logging.critical"><code>critical()</code></a>) will call <a class="reference internal" href="#logging.basicConfig" title="logging.basicConfig"><code>basicConfig()</code></a> if the root logger doesn’t have any handler attached.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>The <em>stack_info</em> parameter was added.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.info">
<code>logging.info(msg, *args, **kwargs)</code> </dt> <dd>
<p>Logs a message with level <a class="reference internal" href="#logging.INFO" title="logging.INFO"><code>INFO</code></a> on the root logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code>debug()</code></a>.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.warning">
<code>logging.warning(msg, *args, **kwargs)</code> </dt> <dd>
<p>Logs a message with level <a class="reference internal" href="#logging.WARNING" title="logging.WARNING"><code>WARNING</code></a> on the root logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code>debug()</code></a>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>There is an obsolete function <code>warn</code> which is functionally identical to <code>warning</code>. As <code>warn</code> is deprecated, please do not use it - use <code>warning</code> instead.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.error">
<code>logging.error(msg, *args, **kwargs)</code> </dt> <dd>
<p>Logs a message with level <a class="reference internal" href="#logging.ERROR" title="logging.ERROR"><code>ERROR</code></a> on the root logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code>debug()</code></a>.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.critical">
<code>logging.critical(msg, *args, **kwargs)</code> </dt> <dd>
<p>Logs a message with level <a class="reference internal" href="#logging.CRITICAL" title="logging.CRITICAL"><code>CRITICAL</code></a> on the root logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code>debug()</code></a>.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.exception">
<code>logging.exception(msg, *args, **kwargs)</code> </dt> <dd>
<p>Logs a message with level <a class="reference internal" href="#logging.ERROR" title="logging.ERROR"><code>ERROR</code></a> on the root logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code>debug()</code></a>. Exception info is added to the logging message. This function should only be called from an exception handler.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.log">
<code>logging.log(level, msg, *args, **kwargs)</code> </dt> <dd>
<p>Logs a message with level <em>level</em> on the root logger. The other arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code>debug()</code></a>.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.disable">
<code>logging.disable(level=CRITICAL)</code> </dt> <dd>
<p>Provides an overriding level <em>level</em> for all loggers which takes precedence over the logger’s own level. When the need arises to temporarily throttle logging output down across the whole application, this function can be useful. Its effect is to disable all logging calls of severity <em>level</em> and below, so that if you call it with a value of INFO, then all INFO and DEBUG events would be discarded, whereas those of severity WARNING and above would be processed according to the logger’s effective level. If <code>logging.disable(logging.NOTSET)</code> is called, it effectively removes this overriding level, so that logging output again depends on the effective levels of individual loggers.</p> <p>Note that if you have defined any custom logging level higher than <code>CRITICAL</code> (this is not recommended), you won’t be able to rely on the default value for the <em>level</em> parameter, but will have to explicitly supply a suitable value.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The <em>level</em> parameter was defaulted to level <code>CRITICAL</code>. See <a class="reference external" href="https://bugs.python.org/issue?@action=redirect&amp;bpo=28524">bpo-28524</a> for more information about this change.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.addLevelName">
<code>logging.addLevelName(level, levelName)</code> </dt> <dd>
<p>Associates level <em>level</em> with text <em>levelName</em> in an internal dictionary, which is used to map numeric levels to a textual representation, for example when a <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code>Formatter</code></a> formats a message. This function can also be used to define your own levels. The only constraints are that all levels used must be registered using this function, levels should be positive integers and they should increase in increasing order of severity.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>If you are thinking of defining your own levels, please see the section on <a class="reference internal" href="../howto/logging#custom-levels"><span class="std std-ref">Custom Levels</span></a>.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.getLevelNamesMapping">
<code>logging.getLevelNamesMapping()</code> </dt> <dd>
<p>Returns a mapping from level names to their corresponding logging levels. For example, the string “CRITICAL” maps to <a class="reference internal" href="#logging.CRITICAL" title="logging.CRITICAL"><code>CRITICAL</code></a>. The returned mapping is copied from an internal mapping on each call to this function.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.getLevelName">
<code>logging.getLevelName(level)</code> </dt> <dd>
<p>Returns the textual or numeric representation of logging level <em>level</em>.</p> <p>If <em>level</em> is one of the predefined levels <a class="reference internal" href="#logging.CRITICAL" title="logging.CRITICAL"><code>CRITICAL</code></a>, <a class="reference internal" href="#logging.ERROR" title="logging.ERROR"><code>ERROR</code></a>, <a class="reference internal" href="#logging.WARNING" title="logging.WARNING"><code>WARNING</code></a>, <a class="reference internal" href="#logging.INFO" title="logging.INFO"><code>INFO</code></a> or <a class="reference internal" href="#logging.DEBUG" title="logging.DEBUG"><code>DEBUG</code></a> then you get the corresponding string. If you have associated levels with names using <a class="reference internal" href="#logging.addLevelName" title="logging.addLevelName"><code>addLevelName()</code></a> then the name you have associated with <em>level</em> is returned. If a numeric value corresponding to one of the defined levels is passed in, the corresponding string representation is returned.</p> <p>The <em>level</em> parameter also accepts a string representation of the level such as ‘INFO’. In such cases, this functions returns the corresponding numeric value of the level.</p> <p>If no matching numeric or string value is passed in, the string ‘Level %s’ % level is returned.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Levels are internally integers (as they need to be compared in the logging logic). This function is used to convert between an integer level and the level name displayed in the formatted log output by means of the <code>%(levelname)s</code> format specifier (see <a class="reference internal" href="#logrecord-attributes"><span class="std std-ref">LogRecord attributes</span></a>), and vice versa.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>In Python versions earlier than 3.4, this function could also be passed a text level, and would return the corresponding numeric value of the level. This undocumented behaviour was considered a mistake, and was removed in Python 3.4, but reinstated in 3.4.2 due to retain backward compatibility.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.getHandlerByName">
<code>logging.getHandlerByName(name)</code> </dt> <dd>
<p>Returns a handler with the specified <em>name</em>, or <code>None</code> if there is no handler with that name.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.getHandlerNames">
<code>logging.getHandlerNames()</code> </dt> <dd>
<p>Returns an immutable set of all known handler names.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.makeLogRecord">
<code>logging.makeLogRecord(attrdict)</code> </dt> <dd>
<p>Creates and returns a new <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> instance whose attributes are defined by <em>attrdict</em>. This function is useful for taking a pickled <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> attribute dictionary, sent over a socket, and reconstituting it as a <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> instance at the receiving end.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.basicConfig">
<code>logging.basicConfig(**kwargs)</code> </dt> <dd>
<p>Does basic configuration for the logging system by creating a <a class="reference internal" href="logging.handlers#logging.StreamHandler" title="logging.StreamHandler"><code>StreamHandler</code></a> with a default <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code>Formatter</code></a> and adding it to the root logger. The functions <a class="reference internal" href="#logging.debug" title="logging.debug"><code>debug()</code></a>, <a class="reference internal" href="#logging.info" title="logging.info"><code>info()</code></a>, <a class="reference internal" href="#logging.warning" title="logging.warning"><code>warning()</code></a>, <a class="reference internal" href="#logging.error" title="logging.error"><code>error()</code></a> and <a class="reference internal" href="#logging.critical" title="logging.critical"><code>critical()</code></a> will call <a class="reference internal" href="#logging.basicConfig" title="logging.basicConfig"><code>basicConfig()</code></a> automatically if no handlers are defined for the root logger.</p> <p>This function does nothing if the root logger already has handlers configured, unless the keyword argument <em>force</em> is set to <code>True</code>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>This function should be called from the main thread before other threads are started. In versions of Python prior to 2.7.1 and 3.2, if this function is called from multiple threads, it is possible (in rare circumstances) that a handler will be added to the root logger more than once, leading to unexpected results such as messages being duplicated in the log.</p> </div> <p>The following keyword arguments are supported.</p> <table class="docutils align-default">  <thead> <tr>
<th class="head"><p>Format</p></th> <th class="head"><p>Description</p></th> </tr> </thead>  <tr>
<td><p><em>filename</em></p></td> <td><p>Specifies that a <a class="reference internal" href="logging.handlers#logging.FileHandler" title="logging.FileHandler"><code>FileHandler</code></a> be created, using the specified filename, rather than a <a class="reference internal" href="logging.handlers#logging.StreamHandler" title="logging.StreamHandler"><code>StreamHandler</code></a>.</p></td> </tr> <tr>
<td><p><em>filemode</em></p></td> <td><p>If <em>filename</em> is specified, open the file in this <a class="reference internal" href="functions#filemodes"><span class="std std-ref">mode</span></a>. Defaults to <code>'a'</code>.</p></td> </tr> <tr>
<td><p><em>format</em></p></td> <td><p>Use the specified format string for the handler. Defaults to attributes <code>levelname</code>, <code>name</code> and <code>message</code> separated by colons.</p></td> </tr> <tr>
<td><p><em>datefmt</em></p></td> <td><p>Use the specified date/time format, as accepted by <a class="reference internal" href="time#time.strftime" title="time.strftime"><code>time.strftime()</code></a>.</p></td> </tr> <tr>
<td><p><em>style</em></p></td> <td><p>If <em>format</em> is specified, use this style for the format string. One of <code>'%'</code>, <code>'{'</code> or <code>'$'</code> for <a class="reference internal" href="stdtypes#old-string-formatting"><span class="std std-ref">printf-style</span></a>, <a class="reference internal" href="stdtypes#str.format" title="str.format"><code>str.format()</code></a> or <a class="reference internal" href="string#string.Template" title="string.Template"><code>string.Template</code></a> respectively. Defaults to <code>'%'</code>.</p></td> </tr> <tr>
<td><p><em>level</em></p></td> <td><p>Set the root logger level to the specified <a class="reference internal" href="#levels"><span class="std std-ref">level</span></a>.</p></td> </tr> <tr>
<td><p><em>stream</em></p></td> <td><p>Use the specified stream to initialize the <a class="reference internal" href="logging.handlers#logging.StreamHandler" title="logging.StreamHandler"><code>StreamHandler</code></a>. Note that this argument is incompatible with <em>filename</em> - if both are present, a <code>ValueError</code> is raised.</p></td> </tr> <tr>
<td><p><em>handlers</em></p></td> <td><p>If specified, this should be an iterable of already created handlers to add to the root logger. Any handlers which don’t already have a formatter set will be assigned the default formatter created in this function. Note that this argument is incompatible with <em>filename</em> or <em>stream</em> - if both are present, a <code>ValueError</code> is raised.</p></td> </tr> <tr>
<td><p><em>force</em></p></td> <td><p>If this keyword argument is specified as true, any existing handlers attached to the root logger are removed and closed, before carrying out the configuration as specified by the other arguments.</p></td> </tr> <tr>
<td><p><em>encoding</em></p></td> <td><p>If this keyword argument is specified along with <em>filename</em>, its value is used when the <a class="reference internal" href="logging.handlers#logging.FileHandler" title="logging.FileHandler"><code>FileHandler</code></a> is created, and thus used when opening the output file.</p></td> </tr> <tr>
<td><p><em>errors</em></p></td> <td><p>If this keyword argument is specified along with <em>filename</em>, its value is used when the <a class="reference internal" href="logging.handlers#logging.FileHandler" title="logging.FileHandler"><code>FileHandler</code></a> is created, and thus used when opening the output file. If not specified, the value ‘backslashreplace’ is used. Note that if <code>None</code> is specified, it will be passed as such to <a class="reference internal" href="functions#open" title="open"><code>open()</code></a>, which means that it will be treated the same as passing ‘errors’.</p></td> </tr>  </table> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>The <em>style</em> argument was added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>The <em>handlers</em> argument was added. Additional checks were added to catch situations where incompatible arguments are specified (e.g. <em>handlers</em> together with <em>stream</em> or <em>filename</em>, or <em>stream</em> together with <em>filename</em>).</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>The <em>force</em> argument was added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>The <em>encoding</em> and <em>errors</em> arguments were added.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.shutdown">
<code>logging.shutdown()</code> </dt> <dd>
<p>Informs the logging system to perform an orderly shutdown by flushing and closing all handlers. This should be called at application exit and no further use of the logging system should be made after this call.</p> <p>When the logging module is imported, it registers this function as an exit handler (see <a class="reference internal" href="atexit#module-atexit" title="atexit: Register and execute cleanup functions."><code>atexit</code></a>), so normally there’s no need to do that manually.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.setLoggerClass">
<code>logging.setLoggerClass(klass)</code> </dt> <dd>
<p>Tells the logging system to use the class <em>klass</em> when instantiating a logger. The class should define <code>__init__()</code> such that only a name argument is required, and the <code>__init__()</code> should call <code>Logger.__init__()</code>. This function is typically called before any loggers are instantiated by applications which need to use custom logger behavior. After this call, as at any other time, do not instantiate loggers directly using the subclass: continue to use the <a class="reference internal" href="#logging.getLogger" title="logging.getLogger"><code>logging.getLogger()</code></a> API to get your loggers.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="logging.setLogRecordFactory">
<code>logging.setLogRecordFactory(factory)</code> </dt> <dd>
<p>Set a callable which is used to create a <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a>.</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd">
<p><strong>factory</strong> – The factory callable to be used to instantiate a log record.</p> </dd> </dl> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2: </span>This function has been provided, along with <a class="reference internal" href="#logging.getLogRecordFactory" title="logging.getLogRecordFactory"><code>getLogRecordFactory()</code></a>, to allow developers more control over how the <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> representing a logging event is constructed.</p> </div> <p>The factory has the following signature:</p> <p><code>factory(name, level, fn, lno, msg, args, exc_info, func=None, sinfo=None, **kwargs)</code></p>  <dl class="field-list simple"> <dt class="field-odd">name</dt> <dd class="field-odd">
<p>The logger name.</p> </dd> <dt class="field-even">level</dt> <dd class="field-even">
<p>The logging level (numeric).</p> </dd> <dt class="field-odd">fn</dt> <dd class="field-odd">
<p>The full pathname of the file where the logging call was made.</p> </dd> <dt class="field-even">lno</dt> <dd class="field-even">
<p>The line number in the file where the logging call was made.</p> </dd> <dt class="field-odd">msg</dt> <dd class="field-odd">
<p>The logging message.</p> </dd> <dt class="field-even">args</dt> <dd class="field-even">
<p>The arguments for the logging message.</p> </dd> <dt class="field-odd">exc_info</dt> <dd class="field-odd">
<p>An exception tuple, or <code>None</code>.</p> </dd> <dt class="field-even">func</dt> <dd class="field-even">
<p>The name of the function or method which invoked the logging call.</p> </dd> <dt class="field-odd">sinfo</dt> <dd class="field-odd">
<p>A stack traceback such as is provided by <a class="reference internal" href="traceback#traceback.print_stack" title="traceback.print_stack"><code>traceback.print_stack()</code></a>, showing the call hierarchy.</p> </dd> <dt class="field-even">kwargs</dt> <dd class="field-even">
<p>Additional keyword arguments.</p> </dd> </dl>  </dd>
</dl> </section> <section id="module-level-attributes"> <h2>Module-Level Attributes</h2> <dl class="py attribute"> <dt class="sig sig-object py" id="logging.lastResort">
<code>logging.lastResort</code> </dt> <dd>
<p>A “handler of last resort” is available through this attribute. This is a <a class="reference internal" href="logging.handlers#logging.StreamHandler" title="logging.StreamHandler"><code>StreamHandler</code></a> writing to <code>sys.stderr</code> with a level of <code>WARNING</code>, and is used to handle logging events in the absence of any logging configuration. The end result is to just print the message to <code>sys.stderr</code>. This replaces the earlier error message saying that “no handlers could be found for logger XYZ”. If you need the earlier behaviour for some reason, <code>lastResort</code> can be set to <code>None</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
</dl> </section> <section id="integration-with-the-warnings-module"> <h2>Integration with the warnings module</h2> <p>The <a class="reference internal" href="#logging.captureWarnings" title="logging.captureWarnings"><code>captureWarnings()</code></a> function can be used to integrate <a class="reference internal" href="#module-logging" title="logging: Flexible event logging system for applications."><code>logging</code></a> with the <a class="reference internal" href="warnings#module-warnings" title="warnings: Issue warning messages and control their disposition."><code>warnings</code></a> module.</p> <dl class="py function"> <dt class="sig sig-object py" id="logging.captureWarnings">
<code>logging.captureWarnings(capture)</code> </dt> <dd>
<p>This function is used to turn the capture of warnings by logging on and off.</p> <p>If <em>capture</em> is <code>True</code>, warnings issued by the <a class="reference internal" href="warnings#module-warnings" title="warnings: Issue warning messages and control their disposition."><code>warnings</code></a> module will be redirected to the logging system. Specifically, a warning will be formatted using <a class="reference internal" href="warnings#warnings.formatwarning" title="warnings.formatwarning"><code>warnings.formatwarning()</code></a> and the resulting string logged to a logger named <code>'py.warnings'</code> with a severity of <a class="reference internal" href="#logging.WARNING" title="logging.WARNING"><code>WARNING</code></a>.</p> <p>If <em>capture</em> is <code>False</code>, the redirection of warnings to the logging system will stop, and warnings will be redirected to their original destinations (i.e. those in effect before <code>captureWarnings(True)</code> was called).</p> </dd>
</dl> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt>
<code>Module</code> <a class="reference internal" href="logging.config#module-logging.config" title="logging.config: Configuration of the logging module."><code>logging.config</code></a>
</dt>
<dd>
<p>Configuration API for the logging module.</p> </dd> <dt>
<code>Module</code> <a class="reference internal" href="logging.handlers#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code>logging.handlers</code></a>
</dt>
<dd>
<p>Useful handlers included with the logging module.</p> </dd> <dt>
<span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-0282/"><strong>PEP 282</strong></a> - A Logging System</dt>
<dd>
<p>The proposal which described this feature for inclusion in the Python standard library.</p> </dd> <dt><a class="reference external" href="https://old.red-dove.com/python_logging.html">Original Python logging package</a></dt>
<dd>
<p>This is the original source for the <a class="reference internal" href="#module-logging" title="logging: Flexible event logging system for applications."><code>logging</code></a> package. The version of the package available from this site is suitable for use with Python 1.5.2, 2.1.x and 2.2.x, which do not include the <a class="reference internal" href="#module-logging" title="logging: Flexible event logging system for applications."><code>logging</code></a> package in the standard library.</p> </dd> </dl> </div> </section> <div class="_attribution">
  <p class="_attribution-p">
    &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
    <a href="https://docs.python.org/3.12/library/logging.html" class="_attribution-link">https://docs.python.org/3.12/library/logging.html</a>
  </p>
</div>