~dkuhlman/python-training-materials/Materials

« back to all changes in this revision

Viewing changes to python-3.5.2-docs-html/howto/logging.html

  • Committer: Dave Kuhlman
  • Date: 2017-04-15 16:24:56 UTC
  • Revision ID: dkuhlman@davekuhlman.org-20170415162456-iav9vozzg4iwqwv3
Updated docs

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 
2
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
3
 
 
4
 
 
5
<html xmlns="http://www.w3.org/1999/xhtml">
 
6
  <head>
 
7
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 
8
    
 
9
    <title>Logging HOWTO &mdash; Python 3.5.2 documentation</title>
 
10
    
 
11
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
 
12
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
 
13
    
 
14
    <script type="text/javascript">
 
15
      var DOCUMENTATION_OPTIONS = {
 
16
        URL_ROOT:    '../',
 
17
        VERSION:     '3.5.2',
 
18
        COLLAPSE_INDEX: false,
 
19
        FILE_SUFFIX: '.html',
 
20
        HAS_SOURCE:  true
 
21
      };
 
22
    </script>
 
23
    <script type="text/javascript" src="../_static/jquery.js"></script>
 
24
    <script type="text/javascript" src="../_static/underscore.js"></script>
 
25
    <script type="text/javascript" src="../_static/doctools.js"></script>
 
26
    <script type="text/javascript" src="../_static/sidebar.js"></script>
 
27
    <link rel="search" type="application/opensearchdescription+xml"
 
28
          title="Search within Python 3.5.2 documentation"
 
29
          href="../_static/opensearch.xml"/>
 
30
    <link rel="author" title="About these documents" href="../about.html" />
 
31
    <link rel="copyright" title="Copyright" href="../copyright.html" />
 
32
    <link rel="top" title="Python 3.5.2 documentation" href="../contents.html" />
 
33
    <link rel="up" title="Python HOWTOs" href="index.html" />
 
34
    <link rel="next" title="Logging Cookbook" href="logging-cookbook.html" />
 
35
    <link rel="prev" title="Functional Programming HOWTO" href="functional.html" />
 
36
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
 
37
    
 
38
    <script type="text/javascript" src="../_static/copybutton.js"></script>
 
39
    <script type="text/javascript" src="../_static/version_switch.js"></script>
 
40
    
 
41
    
 
42
 
 
43
 
 
44
  </head>
 
45
  <body role="document">  
 
46
    <div class="related" role="navigation" aria-label="related navigation">
 
47
      <h3>Navigation</h3>
 
48
      <ul>
 
49
        <li class="right" style="margin-right: 10px">
 
50
          <a href="../genindex.html" title="General Index"
 
51
             accesskey="I">index</a></li>
 
52
        <li class="right" >
 
53
          <a href="../py-modindex.html" title="Python Module Index"
 
54
             >modules</a> |</li>
 
55
        <li class="right" >
 
56
          <a href="logging-cookbook.html" title="Logging Cookbook"
 
57
             accesskey="N">next</a> |</li>
 
58
        <li class="right" >
 
59
          <a href="functional.html" title="Functional Programming HOWTO"
 
60
             accesskey="P">previous</a> |</li>
 
61
        <li><img src="../_static/py.png" alt=""
 
62
                 style="vertical-align: middle; margin-top: -1px"/></li>
 
63
        <li><a href="https://www.python.org/">Python</a> &raquo;</li>
 
64
        <li>
 
65
          <span class="version_switcher_placeholder">3.5.2</span>
 
66
          <a href="../index.html">Documentation </a> &raquo;
 
67
        </li>
 
68
 
 
69
          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &raquo;</li>
 
70
    <li class="right">
 
71
        
 
72
 
 
73
    <div class="inline-search" style="display: none" role="search">
 
74
        <form class="inline-search" action="../search.html" method="get">
 
75
          <input placeholder="Quick search" type="text" name="q" />
 
76
          <input type="submit" value="Go" />
 
77
          <input type="hidden" name="check_keywords" value="yes" />
 
78
          <input type="hidden" name="area" value="default" />
 
79
        </form>
 
80
    </div>
 
81
    <script type="text/javascript">$('.inline-search').show(0);</script>
 
82
         |
 
83
    </li>
 
84
 
 
85
      </ul>
 
86
    </div>    
 
87
 
 
88
    <div class="document">
 
89
      <div class="documentwrapper">
 
90
        <div class="bodywrapper">
 
91
          <div class="body" role="main">
 
92
            
 
93
  <div class="section" id="logging-howto">
 
94
<h1>Logging HOWTO<a class="headerlink" href="#logging-howto" title="Permalink to this headline">¶</a></h1>
 
95
<table class="docutils field-list" frame="void" rules="none">
 
96
<col class="field-name" />
 
97
<col class="field-body" />
 
98
<tbody valign="top">
 
99
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">Vinay Sajip &lt;vinay_sajip at red-dove dot com&gt;</td>
 
100
</tr>
 
101
</tbody>
 
102
</table>
 
103
<div class="section" id="basic-logging-tutorial">
 
104
<span id="logging-basic-tutorial"></span><h2>Basic Logging Tutorial<a class="headerlink" href="#basic-logging-tutorial" title="Permalink to this headline">¶</a></h2>
 
105
<p>Logging is a means of tracking events that happen when some software runs. The
 
106
software&#8217;s developer adds logging calls to their code to indicate that certain
 
107
events have occurred. An event is described by a descriptive message which can
 
108
optionally contain variable data (i.e. data that is potentially different for
 
109
each occurrence of the event). Events also have an importance which the
 
110
developer ascribes to the event; the importance can also be called the <em>level</em>
 
111
or <em>severity</em>.</p>
 
112
<div class="section" id="when-to-use-logging">
 
113
<h3>When to use logging<a class="headerlink" href="#when-to-use-logging" title="Permalink to this headline">¶</a></h3>
 
114
<p>Logging provides a set of convenience functions for simple logging usage. These
 
115
are <a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal"><span class="pre">debug()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><code class="xref py py-func docutils literal"><span class="pre">info()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><code class="xref py py-func docutils literal"><span class="pre">warning()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.error" title="logging.error"><code class="xref py py-func docutils literal"><span class="pre">error()</span></code></a> and
 
116
<a class="reference internal" href="../library/logging.html#logging.critical" title="logging.critical"><code class="xref py py-func docutils literal"><span class="pre">critical()</span></code></a>. To determine when to use logging, see the table below, which
 
117
states, for each of a set of common tasks, the best tool to use for it.</p>
 
118
<table border="1" class="docutils">
 
119
<colgroup>
 
120
<col width="49%" />
 
121
<col width="51%" />
 
122
</colgroup>
 
123
<thead valign="bottom">
 
124
<tr class="row-odd"><th class="head">Task you want to perform</th>
 
125
<th class="head">The best tool for the task</th>
 
126
</tr>
 
127
</thead>
 
128
<tbody valign="top">
 
129
<tr class="row-even"><td>Display console output for ordinary
 
130
usage of a command line script or
 
131
program</td>
 
132
<td><a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal"><span class="pre">print()</span></code></a></td>
 
133
</tr>
 
134
<tr class="row-odd"><td>Report events that occur during
 
135
normal operation of a program (e.g.
 
136
for status monitoring or fault
 
137
investigation)</td>
 
138
<td><a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><code class="xref py py-func docutils literal"><span class="pre">logging.info()</span></code></a> (or
 
139
<a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal"><span class="pre">logging.debug()</span></code></a> for very
 
140
detailed output for diagnostic
 
141
purposes)</td>
 
142
</tr>
 
143
<tr class="row-even"><td>Issue a warning regarding a
 
144
particular runtime event</td>
 
145
<td><p class="first"><a class="reference internal" href="../library/warnings.html#warnings.warn" title="warnings.warn"><code class="xref py py-func docutils literal"><span class="pre">warnings.warn()</span></code></a> in library
 
146
code if the issue is avoidable and
 
147
the client application should be
 
148
modified to eliminate the warning</p>
 
149
<p class="last"><a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><code class="xref py py-func docutils literal"><span class="pre">logging.warning()</span></code></a> if there is
 
150
nothing the client application can do
 
151
about the situation, but the event
 
152
should still be noted</p>
 
153
</td>
 
154
</tr>
 
155
<tr class="row-odd"><td>Report an error regarding a
 
156
particular runtime event</td>
 
157
<td>Raise an exception</td>
 
158
</tr>
 
159
<tr class="row-even"><td>Report suppression of an error
 
160
without raising an exception (e.g.
 
161
error handler in a long-running
 
162
server process)</td>
 
163
<td><a class="reference internal" href="../library/logging.html#logging.error" title="logging.error"><code class="xref py py-func docutils literal"><span class="pre">logging.error()</span></code></a>,
 
164
<a class="reference internal" href="../library/logging.html#logging.exception" title="logging.exception"><code class="xref py py-func docutils literal"><span class="pre">logging.exception()</span></code></a> or
 
165
<a class="reference internal" href="../library/logging.html#logging.critical" title="logging.critical"><code class="xref py py-func docutils literal"><span class="pre">logging.critical()</span></code></a> as
 
166
appropriate for the specific error
 
167
and application domain</td>
 
168
</tr>
 
169
</tbody>
 
170
</table>
 
171
<p>The logging functions are named after the level or severity of the events
 
172
they are used to track. The standard levels and their applicability are
 
173
described below (in increasing order of severity):</p>
 
174
<table border="1" class="docutils">
 
175
<colgroup>
 
176
<col width="24%" />
 
177
<col width="76%" />
 
178
</colgroup>
 
179
<thead valign="bottom">
 
180
<tr class="row-odd"><th class="head">Level</th>
 
181
<th class="head">When it&#8217;s used</th>
 
182
</tr>
 
183
</thead>
 
184
<tbody valign="top">
 
185
<tr class="row-even"><td><code class="docutils literal"><span class="pre">DEBUG</span></code></td>
 
186
<td>Detailed information, typically of interest
 
187
only when diagnosing problems.</td>
 
188
</tr>
 
189
<tr class="row-odd"><td><code class="docutils literal"><span class="pre">INFO</span></code></td>
 
190
<td>Confirmation that things are working as
 
191
expected.</td>
 
192
</tr>
 
193
<tr class="row-even"><td><code class="docutils literal"><span class="pre">WARNING</span></code></td>
 
194
<td>An indication that something unexpected
 
195
happened, or indicative of some problem in
 
196
the near future (e.g. &#8216;disk space low&#8217;).
 
197
The software is still working as expected.</td>
 
198
</tr>
 
199
<tr class="row-odd"><td><code class="docutils literal"><span class="pre">ERROR</span></code></td>
 
200
<td>Due to a more serious problem, the software
 
201
has not been able to perform some function.</td>
 
202
</tr>
 
203
<tr class="row-even"><td><code class="docutils literal"><span class="pre">CRITICAL</span></code></td>
 
204
<td>A serious error, indicating that the program
 
205
itself may be unable to continue running.</td>
 
206
</tr>
 
207
</tbody>
 
208
</table>
 
209
<p>The default level is <code class="docutils literal"><span class="pre">WARNING</span></code>, which means that only events of this level
 
210
and above will be tracked, unless the logging package is configured to do
 
211
otherwise.</p>
 
212
<p>Events that are tracked can be handled in different ways. The simplest way of
 
213
handling tracked events is to print them to the console. Another common way
 
214
is to write them to a disk file.</p>
 
215
</div>
 
216
<div class="section" id="a-simple-example">
 
217
<span id="howto-minimal-example"></span><h3>A simple example<a class="headerlink" href="#a-simple-example" title="Permalink to this headline">¶</a></h3>
 
218
<p>A very simple example is:</p>
 
219
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
 
220
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;Watch out!&#39;</span><span class="p">)</span>  <span class="c1"># will print a message to the console</span>
 
221
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;I told you so&#39;</span><span class="p">)</span>  <span class="c1"># will not print anything</span>
 
222
</pre></div>
 
223
</div>
 
224
<p>If you type these lines into a script and run it, you&#8217;ll see:</p>
 
225
<div class="highlight-none"><div class="highlight"><pre><span></span>WARNING:root:Watch out!
 
226
</pre></div>
 
227
</div>
 
228
<p>printed out on the console. The <code class="docutils literal"><span class="pre">INFO</span></code> message doesn&#8217;t appear because the
 
229
default level is <code class="docutils literal"><span class="pre">WARNING</span></code>. The printed message includes the indication of
 
230
the level and the description of the event provided in the logging call, i.e.
 
231
&#8216;Watch out!&#8217;. Don&#8217;t worry about the &#8216;root&#8217; part for now: it will be explained
 
232
later. The actual output can be formatted quite flexibly if you need that;
 
233
formatting options will also be explained later.</p>
 
234
</div>
 
235
<div class="section" id="logging-to-a-file">
 
236
<h3>Logging to a file<a class="headerlink" href="#logging-to-a-file" title="Permalink to this headline">¶</a></h3>
 
237
<p>A very common situation is that of recording logging events in a file, so let&#8217;s
 
238
look at that next. Be sure to try the following in a newly-started Python
 
239
interpreter, and don&#8217;t just continue from the session described above:</p>
 
240
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
 
241
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="s1">&#39;example.log&#39;</span><span class="p">,</span><span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
 
242
<span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;This message should go to the log file&#39;</span><span class="p">)</span>
 
243
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;So should this&#39;</span><span class="p">)</span>
 
244
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;And this, too&#39;</span><span class="p">)</span>
 
245
</pre></div>
 
246
</div>
 
247
<p>And now if we open the file and look at what we have, we should find the log
 
248
messages:</p>
 
249
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="n">DEBUG</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">This</span> <span class="n">message</span> <span class="n">should</span> <span class="n">go</span> <span class="n">to</span> <span class="n">the</span> <span class="n">log</span> <span class="n">file</span>
 
250
<span class="n">INFO</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">So</span> <span class="n">should</span> <span class="n">this</span>
 
251
<span class="n">WARNING</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">And</span> <span class="n">this</span><span class="p">,</span> <span class="n">too</span>
 
252
</pre></div>
 
253
</div>
 
254
<p>This example also shows how you can set the logging level which acts as the
 
255
threshold for tracking. In this case, because we set the threshold to
 
256
<code class="docutils literal"><span class="pre">DEBUG</span></code>, all of the messages were printed.</p>
 
257
<p>If you want to set the logging level from a command-line option such as:</p>
 
258
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="o">--</span><span class="n">log</span><span class="o">=</span><span class="n">INFO</span>
 
259
</pre></div>
 
260
</div>
 
261
<p>and you have the value of the parameter passed for <code class="docutils literal"><span class="pre">--log</span></code> in some variable
 
262
<em>loglevel</em>, you can use:</p>
 
263
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="nb">getattr</span><span class="p">(</span><span class="n">logging</span><span class="p">,</span> <span class="n">loglevel</span><span class="o">.</span><span class="n">upper</span><span class="p">())</span>
 
264
</pre></div>
 
265
</div>
 
266
<p>to get the value which you&#8217;ll pass to <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></code></a> via the <em>level</em>
 
267
argument. You may want to error check any user input value, perhaps as in the
 
268
following example:</p>
 
269
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="c1"># assuming loglevel is bound to the string value obtained from the</span>
 
270
<span class="c1"># command line argument. Convert to upper case to allow the user to</span>
 
271
<span class="c1"># specify --log=DEBUG or --log=debug</span>
 
272
<span class="n">numeric_level</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">logging</span><span class="p">,</span> <span class="n">loglevel</span><span class="o">.</span><span class="n">upper</span><span class="p">(),</span> <span class="kc">None</span><span class="p">)</span>
 
273
<span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">numeric_level</span><span class="p">,</span> <span class="nb">int</span><span class="p">):</span>
 
274
    <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s1">&#39;Invalid log level: </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">loglevel</span><span class="p">)</span>
 
275
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">level</span><span class="o">=</span><span class="n">numeric_level</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span>
 
276
</pre></div>
 
277
</div>
 
278
<p>The call to <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></code></a> should come <em>before</em> any calls to <a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal"><span class="pre">debug()</span></code></a>,
 
279
<a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><code class="xref py py-func docutils literal"><span class="pre">info()</span></code></a> etc. As it&#8217;s intended as a one-off simple configuration facility,
 
280
only the first call will actually do anything: subsequent calls are effectively
 
281
no-ops.</p>
 
282
<p>If you run the above script several times, the messages from successive runs
 
283
are appended to the file <em>example.log</em>. If you want each run to start afresh,
 
284
not remembering the messages from earlier runs, you can specify the <em>filemode</em>
 
285
argument, by changing the call in the above example to:</p>
 
286
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="s1">&#39;example.log&#39;</span><span class="p">,</span> <span class="n">filemode</span><span class="o">=</span><span class="s1">&#39;w&#39;</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
 
287
</pre></div>
 
288
</div>
 
289
<p>The output will be the same as before, but the log file is no longer appended
 
290
to, so the messages from earlier runs are lost.</p>
 
291
</div>
 
292
<div class="section" id="logging-from-multiple-modules">
 
293
<h3>Logging from multiple modules<a class="headerlink" href="#logging-from-multiple-modules" title="Permalink to this headline">¶</a></h3>
 
294
<p>If your program consists of multiple modules, here&#8217;s an example of how you
 
295
could organize logging in it:</p>
 
296
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="c1"># myapp.py</span>
 
297
<span class="kn">import</span> <span class="nn">logging</span>
 
298
<span class="kn">import</span> <span class="nn">mylib</span>
 
299
 
 
300
<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
 
301
    <span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="s1">&#39;myapp.log&#39;</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">)</span>
 
302
    <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Started&#39;</span><span class="p">)</span>
 
303
    <span class="n">mylib</span><span class="o">.</span><span class="n">do_something</span><span class="p">()</span>
 
304
    <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Finished&#39;</span><span class="p">)</span>
 
305
 
 
306
<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
 
307
    <span class="n">main</span><span class="p">()</span>
 
308
</pre></div>
 
309
</div>
 
310
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="c1"># mylib.py</span>
 
311
<span class="kn">import</span> <span class="nn">logging</span>
 
312
 
 
313
<span class="k">def</span> <span class="nf">do_something</span><span class="p">():</span>
 
314
    <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Doing something&#39;</span><span class="p">)</span>
 
315
</pre></div>
 
316
</div>
 
317
<p>If you run <em>myapp.py</em>, you should see this in <em>myapp.log</em>:</p>
 
318
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="n">INFO</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">Started</span>
 
319
<span class="n">INFO</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">Doing</span> <span class="n">something</span>
 
320
<span class="n">INFO</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">Finished</span>
 
321
</pre></div>
 
322
</div>
 
323
<p>which is hopefully what you were expecting to see. You can generalize this to
 
324
multiple modules, using the pattern in <em>mylib.py</em>. Note that for this simple
 
325
usage pattern, you won&#8217;t know, by looking in the log file, <em>where</em> in your
 
326
application your messages came from, apart from looking at the event
 
327
description. If you want to track the location of your messages, you&#8217;ll need
 
328
to refer to the documentation beyond the tutorial level &#8211; see
 
329
<a class="reference internal" href="#logging-advanced-tutorial"><span>Advanced Logging Tutorial</span></a>.</p>
 
330
</div>
 
331
<div class="section" id="logging-variable-data">
 
332
<h3>Logging variable data<a class="headerlink" href="#logging-variable-data" title="Permalink to this headline">¶</a></h3>
 
333
<p>To log variable data, use a format string for the event description message and
 
334
append the variable data as arguments. For example:</p>
 
335
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
 
336
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%s</span><span class="s1"> before you </span><span class="si">%s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;Look&#39;</span><span class="p">,</span> <span class="s1">&#39;leap!&#39;</span><span class="p">)</span>
 
337
</pre></div>
 
338
</div>
 
339
<p>will display:</p>
 
340
<div class="highlight-none"><div class="highlight"><pre><span></span>WARNING:root:Look before you leap!
 
341
</pre></div>
 
342
</div>
 
343
<p>As you can see, merging of variable data into the event description message
 
344
uses the old, %-style of string formatting. This is for backwards
 
345
compatibility: the logging package pre-dates newer formatting options such as
 
346
<a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal"><span class="pre">str.format()</span></code></a> and <a class="reference internal" href="../library/string.html#string.Template" title="string.Template"><code class="xref py py-class docutils literal"><span class="pre">string.Template</span></code></a>. These newer formatting
 
347
options <em>are</em> supported, but exploring them is outside the scope of this
 
348
tutorial: see <a class="reference internal" href="logging-cookbook.html#formatting-styles"><span>Using particular formatting styles throughout your application</span></a> for more information.</p>
 
349
</div>
 
350
<div class="section" id="changing-the-format-of-displayed-messages">
 
351
<h3>Changing the format of displayed messages<a class="headerlink" href="#changing-the-format-of-displayed-messages" title="Permalink to this headline">¶</a></h3>
 
352
<p>To change the format which is used to display messages, you need to
 
353
specify the format you want to use:</p>
 
354
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
 
355
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="nb">format</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(levelname)s</span><span class="s1">:</span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
 
356
<span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;This message should appear on the console&#39;</span><span class="p">)</span>
 
357
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;So should this&#39;</span><span class="p">)</span>
 
358
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;And this, too&#39;</span><span class="p">)</span>
 
359
</pre></div>
 
360
</div>
 
361
<p>which would print:</p>
 
362
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="n">DEBUG</span><span class="p">:</span><span class="n">This</span> <span class="n">message</span> <span class="n">should</span> <span class="n">appear</span> <span class="n">on</span> <span class="n">the</span> <span class="n">console</span>
 
363
<span class="n">INFO</span><span class="p">:</span><span class="n">So</span> <span class="n">should</span> <span class="n">this</span>
 
364
<span class="n">WARNING</span><span class="p">:</span><span class="n">And</span> <span class="n">this</span><span class="p">,</span> <span class="n">too</span>
 
365
</pre></div>
 
366
</div>
 
367
<p>Notice that the &#8216;root&#8217; which appeared in earlier examples has disappeared. For
 
368
a full set of things that can appear in format strings, you can refer to the
 
369
documentation for <a class="reference internal" href="../library/logging.html#logrecord-attributes"><span>LogRecord attributes</span></a>, but for simple usage, you just
 
370
need the <em>levelname</em> (severity), <em>message</em> (event description, including
 
371
variable data) and perhaps to display when the event occurred. This is
 
372
described in the next section.</p>
 
373
</div>
 
374
<div class="section" id="displaying-the-date-time-in-messages">
 
375
<h3>Displaying the date/time in messages<a class="headerlink" href="#displaying-the-date-time-in-messages" title="Permalink to this headline">¶</a></h3>
 
376
<p>To display the date and time of an event, you would place &#8216;%(asctime)s&#8217; in
 
377
your format string:</p>
 
378
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
 
379
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="nb">format</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">)</span>
 
380
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;is when this event was logged.&#39;</span><span class="p">)</span>
 
381
</pre></div>
 
382
</div>
 
383
<p>which should print something like this:</p>
 
384
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="mi">2010</span><span class="o">-</span><span class="mi">12</span><span class="o">-</span><span class="mi">12</span> <span class="mi">11</span><span class="p">:</span><span class="mi">41</span><span class="p">:</span><span class="mi">42</span><span class="p">,</span><span class="mi">612</span> <span class="ow">is</span> <span class="n">when</span> <span class="n">this</span> <span class="n">event</span> <span class="n">was</span> <span class="n">logged</span><span class="o">.</span>
 
385
</pre></div>
 
386
</div>
 
387
<p>The default format for date/time display (shown above) is ISO8601. If you need
 
388
more control over the formatting of the date/time, provide a <em>datefmt</em>
 
389
argument to <code class="docutils literal"><span class="pre">basicConfig</span></code>, as in this example:</p>
 
390
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
 
391
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="nb">format</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">datefmt</span><span class="o">=</span><span class="s1">&#39;%m/</span><span class="si">%d</span><span class="s1">/%Y %I:%M:%S %p&#39;</span><span class="p">)</span>
 
392
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;is when this event was logged.&#39;</span><span class="p">)</span>
 
393
</pre></div>
 
394
</div>
 
395
<p>which would display something like this:</p>
 
396
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="mi">12</span><span class="o">/</span><span class="mi">12</span><span class="o">/</span><span class="mi">2010</span> <span class="mi">11</span><span class="p">:</span><span class="mi">46</span><span class="p">:</span><span class="mi">36</span> <span class="n">AM</span> <span class="ow">is</span> <span class="n">when</span> <span class="n">this</span> <span class="n">event</span> <span class="n">was</span> <span class="n">logged</span><span class="o">.</span>
 
397
</pre></div>
 
398
</div>
 
399
<p>The format of the <em>datefmt</em> argument is the same as supported by
 
400
<a class="reference internal" href="../library/time.html#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal"><span class="pre">time.strftime()</span></code></a>.</p>
 
401
</div>
 
402
<div class="section" id="next-steps">
 
403
<h3>Next Steps<a class="headerlink" href="#next-steps" title="Permalink to this headline">¶</a></h3>
 
404
<p>That concludes the basic tutorial. It should be enough to get you up and
 
405
running with logging. There&#8217;s a lot more that the logging package offers, but
 
406
to get the best out of it, you&#8217;ll need to invest a little more of your time in
 
407
reading the following sections. If you&#8217;re ready for that, grab some of your
 
408
favourite beverage and carry on.</p>
 
409
<p>If your logging needs are simple, then use the above examples to incorporate
 
410
logging into your own scripts, and if you run into problems or don&#8217;t
 
411
understand something, please post a question on the comp.lang.python Usenet
 
412
group (available at <a class="reference external" href="https://groups.google.com/group/comp.lang.python">https://groups.google.com/group/comp.lang.python</a>) and you
 
413
should receive help before too long.</p>
 
414
<p>Still here? You can carry on reading the next few sections, which provide a
 
415
slightly more advanced/in-depth tutorial than the basic one above. After that,
 
416
you can take a look at the <a class="reference internal" href="logging-cookbook.html#logging-cookbook"><span>Logging Cookbook</span></a>.</p>
 
417
</div>
 
418
</div>
 
419
<div class="section" id="advanced-logging-tutorial">
 
420
<span id="logging-advanced-tutorial"></span><h2>Advanced Logging Tutorial<a class="headerlink" href="#advanced-logging-tutorial" title="Permalink to this headline">¶</a></h2>
 
421
<p>The logging library takes a modular approach and offers several categories
 
422
of components: loggers, handlers, filters, and formatters.</p>
 
423
<ul class="simple">
 
424
<li>Loggers expose the interface that application code directly uses.</li>
 
425
<li>Handlers send the log records (created by loggers) to the appropriate
 
426
destination.</li>
 
427
<li>Filters provide a finer grained facility for determining which log records
 
428
to output.</li>
 
429
<li>Formatters specify the layout of log records in the final output.</li>
 
430
</ul>
 
431
<p>Log event information is passed between loggers, handlers, filters and
 
432
formatters in a <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal"><span class="pre">LogRecord</span></code></a> instance.</p>
 
433
<p>Logging is performed by calling methods on instances of the <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal"><span class="pre">Logger</span></code></a>
 
434
class (hereafter called <em class="dfn">loggers</em>). Each instance has a name, and they are
 
435
conceptually arranged in a namespace hierarchy using dots (periods) as
 
436
separators. For example, a logger named &#8216;scan&#8217; is the parent of loggers
 
437
&#8216;scan.text&#8217;, &#8216;scan.html&#8217; and &#8216;scan.pdf&#8217;. Logger names can be anything you want,
 
438
and indicate the area of an application in which a logged message originates.</p>
 
439
<p>A good convention to use when naming loggers is to use a module-level logger,
 
440
in each module which uses logging, named as follows:</p>
 
441
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="n">__name__</span><span class="p">)</span>
 
442
</pre></div>
 
443
</div>
 
444
<p>This means that logger names track the package/module hierarchy, and it&#8217;s
 
445
intuitively obvious where events are logged just from the logger name.</p>
 
446
<p>The root of the hierarchy of loggers is called the root logger. That&#8217;s the
 
447
logger used by the functions <a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal"><span class="pre">debug()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><code class="xref py py-func docutils literal"><span class="pre">info()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><code class="xref py py-func docutils literal"><span class="pre">warning()</span></code></a>,
 
448
<a class="reference internal" href="../library/logging.html#logging.error" title="logging.error"><code class="xref py py-func docutils literal"><span class="pre">error()</span></code></a> and <a class="reference internal" href="../library/logging.html#logging.critical" title="logging.critical"><code class="xref py py-func docutils literal"><span class="pre">critical()</span></code></a>, which just call the same-named method of
 
449
the root logger. The functions and the methods have the same signatures. The
 
450
root logger&#8217;s name is printed as &#8216;root&#8217; in the logged output.</p>
 
451
<p>It is, of course, possible to log messages to different destinations. Support
 
452
is included in the package for writing log messages to files, HTTP GET/POST
 
453
locations, email via SMTP, generic sockets, queues, or OS-specific logging
 
454
mechanisms such as syslog or the Windows NT event log. Destinations are served
 
455
by <em class="dfn">handler</em> classes. You can create your own log destination class if
 
456
you have special requirements not met by any of the built-in handler classes.</p>
 
457
<p>By default, no destination is set for any logging messages. You can specify
 
458
a destination (such as console or file) by using <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></code></a> as in the
 
459
tutorial examples. If you call the functions  <a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal"><span class="pre">debug()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><code class="xref py py-func docutils literal"><span class="pre">info()</span></code></a>,
 
460
<a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><code class="xref py py-func docutils literal"><span class="pre">warning()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.error" title="logging.error"><code class="xref py py-func docutils literal"><span class="pre">error()</span></code></a> and <a class="reference internal" href="../library/logging.html#logging.critical" title="logging.critical"><code class="xref py py-func docutils literal"><span class="pre">critical()</span></code></a>, they will check to see
 
461
if no destination is set; and if one is not set, they will set a destination
 
462
of the console (<code class="docutils literal"><span class="pre">sys.stderr</span></code>) and a default format for the displayed
 
463
message before delegating to the root logger to do the actual message output.</p>
 
464
<p>The default format set by <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></code></a> for messages is:</p>
 
465
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="n">severity</span><span class="p">:</span><span class="n">logger</span> <span class="n">name</span><span class="p">:</span><span class="n">message</span>
 
466
</pre></div>
 
467
</div>
 
468
<p>You can change this by passing a format string to <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></code></a> with the
 
469
<em>format</em> keyword argument. For all options regarding how a format string is
 
470
constructed, see <a class="reference internal" href="../library/logging.html#formatter-objects"><span>Formatter Objects</span></a>.</p>
 
471
<div class="section" id="logging-flow">
 
472
<h3>Logging Flow<a class="headerlink" href="#logging-flow" title="Permalink to this headline">¶</a></h3>
 
473
<p>The flow of log event information in loggers and handlers is illustrated in the
 
474
following diagram.</p>
 
475
<img alt="../_images/logging_flow.png" src="../_images/logging_flow.png" />
 
476
</div>
 
477
<div class="section" id="loggers">
 
478
<h3>Loggers<a class="headerlink" href="#loggers" title="Permalink to this headline">¶</a></h3>
 
479
<p><a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal"><span class="pre">Logger</span></code></a> objects have a threefold job.  First, they expose several
 
480
methods to application code so that applications can log messages at runtime.
 
481
Second, logger objects determine which log messages to act upon based upon
 
482
severity (the default filtering facility) or filter objects.  Third, logger
 
483
objects pass along relevant log messages to all interested log handlers.</p>
 
484
<p>The most widely used methods on logger objects fall into two categories:
 
485
configuration and message sending.</p>
 
486
<p>These are the most common configuration methods:</p>
 
487
<ul class="simple">
 
488
<li><a class="reference internal" href="../library/logging.html#logging.Logger.setLevel" title="logging.Logger.setLevel"><code class="xref py py-meth docutils literal"><span class="pre">Logger.setLevel()</span></code></a> specifies the lowest-severity log message a logger
 
489
will handle, where debug is the lowest built-in severity level and critical
 
490
is the highest built-in severity.  For example, if the severity level is
 
491
INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL messages
 
492
and will ignore DEBUG messages.</li>
 
493
<li><a class="reference internal" href="../library/logging.html#logging.Logger.addHandler" title="logging.Logger.addHandler"><code class="xref py py-meth docutils literal"><span class="pre">Logger.addHandler()</span></code></a> and <a class="reference internal" href="../library/logging.html#logging.Logger.removeHandler" title="logging.Logger.removeHandler"><code class="xref py py-meth docutils literal"><span class="pre">Logger.removeHandler()</span></code></a> add and remove
 
494
handler objects from the logger object.  Handlers are covered in more detail
 
495
in <a class="reference internal" href="#handler-basic"><span>Handlers</span></a>.</li>
 
496
<li><a class="reference internal" href="../library/logging.html#logging.Logger.addFilter" title="logging.Logger.addFilter"><code class="xref py py-meth docutils literal"><span class="pre">Logger.addFilter()</span></code></a> and <a class="reference internal" href="../library/logging.html#logging.Logger.removeFilter" title="logging.Logger.removeFilter"><code class="xref py py-meth docutils literal"><span class="pre">Logger.removeFilter()</span></code></a> add and remove filter
 
497
objects from the logger object.  Filters are covered in more detail in
 
498
<a class="reference internal" href="../library/logging.html#filter"><span>Filter Objects</span></a>.</li>
 
499
</ul>
 
500
<p>You don&#8217;t need to always call these methods on every logger you create. See the
 
501
last two paragraphs in this section.</p>
 
502
<p>With the logger object configured, the following methods create log messages:</p>
 
503
<ul class="simple">
 
504
<li><a class="reference internal" href="../library/logging.html#logging.Logger.debug" title="logging.Logger.debug"><code class="xref py py-meth docutils literal"><span class="pre">Logger.debug()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.Logger.info" title="logging.Logger.info"><code class="xref py py-meth docutils literal"><span class="pre">Logger.info()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.Logger.warning" title="logging.Logger.warning"><code class="xref py py-meth docutils literal"><span class="pre">Logger.warning()</span></code></a>,
 
505
<a class="reference internal" href="../library/logging.html#logging.Logger.error" title="logging.Logger.error"><code class="xref py py-meth docutils literal"><span class="pre">Logger.error()</span></code></a>, and <a class="reference internal" href="../library/logging.html#logging.Logger.critical" title="logging.Logger.critical"><code class="xref py py-meth docutils literal"><span class="pre">Logger.critical()</span></code></a> all create log records with
 
506
a message and a level that corresponds to their respective method names. The
 
507
message is actually a format string, which may contain the standard string
 
508
substitution syntax of <code class="docutils literal"><span class="pre">%s</span></code>, <code class="docutils literal"><span class="pre">%d</span></code>, <code class="docutils literal"><span class="pre">%f</span></code>, and so on.  The
 
509
rest of their arguments is a list of objects that correspond with the
 
510
substitution fields in the message.  With regard to <code class="docutils literal"><span class="pre">**kwargs</span></code>, the
 
511
logging methods care only about a keyword of <code class="docutils literal"><span class="pre">exc_info</span></code> and use it to
 
512
determine whether to log exception information.</li>
 
513
<li><a class="reference internal" href="../library/logging.html#logging.Logger.exception" title="logging.Logger.exception"><code class="xref py py-meth docutils literal"><span class="pre">Logger.exception()</span></code></a> creates a log message similar to
 
514
<a class="reference internal" href="../library/logging.html#logging.Logger.error" title="logging.Logger.error"><code class="xref py py-meth docutils literal"><span class="pre">Logger.error()</span></code></a>.  The difference is that <a class="reference internal" href="../library/logging.html#logging.Logger.exception" title="logging.Logger.exception"><code class="xref py py-meth docutils literal"><span class="pre">Logger.exception()</span></code></a> dumps a
 
515
stack trace along with it.  Call this method only from an exception handler.</li>
 
516
<li><a class="reference internal" href="../library/logging.html#logging.Logger.log" title="logging.Logger.log"><code class="xref py py-meth docutils literal"><span class="pre">Logger.log()</span></code></a> takes a log level as an explicit argument.  This is a
 
517
little more verbose for logging messages than using the log level convenience
 
518
methods listed above, but this is how to log at custom log levels.</li>
 
519
</ul>
 
520
<p><a class="reference internal" href="../library/logging.html#logging.getLogger" title="logging.getLogger"><code class="xref py py-func docutils literal"><span class="pre">getLogger()</span></code></a> returns a reference to a logger instance with the specified
 
521
name if it is provided, or <code class="docutils literal"><span class="pre">root</span></code> if not.  The names are period-separated
 
522
hierarchical structures.  Multiple calls to <a class="reference internal" href="../library/logging.html#logging.getLogger" title="logging.getLogger"><code class="xref py py-func docutils literal"><span class="pre">getLogger()</span></code></a> with the same name
 
523
will return a reference to the same logger object.  Loggers that are further
 
524
down in the hierarchical list are children of loggers higher up in the list.
 
525
For example, given a logger with a name of <code class="docutils literal"><span class="pre">foo</span></code>, loggers with names of
 
526
<code class="docutils literal"><span class="pre">foo.bar</span></code>, <code class="docutils literal"><span class="pre">foo.bar.baz</span></code>, and <code class="docutils literal"><span class="pre">foo.bam</span></code> are all descendants of <code class="docutils literal"><span class="pre">foo</span></code>.</p>
 
527
<p>Loggers have a concept of <em>effective level</em>. If a level is not explicitly set
 
528
on a logger, the level of its parent is used instead as its effective level.
 
529
If the parent has no explicit level set, <em>its</em> parent is examined, and so on -
 
530
all ancestors are searched until an explicitly set level is found. The root
 
531
logger always has an explicit level set (<code class="docutils literal"><span class="pre">WARNING</span></code> by default). When deciding
 
532
whether to process an event, the effective level of the logger is used to
 
533
determine whether the event is passed to the logger&#8217;s handlers.</p>
 
534
<p>Child loggers propagate messages up to the handlers associated with their
 
535
ancestor loggers. Because of this, it is unnecessary to define and configure
 
536
handlers for all the loggers an application uses. It is sufficient to
 
537
configure handlers for a top-level logger and create child loggers as needed.
 
538
(You can, however, turn off propagation by setting the <em>propagate</em>
 
539
attribute of a logger to <code class="docutils literal"><span class="pre">False</span></code>.)</p>
 
540
</div>
 
541
<div class="section" id="handlers">
 
542
<span id="handler-basic"></span><h3>Handlers<a class="headerlink" href="#handlers" title="Permalink to this headline">¶</a></h3>
 
543
<p><code class="xref py py-class docutils literal"><span class="pre">Handler</span></code> objects are responsible for dispatching the
 
544
appropriate log messages (based on the log messages&#8217; severity) to the handler&#8217;s
 
545
specified destination.  <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal"><span class="pre">Logger</span></code></a> objects can add zero or more handler
 
546
objects to themselves with an <a class="reference internal" href="../library/logging.html#logging.Logger.addHandler" title="logging.Logger.addHandler"><code class="xref py py-meth docutils literal"><span class="pre">addHandler()</span></code></a> method.  As an example
 
547
scenario, an application may want to send all log messages to a log file, all
 
548
log messages of error or higher to stdout, and all messages of critical to an
 
549
email address. This scenario requires three individual handlers where each
 
550
handler is responsible for sending messages of a specific severity to a specific
 
551
location.</p>
 
552
<p>The standard library includes quite a few handler types (see
 
553
<a class="reference internal" href="#useful-handlers"><span>Useful Handlers</span></a>); the tutorials use mainly <a class="reference internal" href="../library/logging.handlers.html#logging.StreamHandler" title="logging.StreamHandler"><code class="xref py py-class docutils literal"><span class="pre">StreamHandler</span></code></a> and
 
554
<a class="reference internal" href="../library/logging.handlers.html#logging.FileHandler" title="logging.FileHandler"><code class="xref py py-class docutils literal"><span class="pre">FileHandler</span></code></a> in its examples.</p>
 
555
<p>There are very few methods in a handler for application developers to concern
 
556
themselves with.  The only handler methods that seem relevant for application
 
557
developers who are using the built-in handler objects (that is, not creating
 
558
custom handlers) are the following configuration methods:</p>
 
559
<ul class="simple">
 
560
<li>The <a class="reference internal" href="../library/logging.html#logging.Handler.setLevel" title="logging.Handler.setLevel"><code class="xref py py-meth docutils literal"><span class="pre">setLevel()</span></code></a> method, just as in logger objects, specifies the
 
561
lowest severity that will be dispatched to the appropriate destination.  Why
 
562
are there two <code class="xref py py-func docutils literal"><span class="pre">setLevel()</span></code> methods?  The level set in the logger
 
563
determines which severity of messages it will pass to its handlers.  The level
 
564
set in each handler determines which messages that handler will send on.</li>
 
565
<li><a class="reference internal" href="../library/logging.html#logging.Handler.setFormatter" title="logging.Handler.setFormatter"><code class="xref py py-meth docutils literal"><span class="pre">setFormatter()</span></code></a> selects a Formatter object for this handler to
 
566
use.</li>
 
567
<li><a class="reference internal" href="../library/logging.html#logging.Handler.addFilter" title="logging.Handler.addFilter"><code class="xref py py-meth docutils literal"><span class="pre">addFilter()</span></code></a> and <a class="reference internal" href="../library/logging.html#logging.Handler.removeFilter" title="logging.Handler.removeFilter"><code class="xref py py-meth docutils literal"><span class="pre">removeFilter()</span></code></a> respectively
 
568
configure and deconfigure filter objects on handlers.</li>
 
569
</ul>
 
570
<p>Application code should not directly instantiate and use instances of
 
571
<code class="xref py py-class docutils literal"><span class="pre">Handler</span></code>.  Instead, the <code class="xref py py-class docutils literal"><span class="pre">Handler</span></code> class is a base class that
 
572
defines the interface that all handlers should have and establishes some
 
573
default behavior that child classes can use (or override).</p>
 
574
</div>
 
575
<div class="section" id="formatters">
 
576
<h3>Formatters<a class="headerlink" href="#formatters" title="Permalink to this headline">¶</a></h3>
 
577
<p>Formatter objects configure the final order, structure, and contents of the log
 
578
message.  Unlike the base <code class="xref py py-class docutils literal"><span class="pre">logging.Handler</span></code> class, application code may
 
579
instantiate formatter classes, although you could likely subclass the formatter
 
580
if your application needs special behavior.  The constructor takes three
 
581
optional arguments &#8211; a message format string, a date format string and a style
 
582
indicator.</p>
 
583
<dl class="method">
 
584
<dt id="logging.logging.Formatter.__init__">
 
585
<code class="descclassname">logging.Formatter.</code><code class="descname">__init__</code><span class="sig-paren">(</span><em>fmt=None</em>, <em>datefmt=None</em>, <em>style='%'</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.logging.Formatter.__init__" title="Permalink to this definition">¶</a></dt>
 
586
<dd></dd></dl>
 
587
 
 
588
<p>If there is no message format string, the default is to use the
 
589
raw message.  If there is no date format string, the default date format is:</p>
 
590
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="o">%</span><span class="n">Y</span><span class="o">-%</span><span class="n">m</span><span class="o">-%</span><span class="n">d</span> <span class="o">%</span><span class="n">H</span><span class="p">:</span><span class="o">%</span><span class="n">M</span><span class="p">:</span><span class="o">%</span><span class="n">S</span>
 
591
</pre></div>
 
592
</div>
 
593
<p>with the milliseconds tacked on at the end. The <code class="docutils literal"><span class="pre">style</span></code> is one of <cite>%</cite>, &#8216;{&#8216;
 
594
or &#8216;$&#8217;. If one of these is not specified, then &#8216;%&#8217; will be used.</p>
 
595
<p>If the <code class="docutils literal"><span class="pre">style</span></code> is &#8216;%&#8217;, the message format string uses
 
596
<code class="docutils literal"><span class="pre">%(&lt;dictionary</span> <span class="pre">key&gt;)s</span></code> styled string substitution; the possible keys are
 
597
documented in <a class="reference internal" href="../library/logging.html#logrecord-attributes"><span>LogRecord attributes</span></a>. If the style is &#8216;{&#8216;, the message
 
598
format string is assumed to be compatible with <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal"><span class="pre">str.format()</span></code></a> (using
 
599
keyword arguments), while if the style is &#8216;$&#8217; then the message format string
 
600
should conform to what is expected by <a class="reference internal" href="../library/string.html#string.Template.substitute" title="string.Template.substitute"><code class="xref py py-meth docutils literal"><span class="pre">string.Template.substitute()</span></code></a>.</p>
 
601
<div class="versionchanged">
 
602
<p><span class="versionmodified">Changed in version 3.2: </span>Added the <code class="docutils literal"><span class="pre">style</span></code> parameter.</p>
 
603
</div>
 
604
<p>The following message format string will log the time in a human-readable
 
605
format, the severity of the message, and the contents of the message, in that
 
606
order:</p>
 
607
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> - </span><span class="si">%(levelname)s</span><span class="s1"> - </span><span class="si">%(message)s</span><span class="s1">&#39;</span>
 
608
</pre></div>
 
609
</div>
 
610
<p>Formatters use a user-configurable function to convert the creation time of a
 
611
record to a tuple. By default, <a class="reference internal" href="../library/time.html#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal"><span class="pre">time.localtime()</span></code></a> is used; to change this
 
612
for a particular formatter instance, set the <code class="docutils literal"><span class="pre">converter</span></code> attribute of the
 
613
instance to a function with the same signature as <a class="reference internal" href="../library/time.html#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal"><span class="pre">time.localtime()</span></code></a> or
 
614
<a class="reference internal" href="../library/time.html#time.gmtime" title="time.gmtime"><code class="xref py py-func docutils literal"><span class="pre">time.gmtime()</span></code></a>. To change it for all formatters, for example if you want
 
615
all logging times to be shown in GMT, set the <code class="docutils literal"><span class="pre">converter</span></code> attribute in the
 
616
Formatter class (to <code class="docutils literal"><span class="pre">time.gmtime</span></code> for GMT display).</p>
 
617
</div>
 
618
<div class="section" id="configuring-logging">
 
619
<h3>Configuring Logging<a class="headerlink" href="#configuring-logging" title="Permalink to this headline">¶</a></h3>
 
620
<p>Programmers can configure logging in three ways:</p>
 
621
<ol class="arabic simple">
 
622
<li>Creating loggers, handlers, and formatters explicitly using Python
 
623
code that calls the configuration methods listed above.</li>
 
624
<li>Creating a logging config file and reading it using the <a class="reference internal" href="../library/logging.config.html#logging.config.fileConfig" title="logging.config.fileConfig"><code class="xref py py-func docutils literal"><span class="pre">fileConfig()</span></code></a>
 
625
function.</li>
 
626
<li>Creating a dictionary of configuration information and passing it
 
627
to the <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal"><span class="pre">dictConfig()</span></code></a> function.</li>
 
628
</ol>
 
629
<p>For the reference documentation on the last two options, see
 
630
<a class="reference internal" href="../library/logging.config.html#logging-config-api"><span>Configuration functions</span></a>.  The following example configures a very simple
 
631
logger, a console handler, and a simple formatter using Python code:</p>
 
632
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
 
633
 
 
634
<span class="c1"># create logger</span>
 
635
<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;simple_example&#39;</span><span class="p">)</span>
 
636
<span class="n">logger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
 
637
 
 
638
<span class="c1"># create console handler and set level to debug</span>
 
639
<span class="n">ch</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">StreamHandler</span><span class="p">()</span>
 
640
<span class="n">ch</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
 
641
 
 
642
<span class="c1"># create formatter</span>
 
643
<span class="n">formatter</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">Formatter</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> - </span><span class="si">%(name)s</span><span class="s1"> - </span><span class="si">%(levelname)s</span><span class="s1"> - </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">)</span>
 
644
 
 
645
<span class="c1"># add formatter to ch</span>
 
646
<span class="n">ch</span><span class="o">.</span><span class="n">setFormatter</span><span class="p">(</span><span class="n">formatter</span><span class="p">)</span>
 
647
 
 
648
<span class="c1"># add ch to logger</span>
 
649
<span class="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">ch</span><span class="p">)</span>
 
650
 
 
651
<span class="c1"># &#39;application&#39; code</span>
 
652
<span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;debug message&#39;</span><span class="p">)</span>
 
653
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;info message&#39;</span><span class="p">)</span>
 
654
<span class="n">logger</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s1">&#39;warn message&#39;</span><span class="p">)</span>
 
655
<span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">&#39;error message&#39;</span><span class="p">)</span>
 
656
<span class="n">logger</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s1">&#39;critical message&#39;</span><span class="p">)</span>
 
657
</pre></div>
 
658
</div>
 
659
<p>Running this module from the command line produces the following output:</p>
 
660
<div class="highlight-shell-session"><div class="highlight"><pre><span></span><span class="gp">$</span> python simple_logging_module.py
 
661
<span class="go">2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message</span>
 
662
<span class="go">2005-03-19 15:10:26,620 - simple_example - INFO - info message</span>
 
663
<span class="go">2005-03-19 15:10:26,695 - simple_example - WARNING - warn message</span>
 
664
<span class="go">2005-03-19 15:10:26,697 - simple_example - ERROR - error message</span>
 
665
<span class="go">2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message</span>
 
666
</pre></div>
 
667
</div>
 
668
<p>The following Python module creates a logger, handler, and formatter nearly
 
669
identical to those in the example listed above, with the only difference being
 
670
the names of the objects:</p>
 
671
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
 
672
<span class="kn">import</span> <span class="nn">logging.config</span>
 
673
 
 
674
<span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">fileConfig</span><span class="p">(</span><span class="s1">&#39;logging.conf&#39;</span><span class="p">)</span>
 
675
 
 
676
<span class="c1"># create logger</span>
 
677
<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;simpleExample&#39;</span><span class="p">)</span>
 
678
 
 
679
<span class="c1"># &#39;application&#39; code</span>
 
680
<span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;debug message&#39;</span><span class="p">)</span>
 
681
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;info message&#39;</span><span class="p">)</span>
 
682
<span class="n">logger</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s1">&#39;warn message&#39;</span><span class="p">)</span>
 
683
<span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">&#39;error message&#39;</span><span class="p">)</span>
 
684
<span class="n">logger</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s1">&#39;critical message&#39;</span><span class="p">)</span>
 
685
</pre></div>
 
686
</div>
 
687
<p>Here is the logging.conf file:</p>
 
688
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="p">[</span><span class="n">loggers</span><span class="p">]</span>
 
689
<span class="n">keys</span><span class="o">=</span><span class="n">root</span><span class="p">,</span><span class="n">simpleExample</span>
 
690
 
 
691
<span class="p">[</span><span class="n">handlers</span><span class="p">]</span>
 
692
<span class="n">keys</span><span class="o">=</span><span class="n">consoleHandler</span>
 
693
 
 
694
<span class="p">[</span><span class="n">formatters</span><span class="p">]</span>
 
695
<span class="n">keys</span><span class="o">=</span><span class="n">simpleFormatter</span>
 
696
 
 
697
<span class="p">[</span><span class="n">logger_root</span><span class="p">]</span>
 
698
<span class="n">level</span><span class="o">=</span><span class="n">DEBUG</span>
 
699
<span class="n">handlers</span><span class="o">=</span><span class="n">consoleHandler</span>
 
700
 
 
701
<span class="p">[</span><span class="n">logger_simpleExample</span><span class="p">]</span>
 
702
<span class="n">level</span><span class="o">=</span><span class="n">DEBUG</span>
 
703
<span class="n">handlers</span><span class="o">=</span><span class="n">consoleHandler</span>
 
704
<span class="n">qualname</span><span class="o">=</span><span class="n">simpleExample</span>
 
705
<span class="n">propagate</span><span class="o">=</span><span class="mi">0</span>
 
706
 
 
707
<span class="p">[</span><span class="n">handler_consoleHandler</span><span class="p">]</span>
 
708
<span class="n">class</span><span class="o">=</span><span class="n">StreamHandler</span>
 
709
<span class="n">level</span><span class="o">=</span><span class="n">DEBUG</span>
 
710
<span class="n">formatter</span><span class="o">=</span><span class="n">simpleFormatter</span>
 
711
<span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">,)</span>
 
712
 
 
713
<span class="p">[</span><span class="n">formatter_simpleFormatter</span><span class="p">]</span>
 
714
<span class="nb">format</span><span class="o">=%</span><span class="p">(</span><span class="n">asctime</span><span class="p">)</span><span class="n">s</span> <span class="o">-</span> <span class="o">%</span><span class="p">(</span><span class="n">name</span><span class="p">)</span><span class="n">s</span> <span class="o">-</span> <span class="o">%</span><span class="p">(</span><span class="n">levelname</span><span class="p">)</span><span class="n">s</span> <span class="o">-</span> <span class="o">%</span><span class="p">(</span><span class="n">message</span><span class="p">)</span><span class="n">s</span>
 
715
<span class="n">datefmt</span><span class="o">=</span>
 
716
</pre></div>
 
717
</div>
 
718
<p>The output is nearly identical to that of the non-config-file-based example:</p>
 
719
<div class="highlight-shell-session"><div class="highlight"><pre><span></span><span class="gp">$</span> python simple_logging_config.py
 
720
<span class="go">2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message</span>
 
721
<span class="go">2005-03-19 15:38:55,979 - simpleExample - INFO - info message</span>
 
722
<span class="go">2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message</span>
 
723
<span class="go">2005-03-19 15:38:56,055 - simpleExample - ERROR - error message</span>
 
724
<span class="go">2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message</span>
 
725
</pre></div>
 
726
</div>
 
727
<p>You can see that the config file approach has a few advantages over the Python
 
728
code approach, mainly separation of configuration and code and the ability of
 
729
noncoders to easily modify the logging properties.</p>
 
730
<div class="admonition warning">
 
731
<p class="first admonition-title">Warning</p>
 
732
<p>The <a class="reference internal" href="../library/logging.config.html#logging.config.fileConfig" title="logging.config.fileConfig"><code class="xref py py-func docutils literal"><span class="pre">fileConfig()</span></code></a> function takes a default parameter,
 
733
<code class="docutils literal"><span class="pre">disable_existing_loggers</span></code>, which defaults to <code class="docutils literal"><span class="pre">True</span></code> for reasons of
 
734
backward compatibility. This may or may not be what you want, since it
 
735
will cause any loggers existing before the <a class="reference internal" href="../library/logging.config.html#logging.config.fileConfig" title="logging.config.fileConfig"><code class="xref py py-func docutils literal"><span class="pre">fileConfig()</span></code></a> call to
 
736
be disabled unless they (or an ancestor) are explicitly named in the
 
737
configuration.  Please refer to the reference documentation for more
 
738
information, and specify <code class="docutils literal"><span class="pre">False</span></code> for this parameter if you wish.</p>
 
739
<p class="last">The dictionary passed to <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal"><span class="pre">dictConfig()</span></code></a> can also specify a Boolean
 
740
value with key <code class="docutils literal"><span class="pre">disable_existing_loggers</span></code>, which if not specified
 
741
explicitly in the dictionary also defaults to being interpreted as
 
742
<code class="docutils literal"><span class="pre">True</span></code>.  This leads to the logger-disabling behaviour described above,
 
743
which may not be what you want - in which case, provide the key
 
744
explicitly with a value of <code class="docutils literal"><span class="pre">False</span></code>.</p>
 
745
</div>
 
746
<p>Note that the class names referenced in config files need to be either relative
 
747
to the logging module, or absolute values which can be resolved using normal
 
748
import mechanisms. Thus, you could use either
 
749
<a class="reference internal" href="../library/logging.handlers.html#logging.handlers.WatchedFileHandler" title="logging.handlers.WatchedFileHandler"><code class="xref py py-class docutils literal"><span class="pre">WatchedFileHandler</span></code></a> (relative to the logging module) or
 
750
<code class="docutils literal"><span class="pre">mypackage.mymodule.MyHandler</span></code> (for a class defined in package <code class="docutils literal"><span class="pre">mypackage</span></code>
 
751
and module <code class="docutils literal"><span class="pre">mymodule</span></code>, where <code class="docutils literal"><span class="pre">mypackage</span></code> is available on the Python import
 
752
path).</p>
 
753
<p>In Python 3.2, a new means of configuring logging has been introduced, using
 
754
dictionaries to hold configuration information. This provides a superset of the
 
755
functionality of the config-file-based approach outlined above, and is the
 
756
recommended configuration method for new applications and deployments. Because
 
757
a Python dictionary is used to hold configuration information, and since you
 
758
can populate that dictionary using different means, you have more options for
 
759
configuration. For example, you can use a configuration file in JSON format,
 
760
or, if you have access to YAML processing functionality, a file in YAML
 
761
format, to populate the configuration dictionary. Or, of course, you can
 
762
construct the dictionary in Python code, receive it in pickled form over a
 
763
socket, or use whatever approach makes sense for your application.</p>
 
764
<p>Here&#8217;s an example of the same configuration as above, in YAML format for
 
765
the new dictionary-based approach:</p>
 
766
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="n">version</span><span class="p">:</span> <span class="mi">1</span>
 
767
<span class="n">formatters</span><span class="p">:</span>
 
768
  <span class="n">simple</span><span class="p">:</span>
 
769
    <span class="nb">format</span><span class="p">:</span> <span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> - </span><span class="si">%(name)s</span><span class="s1"> - </span><span class="si">%(levelname)s</span><span class="s1"> - </span><span class="si">%(message)s</span><span class="s1">&#39;</span>
 
770
<span class="n">handlers</span><span class="p">:</span>
 
771
  <span class="n">console</span><span class="p">:</span>
 
772
    <span class="n">class</span><span class="p">:</span> <span class="n">logging</span><span class="o">.</span><span class="n">StreamHandler</span>
 
773
    <span class="n">level</span><span class="p">:</span> <span class="n">DEBUG</span>
 
774
    <span class="n">formatter</span><span class="p">:</span> <span class="n">simple</span>
 
775
    <span class="n">stream</span><span class="p">:</span> <span class="n">ext</span><span class="p">:</span><span class="o">//</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span>
 
776
<span class="n">loggers</span><span class="p">:</span>
 
777
  <span class="n">simpleExample</span><span class="p">:</span>
 
778
    <span class="n">level</span><span class="p">:</span> <span class="n">DEBUG</span>
 
779
    <span class="n">handlers</span><span class="p">:</span> <span class="p">[</span><span class="n">console</span><span class="p">]</span>
 
780
    <span class="n">propagate</span><span class="p">:</span> <span class="n">no</span>
 
781
<span class="n">root</span><span class="p">:</span>
 
782
  <span class="n">level</span><span class="p">:</span> <span class="n">DEBUG</span>
 
783
  <span class="n">handlers</span><span class="p">:</span> <span class="p">[</span><span class="n">console</span><span class="p">]</span>
 
784
</pre></div>
 
785
</div>
 
786
<p>For more information about logging using a dictionary, see
 
787
<a class="reference internal" href="../library/logging.config.html#logging-config-api"><span>Configuration functions</span></a>.</p>
 
788
</div>
 
789
<div class="section" id="what-happens-if-no-configuration-is-provided">
 
790
<h3>What happens if no configuration is provided<a class="headerlink" href="#what-happens-if-no-configuration-is-provided" title="Permalink to this headline">¶</a></h3>
 
791
<p>If no logging configuration is provided, it is possible to have a situation
 
792
where a logging event needs to be output, but no handlers can be found to
 
793
output the event. The behaviour of the logging package in these
 
794
circumstances is dependent on the Python version.</p>
 
795
<p>For versions of Python prior to 3.2, the behaviour is as follows:</p>
 
796
<ul class="simple">
 
797
<li>If <em>logging.raiseExceptions</em> is <code class="docutils literal"><span class="pre">False</span></code> (production mode), the event is
 
798
silently dropped.</li>
 
799
<li>If <em>logging.raiseExceptions</em> is <code class="docutils literal"><span class="pre">True</span></code> (development mode), a message
 
800
&#8216;No handlers could be found for logger X.Y.Z&#8217; is printed once.</li>
 
801
</ul>
 
802
<p>In Python 3.2 and later, the behaviour is as follows:</p>
 
803
<ul class="simple">
 
804
<li>The event is output using a &#8216;handler of last resort&#8217;, stored in
 
805
<code class="docutils literal"><span class="pre">logging.lastResort</span></code>. This internal handler is not associated with any
 
806
logger, and acts like a <a class="reference internal" href="../library/logging.handlers.html#logging.StreamHandler" title="logging.StreamHandler"><code class="xref py py-class docutils literal"><span class="pre">StreamHandler</span></code></a> which writes the
 
807
event description message to the current value of <code class="docutils literal"><span class="pre">sys.stderr</span></code> (therefore
 
808
respecting any redirections which may be in effect). No formatting is
 
809
done on the message - just the bare event description message is printed.
 
810
The handler&#8217;s level is set to <code class="docutils literal"><span class="pre">WARNING</span></code>, so all events at this and
 
811
greater severities will be output.</li>
 
812
</ul>
 
813
<p>To obtain the pre-3.2 behaviour, <code class="docutils literal"><span class="pre">logging.lastResort</span></code> can be set to <code class="docutils literal"><span class="pre">None</span></code>.</p>
 
814
</div>
 
815
<div class="section" id="configuring-logging-for-a-library">
 
816
<span id="library-config"></span><h3>Configuring Logging for a Library<a class="headerlink" href="#configuring-logging-for-a-library" title="Permalink to this headline">¶</a></h3>
 
817
<p>When developing a library which uses logging, you should take care to
 
818
document how the library uses logging - for example, the names of loggers
 
819
used. Some consideration also needs to be given to its logging configuration.
 
820
If the using application does not use logging, and library code makes logging
 
821
calls, then (as described in the previous section) events of severity
 
822
<code class="docutils literal"><span class="pre">WARNING</span></code> and greater will be printed to <code class="docutils literal"><span class="pre">sys.stderr</span></code>. This is regarded as
 
823
the best default behaviour.</p>
 
824
<p>If for some reason you <em>don&#8217;t</em> want these messages printed in the absence of
 
825
any logging configuration, you can attach a do-nothing handler to the top-level
 
826
logger for your library. This avoids the message being printed, since a handler
 
827
will be always be found for the library&#8217;s events: it just doesn&#8217;t produce any
 
828
output. If the library user configures logging for application use, presumably
 
829
that configuration will add some handlers, and if levels are suitably
 
830
configured then logging calls made in library code will send output to those
 
831
handlers, as normal.</p>
 
832
<p>A do-nothing handler is included in the logging package:
 
833
<a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><code class="xref py py-class docutils literal"><span class="pre">NullHandler</span></code></a> (since Python 3.1). An instance of this handler
 
834
could be added to the top-level logger of the logging namespace used by the
 
835
library (<em>if</em> you want to prevent your library&#8217;s logged events being output to
 
836
<code class="docutils literal"><span class="pre">sys.stderr</span></code> in the absence of logging configuration). If all logging by a
 
837
library <em>foo</em> is done using loggers with names matching &#8216;foo.x&#8217;, &#8216;foo.x.y&#8217;,
 
838
etc. then the code:</p>
 
839
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
 
840
<span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">NullHandler</span><span class="p">())</span>
 
841
</pre></div>
 
842
</div>
 
843
<p>should have the desired effect. If an organisation produces a number of
 
844
libraries, then the logger name specified can be &#8216;orgname.foo&#8217; rather than
 
845
just &#8216;foo&#8217;.</p>
 
846
<div class="admonition note">
 
847
<p class="first admonition-title">Note</p>
 
848
<p class="last">It is strongly advised that you <em>do not add any handlers other
 
849
than</em> <a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><code class="xref py py-class docutils literal"><span class="pre">NullHandler</span></code></a> <em>to your library&#8217;s loggers</em>. This is
 
850
because the configuration of handlers is the prerogative of the application
 
851
developer who uses your library. The application developer knows their
 
852
target audience and what handlers are most appropriate for their
 
853
application: if you add handlers &#8216;under the hood&#8217;, you might well interfere
 
854
with their ability to carry out unit tests and deliver logs which suit their
 
855
requirements.</p>
 
856
</div>
 
857
</div>
 
858
</div>
 
859
<div class="section" id="logging-levels">
 
860
<h2>Logging Levels<a class="headerlink" href="#logging-levels" title="Permalink to this headline">¶</a></h2>
 
861
<p>The numeric values of logging levels are given in the following table. These are
 
862
primarily of interest if you want to define your own levels, and need them to
 
863
have specific values relative to the predefined levels. If you define a level
 
864
with the same numeric value, it overwrites the predefined value; the predefined
 
865
name is lost.</p>
 
866
<table border="1" class="docutils">
 
867
<colgroup>
 
868
<col width="48%" />
 
869
<col width="52%" />
 
870
</colgroup>
 
871
<thead valign="bottom">
 
872
<tr class="row-odd"><th class="head">Level</th>
 
873
<th class="head">Numeric value</th>
 
874
</tr>
 
875
</thead>
 
876
<tbody valign="top">
 
877
<tr class="row-even"><td><code class="docutils literal"><span class="pre">CRITICAL</span></code></td>
 
878
<td>50</td>
 
879
</tr>
 
880
<tr class="row-odd"><td><code class="docutils literal"><span class="pre">ERROR</span></code></td>
 
881
<td>40</td>
 
882
</tr>
 
883
<tr class="row-even"><td><code class="docutils literal"><span class="pre">WARNING</span></code></td>
 
884
<td>30</td>
 
885
</tr>
 
886
<tr class="row-odd"><td><code class="docutils literal"><span class="pre">INFO</span></code></td>
 
887
<td>20</td>
 
888
</tr>
 
889
<tr class="row-even"><td><code class="docutils literal"><span class="pre">DEBUG</span></code></td>
 
890
<td>10</td>
 
891
</tr>
 
892
<tr class="row-odd"><td><code class="docutils literal"><span class="pre">NOTSET</span></code></td>
 
893
<td>0</td>
 
894
</tr>
 
895
</tbody>
 
896
</table>
 
897
<p>Levels can also be associated with loggers, being set either by the developer or
 
898
through loading a saved logging configuration. When a logging method is called
 
899
on a logger, the logger compares its own level with the level associated with
 
900
the method call. If the logger&#8217;s level is higher than the method call&#8217;s, no
 
901
logging message is actually generated. This is the basic mechanism controlling
 
902
the verbosity of logging output.</p>
 
903
<p>Logging messages are encoded as instances of the <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal"><span class="pre">LogRecord</span></code></a>
 
904
class. When a logger decides to actually log an event, a
 
905
<a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal"><span class="pre">LogRecord</span></code></a> instance is created from the logging message.</p>
 
906
<p>Logging messages are subjected to a dispatch mechanism through the use of
 
907
<em class="dfn">handlers</em>, which are instances of subclasses of the <code class="xref py py-class docutils literal"><span class="pre">Handler</span></code>
 
908
class. Handlers are responsible for ensuring that a logged message (in the form
 
909
of a <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal"><span class="pre">LogRecord</span></code></a>) ends up in a particular location (or set of locations)
 
910
which is useful for the target audience for that message (such as end users,
 
911
support desk staff, system administrators, developers). Handlers are passed
 
912
<a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal"><span class="pre">LogRecord</span></code></a> instances intended for particular destinations. Each logger
 
913
can have zero, one or more handlers associated with it (via the
 
914
<a class="reference internal" href="../library/logging.html#logging.Logger.addHandler" title="logging.Logger.addHandler"><code class="xref py py-meth docutils literal"><span class="pre">addHandler()</span></code></a> method of <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal"><span class="pre">Logger</span></code></a>). In addition to any
 
915
handlers directly associated with a logger, <em>all handlers associated with all
 
916
ancestors of the logger</em> are called to dispatch the message (unless the
 
917
<em>propagate</em> flag for a logger is set to a false value, at which point the
 
918
passing to ancestor handlers stops).</p>
 
919
<p>Just as for loggers, handlers can have levels associated with them. A handler&#8217;s
 
920
level acts as a filter in the same way as a logger&#8217;s level does. If a handler
 
921
decides to actually dispatch an event, the <a class="reference internal" href="../library/logging.html#logging.Handler.emit" title="logging.Handler.emit"><code class="xref py py-meth docutils literal"><span class="pre">emit()</span></code></a> method is used
 
922
to send the message to its destination. Most user-defined subclasses of
 
923
<code class="xref py py-class docutils literal"><span class="pre">Handler</span></code> will need to override this <a class="reference internal" href="../library/logging.html#logging.Handler.emit" title="logging.Handler.emit"><code class="xref py py-meth docutils literal"><span class="pre">emit()</span></code></a>.</p>
 
924
<div class="section" id="custom-levels">
 
925
<span id="id1"></span><h3>Custom Levels<a class="headerlink" href="#custom-levels" title="Permalink to this headline">¶</a></h3>
 
926
<p>Defining your own levels is possible, but should not be necessary, as the
 
927
existing levels have been chosen on the basis of practical experience.
 
928
However, if you are convinced that you need custom levels, great care should
 
929
be exercised when doing this, and it is possibly <em>a very bad idea to define
 
930
custom levels if you are developing a library</em>. That&#8217;s because if multiple
 
931
library authors all define their own custom levels, there is a chance that
 
932
the logging output from such multiple libraries used together will be
 
933
difficult for the using developer to control and/or interpret, because a
 
934
given numeric value might mean different things for different libraries.</p>
 
935
</div>
 
936
</div>
 
937
<div class="section" id="useful-handlers">
 
938
<span id="id2"></span><h2>Useful Handlers<a class="headerlink" href="#useful-handlers" title="Permalink to this headline">¶</a></h2>
 
939
<p>In addition to the base <code class="xref py py-class docutils literal"><span class="pre">Handler</span></code> class, many useful subclasses are
 
940
provided:</p>
 
941
<ol class="arabic simple">
 
942
<li><a class="reference internal" href="../library/logging.handlers.html#logging.StreamHandler" title="logging.StreamHandler"><code class="xref py py-class docutils literal"><span class="pre">StreamHandler</span></code></a> instances send messages to streams (file-like
 
943
objects).</li>
 
944
<li><a class="reference internal" href="../library/logging.handlers.html#logging.FileHandler" title="logging.FileHandler"><code class="xref py py-class docutils literal"><span class="pre">FileHandler</span></code></a> instances send messages to disk files.</li>
 
945
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.BaseRotatingHandler" title="logging.handlers.BaseRotatingHandler"><code class="xref py py-class docutils literal"><span class="pre">BaseRotatingHandler</span></code></a> is the base class for handlers that
 
946
rotate log files at a certain point. It is not meant to be  instantiated
 
947
directly. Instead, use <a class="reference internal" href="../library/logging.handlers.html#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><code class="xref py py-class docutils literal"><span class="pre">RotatingFileHandler</span></code></a> or
 
948
<a class="reference internal" href="../library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler" title="logging.handlers.TimedRotatingFileHandler"><code class="xref py py-class docutils literal"><span class="pre">TimedRotatingFileHandler</span></code></a>.</li>
 
949
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><code class="xref py py-class docutils literal"><span class="pre">RotatingFileHandler</span></code></a> instances send messages to disk
 
950
files, with support for maximum log file sizes and log file rotation.</li>
 
951
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler" title="logging.handlers.TimedRotatingFileHandler"><code class="xref py py-class docutils literal"><span class="pre">TimedRotatingFileHandler</span></code></a> instances send messages to
 
952
disk files, rotating the log file at certain timed intervals.</li>
 
953
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><code class="xref py py-class docutils literal"><span class="pre">SocketHandler</span></code></a> instances send messages to TCP/IP
 
954
sockets. Since 3.4, Unix domain sockets are also supported.</li>
 
955
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.DatagramHandler" title="logging.handlers.DatagramHandler"><code class="xref py py-class docutils literal"><span class="pre">DatagramHandler</span></code></a> instances send messages to UDP
 
956
sockets. Since 3.4, Unix domain sockets are also supported.</li>
 
957
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SMTPHandler" title="logging.handlers.SMTPHandler"><code class="xref py py-class docutils literal"><span class="pre">SMTPHandler</span></code></a> instances send messages to a designated
 
958
email address.</li>
 
959
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><code class="xref py py-class docutils literal"><span class="pre">SysLogHandler</span></code></a> instances send messages to a Unix
 
960
syslog daemon, possibly on a remote machine.</li>
 
961
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.NTEventLogHandler" title="logging.handlers.NTEventLogHandler"><code class="xref py py-class docutils literal"><span class="pre">NTEventLogHandler</span></code></a> instances send messages to a
 
962
Windows NT/2000/XP event log.</li>
 
963
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.MemoryHandler" title="logging.handlers.MemoryHandler"><code class="xref py py-class docutils literal"><span class="pre">MemoryHandler</span></code></a> instances send messages to a buffer
 
964
in memory, which is flushed whenever specific criteria are met.</li>
 
965
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.HTTPHandler" title="logging.handlers.HTTPHandler"><code class="xref py py-class docutils literal"><span class="pre">HTTPHandler</span></code></a> instances send messages to an HTTP
 
966
server using either <code class="docutils literal"><span class="pre">GET</span></code> or <code class="docutils literal"><span class="pre">POST</span></code> semantics.</li>
 
967
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.WatchedFileHandler" title="logging.handlers.WatchedFileHandler"><code class="xref py py-class docutils literal"><span class="pre">WatchedFileHandler</span></code></a> instances watch the file they are
 
968
logging to. If the file changes, it is closed and reopened using the file
 
969
name. This handler is only useful on Unix-like systems; Windows does not
 
970
support the underlying mechanism used.</li>
 
971
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.QueueHandler" title="logging.handlers.QueueHandler"><code class="xref py py-class docutils literal"><span class="pre">QueueHandler</span></code></a> instances send messages to a queue, such as
 
972
those implemented in the <a class="reference internal" href="../library/queue.html#module-queue" title="queue: A synchronized queue class."><code class="xref py py-mod docutils literal"><span class="pre">queue</span></code></a> or <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code class="xref py py-mod docutils literal"><span class="pre">multiprocessing</span></code></a> modules.</li>
 
973
<li><a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><code class="xref py py-class docutils literal"><span class="pre">NullHandler</span></code></a> instances do nothing with error messages. They are used
 
974
by library developers who want to use logging, but want to avoid the &#8216;No
 
975
handlers could be found for logger XXX&#8217; message which can be displayed if
 
976
the library user has not configured logging. See <a class="reference internal" href="#library-config"><span>Configuring Logging for a Library</span></a> for
 
977
more information.</li>
 
978
</ol>
 
979
<div class="versionadded">
 
980
<p><span class="versionmodified">New in version 3.1: </span>The <a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><code class="xref py py-class docutils literal"><span class="pre">NullHandler</span></code></a> class.</p>
 
981
</div>
 
982
<div class="versionadded">
 
983
<p><span class="versionmodified">New in version 3.2: </span>The <a class="reference internal" href="../library/logging.handlers.html#logging.handlers.QueueHandler" title="logging.handlers.QueueHandler"><code class="xref py py-class docutils literal"><span class="pre">QueueHandler</span></code></a> class.</p>
 
984
</div>
 
985
<p>The <a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><code class="xref py py-class docutils literal"><span class="pre">NullHandler</span></code></a>, <a class="reference internal" href="../library/logging.handlers.html#logging.StreamHandler" title="logging.StreamHandler"><code class="xref py py-class docutils literal"><span class="pre">StreamHandler</span></code></a> and <a class="reference internal" href="../library/logging.handlers.html#logging.FileHandler" title="logging.FileHandler"><code class="xref py py-class docutils literal"><span class="pre">FileHandler</span></code></a>
 
986
classes are defined in the core logging package. The other handlers are
 
987
defined in a sub- module, <a class="reference internal" href="../library/logging.handlers.html#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></code></a>. (There is also another
 
988
sub-module, <a class="reference internal" href="../library/logging.config.html#module-logging.config" title="logging.config: Configuration of the logging module."><code class="xref py py-mod docutils literal"><span class="pre">logging.config</span></code></a>, for configuration functionality.)</p>
 
989
<p>Logged messages are formatted for presentation through instances of the
 
990
<a class="reference internal" href="../library/logging.html#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal"><span class="pre">Formatter</span></code></a> class. They are initialized with a format string suitable for
 
991
use with the % operator and a dictionary.</p>
 
992
<p>For formatting multiple messages in a batch, instances of
 
993
<code class="xref py py-class docutils literal"><span class="pre">BufferingFormatter</span></code> can be used. In addition to the format
 
994
string (which is applied to each message in the batch), there is provision for
 
995
header and trailer format strings.</p>
 
996
<p>When filtering based on logger level and/or handler level is not enough,
 
997
instances of <a class="reference internal" href="../library/logging.html#logging.Filter" title="logging.Filter"><code class="xref py py-class docutils literal"><span class="pre">Filter</span></code></a> can be added to both <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal"><span class="pre">Logger</span></code></a> and
 
998
<code class="xref py py-class docutils literal"><span class="pre">Handler</span></code> instances (through their <a class="reference internal" href="../library/logging.html#logging.Handler.addFilter" title="logging.Handler.addFilter"><code class="xref py py-meth docutils literal"><span class="pre">addFilter()</span></code></a> method).
 
999
Before deciding to process a message further, both loggers and handlers consult
 
1000
all their filters for permission. If any filter returns a false value, the
 
1001
message is not processed further.</p>
 
1002
<p>The basic <a class="reference internal" href="../library/logging.html#logging.Filter" title="logging.Filter"><code class="xref py py-class docutils literal"><span class="pre">Filter</span></code></a> functionality allows filtering by specific logger
 
1003
name. If this feature is used, messages sent to the named logger and its
 
1004
children are allowed through the filter, and all others dropped.</p>
 
1005
</div>
 
1006
<div class="section" id="exceptions-raised-during-logging">
 
1007
<span id="logging-exceptions"></span><h2>Exceptions raised during logging<a class="headerlink" href="#exceptions-raised-during-logging" title="Permalink to this headline">¶</a></h2>
 
1008
<p>The logging package is designed to swallow exceptions which occur while logging
 
1009
in production. This is so that errors which occur while handling logging events
 
1010
- such as logging misconfiguration, network or other similar errors - do not
 
1011
cause the application using logging to terminate prematurely.</p>
 
1012
<p><a class="reference internal" href="../library/exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-class docutils literal"><span class="pre">SystemExit</span></code></a> and <a class="reference internal" href="../library/exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-class docutils literal"><span class="pre">KeyboardInterrupt</span></code></a> exceptions are never
 
1013
swallowed. Other exceptions which occur during the <a class="reference internal" href="../library/logging.html#logging.Handler.emit" title="logging.Handler.emit"><code class="xref py py-meth docutils literal"><span class="pre">emit()</span></code></a> method
 
1014
of a <code class="xref py py-class docutils literal"><span class="pre">Handler</span></code> subclass are passed to its <a class="reference internal" href="../library/logging.html#logging.Handler.handleError" title="logging.Handler.handleError"><code class="xref py py-meth docutils literal"><span class="pre">handleError()</span></code></a>
 
1015
method.</p>
 
1016
<p>The default implementation of <a class="reference internal" href="../library/logging.html#logging.Handler.handleError" title="logging.Handler.handleError"><code class="xref py py-meth docutils literal"><span class="pre">handleError()</span></code></a> in <code class="xref py py-class docutils literal"><span class="pre">Handler</span></code>
 
1017
checks to see if a module-level variable, <code class="xref py py-data docutils literal"><span class="pre">raiseExceptions</span></code>, is set. If
 
1018
set, a traceback is printed to <a class="reference internal" href="../library/sys.html#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal"><span class="pre">sys.stderr</span></code></a>. If not set, the exception is
 
1019
swallowed.</p>
 
1020
<div class="admonition note">
 
1021
<p class="first admonition-title">Note</p>
 
1022
<p class="last">The default value of <code class="xref py py-data docutils literal"><span class="pre">raiseExceptions</span></code> is <code class="docutils literal"><span class="pre">True</span></code>. This is
 
1023
because during development, you typically want to be notified of any
 
1024
exceptions that occur. It&#8217;s advised that you set <code class="xref py py-data docutils literal"><span class="pre">raiseExceptions</span></code> to
 
1025
<code class="docutils literal"><span class="pre">False</span></code> for production usage.</p>
 
1026
</div>
 
1027
</div>
 
1028
<div class="section" id="using-arbitrary-objects-as-messages">
 
1029
<span id="arbitrary-object-messages"></span><h2>Using arbitrary objects as messages<a class="headerlink" href="#using-arbitrary-objects-as-messages" title="Permalink to this headline">¶</a></h2>
 
1030
<p>In the preceding sections and examples, it has been assumed that the message
 
1031
passed when logging the event is a string. However, this is not the only
 
1032
possibility. You can pass an arbitrary object as a message, and its
 
1033
<a class="reference internal" href="../reference/datamodel.html#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal"><span class="pre">__str__()</span></code></a> method will be called when the logging system needs to
 
1034
convert it to a string representation. In fact, if you want to, you can avoid
 
1035
computing a string representation altogether - for example, the
 
1036
<a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><code class="xref py py-class docutils literal"><span class="pre">SocketHandler</span></code></a> emits an event by pickling it and sending it
 
1037
over the wire.</p>
 
1038
</div>
 
1039
<div class="section" id="optimization">
 
1040
<h2>Optimization<a class="headerlink" href="#optimization" title="Permalink to this headline">¶</a></h2>
 
1041
<p>Formatting of message arguments is deferred until it cannot be avoided.
 
1042
However, computing the arguments passed to the logging method can also be
 
1043
expensive, and you may want to avoid doing it if the logger will just throw
 
1044
away your event. To decide what to do, you can call the
 
1045
<a class="reference internal" href="../library/logging.html#logging.Logger.isEnabledFor" title="logging.Logger.isEnabledFor"><code class="xref py py-meth docutils literal"><span class="pre">isEnabledFor()</span></code></a> method which takes a level argument and returns
 
1046
true if the event would be created by the Logger for that level of call.
 
1047
You can write code like this:</p>
 
1048
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">logger</span><span class="o">.</span><span class="n">isEnabledFor</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">):</span>
 
1049
    <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;Message with </span><span class="si">%s</span><span class="s1">, </span><span class="si">%s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">expensive_func1</span><span class="p">(),</span>
 
1050
                                        <span class="n">expensive_func2</span><span class="p">())</span>
 
1051
</pre></div>
 
1052
</div>
 
1053
<p>so that if the logger&#8217;s threshold is set above <code class="docutils literal"><span class="pre">DEBUG</span></code>, the calls to
 
1054
<code class="xref py py-func docutils literal"><span class="pre">expensive_func1()</span></code> and <code class="xref py py-func docutils literal"><span class="pre">expensive_func2()</span></code> are never made.</p>
 
1055
<div class="admonition note">
 
1056
<p class="first admonition-title">Note</p>
 
1057
<p class="last">In some cases, <a class="reference internal" href="../library/logging.html#logging.Logger.isEnabledFor" title="logging.Logger.isEnabledFor"><code class="xref py py-meth docutils literal"><span class="pre">isEnabledFor()</span></code></a> can itself be more
 
1058
expensive than you&#8217;d like (e.g. for deeply nested loggers where an explicit
 
1059
level is only set high up in the logger hierarchy). In such cases (or if you
 
1060
want to avoid calling a method in tight loops), you can cache the result of a
 
1061
call to <a class="reference internal" href="../library/logging.html#logging.Logger.isEnabledFor" title="logging.Logger.isEnabledFor"><code class="xref py py-meth docutils literal"><span class="pre">isEnabledFor()</span></code></a> in a local or instance variable, and use
 
1062
that instead of calling the method each time. Such a cached value would only
 
1063
need to be recomputed when the logging configuration changes dynamically
 
1064
while the application is running (which is not all that common).</p>
 
1065
</div>
 
1066
<p>There are other optimizations which can be made for specific applications which
 
1067
need more precise control over what logging information is collected. Here&#8217;s a
 
1068
list of things you can do to avoid processing during logging which you don&#8217;t
 
1069
need:</p>
 
1070
<table border="1" class="docutils">
 
1071
<colgroup>
 
1072
<col width="54%" />
 
1073
<col width="46%" />
 
1074
</colgroup>
 
1075
<thead valign="bottom">
 
1076
<tr class="row-odd"><th class="head">What you don&#8217;t want to collect</th>
 
1077
<th class="head">How to avoid collecting it</th>
 
1078
</tr>
 
1079
</thead>
 
1080
<tbody valign="top">
 
1081
<tr class="row-even"><td>Information about where calls were made from.</td>
 
1082
<td>Set <code class="docutils literal"><span class="pre">logging._srcfile</span></code> to <code class="docutils literal"><span class="pre">None</span></code>.
 
1083
This avoids calling
 
1084
<a class="reference internal" href="../library/sys.html#sys._getframe" title="sys._getframe"><code class="xref py py-func docutils literal"><span class="pre">sys._getframe()</span></code></a>, which may help
 
1085
to speed up your code in environments
 
1086
like PyPy (which can&#8217;t speed up code
 
1087
that uses <a class="reference internal" href="../library/sys.html#sys._getframe" title="sys._getframe"><code class="xref py py-func docutils literal"><span class="pre">sys._getframe()</span></code></a>), if
 
1088
and when PyPy supports Python 3.x.</td>
 
1089
</tr>
 
1090
<tr class="row-odd"><td>Threading information.</td>
 
1091
<td>Set <code class="docutils literal"><span class="pre">logging.logThreads</span></code> to <code class="docutils literal"><span class="pre">0</span></code>.</td>
 
1092
</tr>
 
1093
<tr class="row-even"><td>Process information.</td>
 
1094
<td>Set <code class="docutils literal"><span class="pre">logging.logProcesses</span></code> to <code class="docutils literal"><span class="pre">0</span></code>.</td>
 
1095
</tr>
 
1096
</tbody>
 
1097
</table>
 
1098
<p>Also note that the core logging module only includes the basic handlers. If
 
1099
you don&#8217;t import <a class="reference internal" href="../library/logging.handlers.html#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></code></a> and <a class="reference internal" href="../library/logging.config.html#module-logging.config" title="logging.config: Configuration of the logging module."><code class="xref py py-mod docutils literal"><span class="pre">logging.config</span></code></a>, they won&#8217;t
 
1100
take up any memory.</p>
 
1101
<div class="admonition seealso">
 
1102
<p class="first admonition-title">See also</p>
 
1103
<dl class="docutils">
 
1104
<dt>Module <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal"><span class="pre">logging</span></code></a></dt>
 
1105
<dd>API reference for the logging module.</dd>
 
1106
<dt>Module <a class="reference internal" href="../library/logging.config.html#module-logging.config" title="logging.config: Configuration of the logging module."><code class="xref py py-mod docutils literal"><span class="pre">logging.config</span></code></a></dt>
 
1107
<dd>Configuration API for the logging module.</dd>
 
1108
<dt>Module <a class="reference internal" href="../library/logging.handlers.html#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></code></a></dt>
 
1109
<dd>Useful handlers included with the logging module.</dd>
 
1110
</dl>
 
1111
<p class="last"><a class="reference internal" href="logging-cookbook.html#logging-cookbook"><span>A logging cookbook</span></a></p>
 
1112
</div>
 
1113
</div>
 
1114
</div>
 
1115
 
 
1116
 
 
1117
          </div>
 
1118
        </div>
 
1119
      </div>
 
1120
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
 
1121
        <div class="sphinxsidebarwrapper">
 
1122
  <h3><a href="../contents.html">Table Of Contents</a></h3>
 
1123
  <ul>
 
1124
<li><a class="reference internal" href="#">Logging HOWTO</a><ul>
 
1125
<li><a class="reference internal" href="#basic-logging-tutorial">Basic Logging Tutorial</a><ul>
 
1126
<li><a class="reference internal" href="#when-to-use-logging">When to use logging</a></li>
 
1127
<li><a class="reference internal" href="#a-simple-example">A simple example</a></li>
 
1128
<li><a class="reference internal" href="#logging-to-a-file">Logging to a file</a></li>
 
1129
<li><a class="reference internal" href="#logging-from-multiple-modules">Logging from multiple modules</a></li>
 
1130
<li><a class="reference internal" href="#logging-variable-data">Logging variable data</a></li>
 
1131
<li><a class="reference internal" href="#changing-the-format-of-displayed-messages">Changing the format of displayed messages</a></li>
 
1132
<li><a class="reference internal" href="#displaying-the-date-time-in-messages">Displaying the date/time in messages</a></li>
 
1133
<li><a class="reference internal" href="#next-steps">Next Steps</a></li>
 
1134
</ul>
 
1135
</li>
 
1136
<li><a class="reference internal" href="#advanced-logging-tutorial">Advanced Logging Tutorial</a><ul>
 
1137
<li><a class="reference internal" href="#logging-flow">Logging Flow</a></li>
 
1138
<li><a class="reference internal" href="#loggers">Loggers</a></li>
 
1139
<li><a class="reference internal" href="#handlers">Handlers</a></li>
 
1140
<li><a class="reference internal" href="#formatters">Formatters</a></li>
 
1141
<li><a class="reference internal" href="#configuring-logging">Configuring Logging</a></li>
 
1142
<li><a class="reference internal" href="#what-happens-if-no-configuration-is-provided">What happens if no configuration is provided</a></li>
 
1143
<li><a class="reference internal" href="#configuring-logging-for-a-library">Configuring Logging for a Library</a></li>
 
1144
</ul>
 
1145
</li>
 
1146
<li><a class="reference internal" href="#logging-levels">Logging Levels</a><ul>
 
1147
<li><a class="reference internal" href="#custom-levels">Custom Levels</a></li>
 
1148
</ul>
 
1149
</li>
 
1150
<li><a class="reference internal" href="#useful-handlers">Useful Handlers</a></li>
 
1151
<li><a class="reference internal" href="#exceptions-raised-during-logging">Exceptions raised during logging</a></li>
 
1152
<li><a class="reference internal" href="#using-arbitrary-objects-as-messages">Using arbitrary objects as messages</a></li>
 
1153
<li><a class="reference internal" href="#optimization">Optimization</a></li>
 
1154
</ul>
 
1155
</li>
 
1156
</ul>
 
1157
 
 
1158
  <h4>Previous topic</h4>
 
1159
  <p class="topless"><a href="functional.html"
 
1160
                        title="previous chapter">Functional Programming HOWTO</a></p>
 
1161
  <h4>Next topic</h4>
 
1162
  <p class="topless"><a href="logging-cookbook.html"
 
1163
                        title="next chapter">Logging Cookbook</a></p>
 
1164
  <div role="note" aria-label="source link">
 
1165
    <h3>This Page</h3>
 
1166
    <ul class="this-page-menu">
 
1167
      <li><a href="../bugs.html">Report a Bug</a></li>
 
1168
      <li><a href="../_sources/howto/logging.txt"
 
1169
            rel="nofollow">Show Source</a></li>
 
1170
    </ul>
 
1171
  </div>
 
1172
        </div>
 
1173
      </div>
 
1174
      <div class="clearer"></div>
 
1175
    </div>  
 
1176
    <div class="related" role="navigation" aria-label="related navigation">
 
1177
      <h3>Navigation</h3>
 
1178
      <ul>
 
1179
        <li class="right" style="margin-right: 10px">
 
1180
          <a href="../genindex.html" title="General Index"
 
1181
             >index</a></li>
 
1182
        <li class="right" >
 
1183
          <a href="../py-modindex.html" title="Python Module Index"
 
1184
             >modules</a> |</li>
 
1185
        <li class="right" >
 
1186
          <a href="logging-cookbook.html" title="Logging Cookbook"
 
1187
             >next</a> |</li>
 
1188
        <li class="right" >
 
1189
          <a href="functional.html" title="Functional Programming HOWTO"
 
1190
             >previous</a> |</li>
 
1191
        <li><img src="../_static/py.png" alt=""
 
1192
                 style="vertical-align: middle; margin-top: -1px"/></li>
 
1193
        <li><a href="https://www.python.org/">Python</a> &raquo;</li>
 
1194
        <li>
 
1195
          <span class="version_switcher_placeholder">3.5.2</span>
 
1196
          <a href="../index.html">Documentation </a> &raquo;
 
1197
        </li>
 
1198
 
 
1199
          <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &raquo;</li>
 
1200
    <li class="right">
 
1201
        
 
1202
 
 
1203
    <div class="inline-search" style="display: none" role="search">
 
1204
        <form class="inline-search" action="../search.html" method="get">
 
1205
          <input placeholder="Quick search" type="text" name="q" />
 
1206
          <input type="submit" value="Go" />
 
1207
          <input type="hidden" name="check_keywords" value="yes" />
 
1208
          <input type="hidden" name="area" value="default" />
 
1209
        </form>
 
1210
    </div>
 
1211
    <script type="text/javascript">$('.inline-search').show(0);</script>
 
1212
         |
 
1213
    </li>
 
1214
 
 
1215
      </ul>
 
1216
    </div>  
 
1217
    <div class="footer">
 
1218
    &copy; <a href="../copyright.html">Copyright</a> 2001-2016, Python Software Foundation.
 
1219
    <br />
 
1220
    The Python Software Foundation is a non-profit corporation.
 
1221
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
 
1222
    <br />
 
1223
    Last updated on Oct 19, 2016.
 
1224
    <a href="../bugs.html">Found a bug</a>?
 
1225
    <br />
 
1226
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.3.3.
 
1227
    </div>
 
1228
 
 
1229
  </body>
 
1230
</html>
 
 
b'\\ No newline at end of file'