Linux server.nvwebsoft.co.in 3.10.0-1160.114.2.el7.x86_64 #1 SMP Wed Mar 20 15:54:52 UTC 2024 x86_64
Apache
: 162.240.12.249 | : 52.15.209.178
202 Domain
8.1.31
nbspublicschool
www.github.com/MadExploits
Terminal
AUTO ROOT
Adminer
Backdoor Destroyer
Linux Exploit
Lock Shell
Lock File
Create User
CREATE RDP
PHP Mailer
BACKCONNECT
UNLOCK SHELL
HASH IDENTIFIER
CPANEL RESET
CREATE WP USER
README
+ Create Folder
+ Create File
/
usr /
share /
doc /
python-docs-2.7.5 /
html /
howto /
[ HOME SHELL ]
Name
Size
Permission
Action
argparse.html
72.39
KB
-rw-r--r--
cporting.html
39.22
KB
-rw-r--r--
curses.html
42.8
KB
-rw-r--r--
descriptor.html
50.15
KB
-rw-r--r--
doanddont.html
38.69
KB
-rw-r--r--
functional.html
109
KB
-rw-r--r--
index.html
7.51
KB
-rw-r--r--
logging-cookbook.html
103.51
KB
-rw-r--r--
logging.html
93.47
KB
-rw-r--r--
pyporting.html
60.8
KB
-rw-r--r--
regex.html
133.84
KB
-rw-r--r--
sockets.html
39.93
KB
-rw-r--r--
sorting.html
44.25
KB
-rw-r--r--
unicode.html
64.29
KB
-rw-r--r--
urllib2.html
58.48
KB
-rw-r--r--
webservers.html
55.66
KB
-rw-r--r--
Delete
Unzip
Zip
${this.title}
Close
Code Editor : logging.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Logging HOWTO — Python 2.7.5 documentation</title> <link rel="stylesheet" href="../_static/default.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '2.7.5', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 2.7.5 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="top" title="Python 2.7.5 documentation" href="../index.html" /> <link rel="up" title="Python HOWTOs" href="index.html" /> <link rel="next" title="Logging Cookbook" href="logging-cookbook.html" /> <link rel="prev" title="Functional Programming HOWTO" href="functional.html" /> <link rel="shortcut icon" type="image/png" href="../_static/py.png" /> <script type="text/javascript" src="../_static/copybutton.js"></script> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="logging-cookbook.html" title="Logging Cookbook" accesskey="N">next</a> |</li> <li class="right" > <a href="functional.html" title="Functional Programming HOWTO" accesskey="P">previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="http://www.python.org/">Python</a> »</li> <li> <a href="../index.html">Python 2.7.5 documentation</a> » </li> <li><a href="index.html" accesskey="U">Python HOWTOs</a> »</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <div class="section" id="logging-howto"> <h1>Logging HOWTO<a class="headerlink" href="#logging-howto" title="Permalink to this headline">¶</a></h1> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">Vinay Sajip <vinay_sajip at red-dove dot com></td> </tr> </tbody> </table> <div class="section" id="basic-logging-tutorial"> <span id="logging-basic-tutorial"></span><h2>Basic Logging Tutorial<a class="headerlink" href="#basic-logging-tutorial" title="Permalink to this headline">¶</a></h2> <p>Logging is a means of tracking events that happen when some software runs. The software’s developer adds logging calls to their code to indicate that certain events have occurred. An event is described by a descriptive message which can optionally contain variable data (i.e. data that is potentially different for each occurrence of the event). Events also have an importance which the developer ascribes to the event; the importance can also be called the <em>level</em> or <em>severity</em>.</p> <div class="section" id="when-to-use-logging"> <h3>When to use logging<a class="headerlink" href="#when-to-use-logging" title="Permalink to this headline">¶</a></h3> <p>Logging provides a set of convenience functions for simple logging usage. These are <a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><tt class="xref py py-func docutils literal"><span class="pre">debug()</span></tt></a>, <a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><tt class="xref py py-func docutils literal"><span class="pre">info()</span></tt></a>, <a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><tt class="xref py py-func docutils literal"><span class="pre">warning()</span></tt></a>, <a class="reference internal" href="../library/logging.html#logging.error" title="logging.error"><tt class="xref py py-func docutils literal"><span class="pre">error()</span></tt></a> and <a class="reference internal" href="../library/logging.html#logging.critical" title="logging.critical"><tt class="xref py py-func docutils literal"><span class="pre">critical()</span></tt></a>. To determine when to use logging, see the table below, which states, for each of a set of common tasks, the best tool to use for it.</p> <table border="1" class="docutils"> <colgroup> <col width="49%" /> <col width="51%" /> </colgroup> <thead valign="bottom"> <tr class="row-odd"><th class="head">Task you want to perform</th> <th class="head">The best tool for the task</th> </tr> </thead> <tbody valign="top"> <tr class="row-even"><td>Display console output for ordinary usage of a command line script or program</td> <td><a class="reference internal" href="../library/functions.html#print" title="print"><tt class="xref py py-func docutils literal"><span class="pre">print()</span></tt></a></td> </tr> <tr class="row-odd"><td>Report events that occur during normal operation of a program (e.g. for status monitoring or fault investigation)</td> <td><a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><tt class="xref py py-func docutils literal"><span class="pre">logging.info()</span></tt></a> (or <a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><tt class="xref py py-func docutils literal"><span class="pre">logging.debug()</span></tt></a> for very detailed output for diagnostic purposes)</td> </tr> <tr class="row-even"><td>Issue a warning regarding a particular runtime event</td> <td><p class="first"><a class="reference internal" href="../library/warnings.html#warnings.warn" title="warnings.warn"><tt class="xref py py-func docutils literal"><span class="pre">warnings.warn()</span></tt></a> in library code if the issue is avoidable and the client application should be modified to eliminate the warning</p> <p class="last"><a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><tt class="xref py py-func docutils literal"><span class="pre">logging.warning()</span></tt></a> if there is nothing the client application can do about the situation, but the event should still be noted</p> </td> </tr> <tr class="row-odd"><td>Report an error regarding a particular runtime event</td> <td>Raise an exception</td> </tr> <tr class="row-even"><td>Report suppression of an error without raising an exception (e.g. error handler in a long-running server process)</td> <td><a class="reference internal" href="../library/logging.html#logging.error" title="logging.error"><tt class="xref py py-func docutils literal"><span class="pre">logging.error()</span></tt></a>, <a class="reference internal" href="../library/logging.html#logging.exception" title="logging.exception"><tt class="xref py py-func docutils literal"><span class="pre">logging.exception()</span></tt></a> or <a class="reference internal" href="../library/logging.html#logging.critical" title="logging.critical"><tt class="xref py py-func docutils literal"><span class="pre">logging.critical()</span></tt></a> as appropriate for the specific error and application domain</td> </tr> </tbody> </table> <p>The logging functions are named after the level or severity of the events they are used to track. The standard levels and their applicability are described below (in increasing order of severity):</p> <table border="1" class="docutils"> <colgroup> <col width="24%" /> <col width="76%" /> </colgroup> <thead valign="bottom"> <tr class="row-odd"><th class="head">Level</th> <th class="head">When it’s used</th> </tr> </thead> <tbody valign="top"> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">DEBUG</span></tt></td> <td>Detailed information, typically of interest only when diagnosing problems.</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">INFO</span></tt></td> <td>Confirmation that things are working as expected.</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">WARNING</span></tt></td> <td>An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">ERROR</span></tt></td> <td>Due to a more serious problem, the software has not been able to perform some function.</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">CRITICAL</span></tt></td> <td>A serious error, indicating that the program itself may be unable to continue running.</td> </tr> </tbody> </table> <p>The default level is <tt class="docutils literal"><span class="pre">WARNING</span></tt>, which means that only events of this level and above will be tracked, unless the logging package is configured to do otherwise.</p> <p>Events that are tracked can be handled in different ways. The simplest way of handling tracked events is to print them to the console. Another common way is to write them to a disk file.</p> </div> <div class="section" id="a-simple-example"> <span id="howto-minimal-example"></span><h3>A simple example<a class="headerlink" href="#a-simple-example" title="Permalink to this headline">¶</a></h3> <p>A very simple example is:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span> <span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s">'Watch out!'</span><span class="p">)</span> <span class="c"># will print a message to the console</span> <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">'I told you so'</span><span class="p">)</span> <span class="c"># will not print anything</span> </pre></div> </div> <p>If you type these lines into a script and run it, you’ll see:</p> <div class="highlight-python"><pre>WARNING:root:Watch out!</pre> </div> <p>printed out on the console. The <tt class="docutils literal"><span class="pre">INFO</span></tt> message doesn’t appear because the default level is <tt class="docutils literal"><span class="pre">WARNING</span></tt>. The printed message includes the indication of the level and the description of the event provided in the logging call, i.e. ‘Watch out!’. Don’t worry about the ‘root’ part for now: it will be explained later. The actual output can be formatted quite flexibly if you need that; formatting options will also be explained later.</p> </div> <div class="section" id="logging-to-a-file"> <h3>Logging to a file<a class="headerlink" href="#logging-to-a-file" title="Permalink to this headline">¶</a></h3> <p>A very common situation is that of recording logging events in a file, so let’s look at that next:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</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="s">'example.log'</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> <span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">'This message should go to the log file'</span><span class="p">)</span> <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">'So should this'</span><span class="p">)</span> <span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s">'And this, too'</span><span class="p">)</span> </pre></div> </div> <p>And now if we open the file and look at what we have, we should find the log messages:</p> <div class="highlight-python"><pre>DEBUG:root:This message should go to the log file INFO:root:So should this WARNING:root:And this, too</pre> </div> <p>This example also shows how you can set the logging level which acts as the threshold for tracking. In this case, because we set the threshold to <tt class="docutils literal"><span class="pre">DEBUG</span></tt>, all of the messages were printed.</p> <p>If you want to set the logging level from a command-line option such as:</p> <div class="highlight-python"><div class="highlight"><pre><span class="o">--</span><span class="n">log</span><span class="o">=</span><span class="n">INFO</span> </pre></div> </div> <p>and you have the value of the parameter passed for <tt class="docutils literal"><span class="pre">--log</span></tt> in some variable <em>loglevel</em>, you can use:</p> <div class="highlight-python"><div class="highlight"><pre><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> </pre></div> </div> <p>to get the value which you’ll pass to <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><tt class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></tt></a> via the <em>level</em> argument. You may want to error check any user input value, perhaps as in the following example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="c"># assuming loglevel is bound to the string value obtained from the</span> <span class="c"># command line argument. Convert to upper case to allow the user to</span> <span class="c"># specify --log=DEBUG or --log=debug</span> <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="bp">None</span><span class="p">)</span> <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> <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s">'Invalid log level: </span><span class="si">%s</span><span class="s">'</span> <span class="o">%</span> <span class="n">loglevel</span><span class="p">)</span> <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> </pre></div> </div> <p>The call to <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><tt class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></tt></a> should come <em>before</em> any calls to <a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><tt class="xref py py-func docutils literal"><span class="pre">debug()</span></tt></a>, <a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><tt class="xref py py-func docutils literal"><span class="pre">info()</span></tt></a> etc. As it’s intended as a one-off simple configuration facility, only the first call will actually do anything: subsequent calls are effectively no-ops.</p> <p>If you run the above script several times, the messages from successive runs are appended to the file <em>example.log</em>. If you want each run to start afresh, not remembering the messages from earlier runs, you can specify the <em>filemode</em> argument, by changing the call in the above example to:</p> <div class="highlight-python"><div class="highlight"><pre><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="s">'example.log'</span><span class="p">,</span> <span class="n">filemode</span><span class="o">=</span><span class="s">'w'</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> </pre></div> </div> <p>The output will be the same as before, but the log file is no longer appended to, so the messages from earlier runs are lost.</p> </div> <div class="section" id="logging-from-multiple-modules"> <h3>Logging from multiple modules<a class="headerlink" href="#logging-from-multiple-modules" title="Permalink to this headline">¶</a></h3> <p>If your program consists of multiple modules, here’s an example of how you could organize logging in it:</p> <div class="highlight-python"><div class="highlight"><pre><span class="c"># myapp.py</span> <span class="kn">import</span> <span class="nn">logging</span> <span class="kn">import</span> <span class="nn">mylib</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</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="s">'myapp.log'</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> <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">'Started'</span><span class="p">)</span> <span class="n">mylib</span><span class="o">.</span><span class="n">do_something</span><span class="p">()</span> <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">'Finished'</span><span class="p">)</span> <span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">'__main__'</span><span class="p">:</span> <span class="n">main</span><span class="p">()</span> </pre></div> </div> <div class="highlight-python"><div class="highlight"><pre><span class="c"># mylib.py</span> <span class="kn">import</span> <span class="nn">logging</span> <span class="k">def</span> <span class="nf">do_something</span><span class="p">():</span> <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">'Doing something'</span><span class="p">)</span> </pre></div> </div> <p>If you run <em>myapp.py</em>, you should see this in <em>myapp.log</em>:</p> <div class="highlight-python"><pre>INFO:root:Started INFO:root:Doing something INFO:root:Finished</pre> </div> <p>which is hopefully what you were expecting to see. You can generalize this to multiple modules, using the pattern in <em>mylib.py</em>. Note that for this simple usage pattern, you won’t know, by looking in the log file, <em>where</em> in your application your messages came from, apart from looking at the event description. If you want to track the location of your messages, you’ll need to refer to the documentation beyond the tutorial level – see <a class="reference internal" href="#logging-advanced-tutorial"><em>Advanced Logging Tutorial</em></a>.</p> </div> <div class="section" id="logging-variable-data"> <h3>Logging variable data<a class="headerlink" href="#logging-variable-data" title="Permalink to this headline">¶</a></h3> <p>To log variable data, use a format string for the event description message and append the variable data as arguments. For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span> <span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s">'</span><span class="si">%s</span><span class="s"> before you </span><span class="si">%s</span><span class="s">'</span><span class="p">,</span> <span class="s">'Look'</span><span class="p">,</span> <span class="s">'leap!'</span><span class="p">)</span> </pre></div> </div> <p>will display:</p> <div class="highlight-python"><pre>WARNING:root:Look before you leap!</pre> </div> <p>As you can see, merging of variable data into the event description message uses the old, %-style of string formatting. This is for backwards compatibility: the logging package pre-dates newer formatting options such as <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><tt class="xref py py-meth docutils literal"><span class="pre">str.format()</span></tt></a> and <a class="reference internal" href="../library/string.html#string.Template" title="string.Template"><tt class="xref py py-class docutils literal"><span class="pre">string.Template</span></tt></a>. These newer formatting options <em>are</em> supported, but exploring them is outside the scope of this tutorial.</p> </div> <div class="section" id="changing-the-format-of-displayed-messages"> <h3>Changing the format of displayed messages<a class="headerlink" href="#changing-the-format-of-displayed-messages" title="Permalink to this headline">¶</a></h3> <p>To change the format which is used to display messages, you need to specify the format you want to use:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span> <span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">format</span><span class="o">=</span><span class="s">'</span><span class="si">%(levelname)s</span><span class="s">:</span><span class="si">%(message)s</span><span class="s">'</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> <span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">'This message should appear on the console'</span><span class="p">)</span> <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">'So should this'</span><span class="p">)</span> <span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s">'And this, too'</span><span class="p">)</span> </pre></div> </div> <p>which would print:</p> <div class="highlight-python"><pre>DEBUG:This message should appear on the console INFO:So should this WARNING:And this, too</pre> </div> <p>Notice that the ‘root’ which appeared in earlier examples has disappeared. For a full set of things that can appear in format strings, you can refer to the documentation for <a class="reference internal" href="../library/logging.html#logrecord-attributes"><em>LogRecord attributes</em></a>, but for simple usage, you just need the <em>levelname</em> (severity), <em>message</em> (event description, including variable data) and perhaps to display when the event occurred. This is described in the next section.</p> </div> <div class="section" id="displaying-the-date-time-in-messages"> <h3>Displaying the date/time in messages<a class="headerlink" href="#displaying-the-date-time-in-messages" title="Permalink to this headline">¶</a></h3> <p>To display the date and time of an event, you would place ‘%(asctime)s’ in your format string:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span> <span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">format</span><span class="o">=</span><span class="s">'</span><span class="si">%(asctime)s</span><span class="s"> </span><span class="si">%(message)s</span><span class="s">'</span><span class="p">)</span> <span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s">'is when this event was logged.'</span><span class="p">)</span> </pre></div> </div> <p>which should print something like this:</p> <div class="highlight-python"><pre>2010-12-12 11:41:42,612 is when this event was logged.</pre> </div> <p>The default format for date/time display (shown above) is ISO8601. If you need more control over the formatting of the date/time, provide a <em>datefmt</em> argument to <tt class="docutils literal"><span class="pre">basicConfig</span></tt>, as in this example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span> <span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">format</span><span class="o">=</span><span class="s">'</span><span class="si">%(asctime)s</span><span class="s"> </span><span class="si">%(message)s</span><span class="s">'</span><span class="p">,</span> <span class="n">datefmt</span><span class="o">=</span><span class="s">'%m/</span><span class="si">%d</span><span class="s">/%Y %I:%M:%S %p'</span><span class="p">)</span> <span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s">'is when this event was logged.'</span><span class="p">)</span> </pre></div> </div> <p>which would display something like this:</p> <div class="highlight-python"><pre>12/12/2010 11:46:36 AM is when this event was logged.</pre> </div> <p>The format of the <em>datefmt</em> argument is the same as supported by <a class="reference internal" href="../library/time.html#time.strftime" title="time.strftime"><tt class="xref py py-func docutils literal"><span class="pre">time.strftime()</span></tt></a>.</p> </div> <div class="section" id="next-steps"> <h3>Next Steps<a class="headerlink" href="#next-steps" title="Permalink to this headline">¶</a></h3> <p>That concludes the basic tutorial. It should be enough to get you up and running with logging. There’s a lot more that the logging package offers, but to get the best out of it, you’ll need to invest a little more of your time in reading the following sections. If you’re ready for that, grab some of your favourite beverage and carry on.</p> <p>If your logging needs are simple, then use the above examples to incorporate logging into your own scripts, and if you run into problems or don’t understand something, please post a question on the comp.lang.python Usenet group (available at <a class="reference external" href="http://groups.google.com/group/comp.lang.python">http://groups.google.com/group/comp.lang.python</a>) and you should receive help before too long.</p> <p>Still here? You can carry on reading the next few sections, which provide a slightly more advanced/in-depth tutorial than the basic one above. After that, you can take a look at the <a class="reference internal" href="logging-cookbook.html#logging-cookbook"><em>Logging Cookbook</em></a>.</p> </div> </div> <div class="section" id="advanced-logging-tutorial"> <span id="logging-advanced-tutorial"></span><h2>Advanced Logging Tutorial<a class="headerlink" href="#advanced-logging-tutorial" title="Permalink to this headline">¶</a></h2> <p>The logging library takes a modular approach and offers several categories of components: loggers, handlers, filters, and formatters.</p> <ul class="simple"> <li>Loggers expose the interface that application code directly uses.</li> <li>Handlers send the log records (created by loggers) to the appropriate destination.</li> <li>Filters provide a finer grained facility for determining which log records to output.</li> <li>Formatters specify the layout of log records in the final output.</li> </ul> <p>Log event information is passed between loggers, handlers, filters and formatters in a <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> instance.</p> <p>Logging is performed by calling methods on instances of the <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt></a> class (hereafter called <em class="dfn">loggers</em>). Each instance has a name, and they are conceptually arranged in a namespace hierarchy using dots (periods) as separators. For example, a logger named ‘scan’ is the parent of loggers ‘scan.text’, ‘scan.html’ and ‘scan.pdf’. Logger names can be anything you want, and indicate the area of an application in which a logged message originates.</p> <p>A good convention to use when naming loggers is to use a module-level logger, in each module which uses logging, named as follows:</p> <div class="highlight-python"><div class="highlight"><pre><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> </pre></div> </div> <p>This means that logger names track the package/module hierarchy, and it’s intuitively obvious where events are logged just from the logger name.</p> <p>The root of the hierarchy of loggers is called the root logger. That’s the logger used by the functions <a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><tt class="xref py py-func docutils literal"><span class="pre">debug()</span></tt></a>, <a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><tt class="xref py py-func docutils literal"><span class="pre">info()</span></tt></a>, <a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><tt class="xref py py-func docutils literal"><span class="pre">warning()</span></tt></a>, <a class="reference internal" href="../library/logging.html#logging.error" title="logging.error"><tt class="xref py py-func docutils literal"><span class="pre">error()</span></tt></a> and <a class="reference internal" href="../library/logging.html#logging.critical" title="logging.critical"><tt class="xref py py-func docutils literal"><span class="pre">critical()</span></tt></a>, which just call the same-named method of the root logger. The functions and the methods have the same signatures. The root logger’s name is printed as ‘root’ in the logged output.</p> <p>It is, of course, possible to log messages to different destinations. Support is included in the package for writing log messages to files, HTTP GET/POST locations, email via SMTP, generic sockets, or OS-specific logging mechanisms such as syslog or the Windows NT event log. Destinations are served by <em class="dfn">handler</em> classes. You can create your own log destination class if you have special requirements not met by any of the built-in handler classes.</p> <p>By default, no destination is set for any logging messages. You can specify a destination (such as console or file) by using <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><tt class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></tt></a> as in the tutorial examples. If you call the functions <a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><tt class="xref py py-func docutils literal"><span class="pre">debug()</span></tt></a>, <a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><tt class="xref py py-func docutils literal"><span class="pre">info()</span></tt></a>, <a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><tt class="xref py py-func docutils literal"><span class="pre">warning()</span></tt></a>, <a class="reference internal" href="../library/logging.html#logging.error" title="logging.error"><tt class="xref py py-func docutils literal"><span class="pre">error()</span></tt></a> and <a class="reference internal" href="../library/logging.html#logging.critical" title="logging.critical"><tt class="xref py py-func docutils literal"><span class="pre">critical()</span></tt></a>, they will check to see if no destination is set; and if one is not set, they will set a destination of the console (<tt class="docutils literal"><span class="pre">sys.stderr</span></tt>) and a default format for the displayed message before delegating to the root logger to do the actual message output.</p> <p>The default format set by <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><tt class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></tt></a> for messages is:</p> <div class="highlight-python"><pre>severity:logger name:message</pre> </div> <p>You can change this by passing a format string to <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><tt class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></tt></a> with the <em>format</em> keyword argument. For all options regarding how a format string is constructed, see <a class="reference internal" href="../library/logging.html#formatter-objects"><em>Formatter Objects</em></a>.</p> <div class="section" id="logging-flow"> <h3>Logging Flow<a class="headerlink" href="#logging-flow" title="Permalink to this headline">¶</a></h3> <p>The flow of log event information in loggers and handlers is illustrated in the following diagram.</p> <img alt="../_images/logging_flow.png" src="../_images/logging_flow.png" /> </div> <div class="section" id="loggers"> <h3>Loggers<a class="headerlink" href="#loggers" title="Permalink to this headline">¶</a></h3> <p><a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt></a> objects have a threefold job. First, they expose several methods to application code so that applications can log messages at runtime. Second, logger objects determine which log messages to act upon based upon severity (the default filtering facility) or filter objects. Third, logger objects pass along relevant log messages to all interested log handlers.</p> <p>The most widely used methods on logger objects fall into two categories: configuration and message sending.</p> <p>These are the most common configuration methods:</p> <ul class="simple"> <li><a class="reference internal" href="../library/logging.html#logging.Logger.setLevel" title="logging.Logger.setLevel"><tt class="xref py py-meth docutils literal"><span class="pre">Logger.setLevel()</span></tt></a> specifies the lowest-severity log message a logger will handle, where debug is the lowest built-in severity level and critical is the highest built-in severity. For example, if the severity level is INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL messages and will ignore DEBUG messages.</li> <li><a class="reference internal" href="../library/logging.html#logging.Logger.addHandler" title="logging.Logger.addHandler"><tt class="xref py py-meth docutils literal"><span class="pre">Logger.addHandler()</span></tt></a> and <a class="reference internal" href="../library/logging.html#logging.Logger.removeHandler" title="logging.Logger.removeHandler"><tt class="xref py py-meth docutils literal"><span class="pre">Logger.removeHandler()</span></tt></a> add and remove handler objects from the logger object. Handlers are covered in more detail in <a class="reference internal" href="#handler-basic"><em>Handlers</em></a>.</li> <li><a class="reference internal" href="../library/logging.html#logging.Logger.addFilter" title="logging.Logger.addFilter"><tt class="xref py py-meth docutils literal"><span class="pre">Logger.addFilter()</span></tt></a> and <a class="reference internal" href="../library/logging.html#logging.Logger.removeFilter" title="logging.Logger.removeFilter"><tt class="xref py py-meth docutils literal"><span class="pre">Logger.removeFilter()</span></tt></a> add and remove filter objects from the logger object. Filters are covered in more detail in <a class="reference internal" href="../library/logging.html#filter"><em>Filter Objects</em></a>.</li> </ul> <p>You don’t need to always call these methods on every logger you create. See the last two paragraphs in this section.</p> <p>With the logger object configured, the following methods create log messages:</p> <ul class="simple"> <li><a class="reference internal" href="../library/logging.html#logging.Logger.debug" title="logging.Logger.debug"><tt class="xref py py-meth docutils literal"><span class="pre">Logger.debug()</span></tt></a>, <a class="reference internal" href="../library/logging.html#logging.Logger.info" title="logging.Logger.info"><tt class="xref py py-meth docutils literal"><span class="pre">Logger.info()</span></tt></a>, <a class="reference internal" href="../library/logging.html#logging.Logger.warning" title="logging.Logger.warning"><tt class="xref py py-meth docutils literal"><span class="pre">Logger.warning()</span></tt></a>, <a class="reference internal" href="../library/logging.html#logging.Logger.error" title="logging.Logger.error"><tt class="xref py py-meth docutils literal"><span class="pre">Logger.error()</span></tt></a>, and <a class="reference internal" href="../library/logging.html#logging.Logger.critical" title="logging.Logger.critical"><tt class="xref py py-meth docutils literal"><span class="pre">Logger.critical()</span></tt></a> all create log records with a message and a level that corresponds to their respective method names. The message is actually a format string, which may contain the standard string substitution syntax of <tt class="xref py py-const docutils literal"><span class="pre">%s</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">%d</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">%f</span></tt>, and so on. The rest of their arguments is a list of objects that correspond with the substitution fields in the message. With regard to <tt class="xref py py-const docutils literal"><span class="pre">**kwargs</span></tt>, the logging methods care only about a keyword of <tt class="xref py py-const docutils literal"><span class="pre">exc_info</span></tt> and use it to determine whether to log exception information.</li> <li><a class="reference internal" href="../library/logging.html#logging.Logger.exception" title="logging.Logger.exception"><tt class="xref py py-meth docutils literal"><span class="pre">Logger.exception()</span></tt></a> creates a log message similar to <a class="reference internal" href="../library/logging.html#logging.Logger.error" title="logging.Logger.error"><tt class="xref py py-meth docutils literal"><span class="pre">Logger.error()</span></tt></a>. The difference is that <a class="reference internal" href="../library/logging.html#logging.Logger.exception" title="logging.Logger.exception"><tt class="xref py py-meth docutils literal"><span class="pre">Logger.exception()</span></tt></a> dumps a stack trace along with it. Call this method only from an exception handler.</li> <li><a class="reference internal" href="../library/logging.html#logging.Logger.log" title="logging.Logger.log"><tt class="xref py py-meth docutils literal"><span class="pre">Logger.log()</span></tt></a> takes a log level as an explicit argument. This is a little more verbose for logging messages than using the log level convenience methods listed above, but this is how to log at custom log levels.</li> </ul> <p><a class="reference internal" href="../library/logging.html#logging.getLogger" title="logging.getLogger"><tt class="xref py py-func docutils literal"><span class="pre">getLogger()</span></tt></a> returns a reference to a logger instance with the specified name if it is provided, or <tt class="docutils literal"><span class="pre">root</span></tt> if not. The names are period-separated hierarchical structures. Multiple calls to <a class="reference internal" href="../library/logging.html#logging.getLogger" title="logging.getLogger"><tt class="xref py py-func docutils literal"><span class="pre">getLogger()</span></tt></a> with the same name will return a reference to the same logger object. Loggers that are further down in the hierarchical list are children of loggers higher up in the list. For example, given a logger with a name of <tt class="docutils literal"><span class="pre">foo</span></tt>, loggers with names of <tt class="docutils literal"><span class="pre">foo.bar</span></tt>, <tt class="docutils literal"><span class="pre">foo.bar.baz</span></tt>, and <tt class="docutils literal"><span class="pre">foo.bam</span></tt> are all descendants of <tt class="docutils literal"><span class="pre">foo</span></tt>.</p> <p>Loggers have a concept of <em>effective level</em>. If a level is not explicitly set on a logger, the level of its parent is used instead as its effective level. If the parent has no explicit level set, <em>its</em> parent is examined, and so on - all ancestors are searched until an explicitly set level is found. The root logger always has an explicit level set (<tt class="docutils literal"><span class="pre">WARNING</span></tt> by default). When deciding whether to process an event, the effective level of the logger is used to determine whether the event is passed to the logger’s handlers.</p> <p>Child loggers propagate messages up to the handlers associated with their ancestor loggers. Because of this, it is unnecessary to define and configure handlers for all the loggers an application uses. It is sufficient to configure handlers for a top-level logger and create child loggers as needed. (You can, however, turn off propagation by setting the <em>propagate</em> attribute of a logger to <em>False</em>.)</p> </div> <div class="section" id="handlers"> <span id="handler-basic"></span><h3>Handlers<a class="headerlink" href="#handlers" title="Permalink to this headline">¶</a></h3> <p><tt class="xref py py-class docutils literal"><span class="pre">Handler</span></tt> objects are responsible for dispatching the appropriate log messages (based on the log messages’ severity) to the handler’s specified destination. Logger objects can add zero or more handler objects to themselves with an <tt class="xref py py-func docutils literal"><span class="pre">addHandler()</span></tt> method. As an example scenario, an application may want to send all log messages to a log file, all log messages of error or higher to stdout, and all messages of critical to an email address. This scenario requires three individual handlers where each handler is responsible for sending messages of a specific severity to a specific location.</p> <p>The standard library includes quite a few handler types (see <a class="reference internal" href="#useful-handlers"><em>Useful Handlers</em></a>); the tutorials use mainly <a class="reference internal" href="../library/logging.handlers.html#logging.StreamHandler" title="logging.StreamHandler"><tt class="xref py py-class docutils literal"><span class="pre">StreamHandler</span></tt></a> and <a class="reference internal" href="../library/logging.handlers.html#logging.FileHandler" title="logging.FileHandler"><tt class="xref py py-class docutils literal"><span class="pre">FileHandler</span></tt></a> in its examples.</p> <p>There are very few methods in a handler for application developers to concern themselves with. The only handler methods that seem relevant for application developers who are using the built-in handler objects (that is, not creating custom handlers) are the following configuration methods:</p> <ul class="simple"> <li>The <a class="reference internal" href="../library/logging.html#logging.Handler.setLevel" title="logging.Handler.setLevel"><tt class="xref py py-meth docutils literal"><span class="pre">Handler.setLevel()</span></tt></a> method, just as in logger objects, specifies the lowest severity that will be dispatched to the appropriate destination. Why are there two <tt class="xref py py-func docutils literal"><span class="pre">setLevel()</span></tt> methods? The level set in the logger determines which severity of messages it will pass to its handlers. The level set in each handler determines which messages that handler will send on.</li> <li><tt class="xref py py-func docutils literal"><span class="pre">setFormatter()</span></tt> selects a Formatter object for this handler to use.</li> <li><tt class="xref py py-func docutils literal"><span class="pre">addFilter()</span></tt> and <tt class="xref py py-func docutils literal"><span class="pre">removeFilter()</span></tt> respectively configure and deconfigure filter objects on handlers.</li> </ul> <p>Application code should not directly instantiate and use instances of <tt class="xref py py-class docutils literal"><span class="pre">Handler</span></tt>. Instead, the <tt class="xref py py-class docutils literal"><span class="pre">Handler</span></tt> class is a base class that defines the interface that all handlers should have and establishes some default behavior that child classes can use (or override).</p> </div> <div class="section" id="formatters"> <h3>Formatters<a class="headerlink" href="#formatters" title="Permalink to this headline">¶</a></h3> <p>Formatter objects configure the final order, structure, and contents of the log message. Unlike the base <tt class="xref py py-class docutils literal"><span class="pre">logging.Handler</span></tt> class, application code may instantiate formatter classes, although you could likely subclass the formatter if your application needs special behavior. The constructor takes two optional arguments – a message format string and a date format string.</p> <dl class="method"> <dt id="logging.logging.Formatter.__init__"> <tt class="descclassname">logging.Formatter.</tt><tt class="descname">__init__</tt><big>(</big><em>fmt=None</em>, <em>datefmt=None</em><big>)</big><a class="headerlink" href="#logging.logging.Formatter.__init__" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>If there is no message format string, the default is to use the raw message. If there is no date format string, the default date format is:</p> <div class="highlight-python"><pre>%Y-%m-%d %H:%M:%S</pre> </div> <p>with the milliseconds tacked on at the end.</p> <p>The message format string uses <tt class="docutils literal"><span class="pre">%(<dictionary</span> <span class="pre">key>)s</span></tt> styled string substitution; the possible keys are documented in <a class="reference internal" href="../library/logging.html#logrecord-attributes"><em>LogRecord attributes</em></a>.</p> <p>The following message format string will log the time in a human-readable format, the severity of the message, and the contents of the message, in that order:</p> <div class="highlight-python"><div class="highlight"><pre><span class="s">'</span><span class="si">%(asctime)s</span><span class="s"> - </span><span class="si">%(levelname)s</span><span class="s"> - </span><span class="si">%(message)s</span><span class="s">'</span> </pre></div> </div> <p>Formatters use a user-configurable function to convert the creation time of a record to a tuple. By default, <a class="reference internal" href="../library/time.html#time.localtime" title="time.localtime"><tt class="xref py py-func docutils literal"><span class="pre">time.localtime()</span></tt></a> is used; to change this for a particular formatter instance, set the <tt class="docutils literal"><span class="pre">converter</span></tt> attribute of the instance to a function with the same signature as <a class="reference internal" href="../library/time.html#time.localtime" title="time.localtime"><tt class="xref py py-func docutils literal"><span class="pre">time.localtime()</span></tt></a> or <a class="reference internal" href="../library/time.html#time.gmtime" title="time.gmtime"><tt class="xref py py-func docutils literal"><span class="pre">time.gmtime()</span></tt></a>. To change it for all formatters, for example if you want all logging times to be shown in GMT, set the <tt class="docutils literal"><span class="pre">converter</span></tt> attribute in the Formatter class (to <tt class="docutils literal"><span class="pre">time.gmtime</span></tt> for GMT display).</p> </div> <div class="section" id="configuring-logging"> <h3>Configuring Logging<a class="headerlink" href="#configuring-logging" title="Permalink to this headline">¶</a></h3> <p>Programmers can configure logging in three ways:</p> <ol class="arabic simple"> <li>Creating loggers, handlers, and formatters explicitly using Python code that calls the configuration methods listed above.</li> <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"><tt class="xref py py-func docutils literal"><span class="pre">fileConfig()</span></tt></a> function.</li> <li>Creating a dictionary of configuration information and passing it to the <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><tt class="xref py py-func docutils literal"><span class="pre">dictConfig()</span></tt></a> function.</li> </ol> <p>For the reference documentation on the last two options, see <a class="reference internal" href="../library/logging.config.html#logging-config-api"><em>Configuration functions</em></a>. The following example configures a very simple logger, a console handler, and a simple formatter using Python code:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span> <span class="c"># create logger</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="s">'simple_example'</span><span class="p">)</span> <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> <span class="c"># create console handler and set level to debug</span> <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> <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> <span class="c"># create formatter</span> <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="s">'</span><span class="si">%(asctime)s</span><span class="s"> - </span><span class="si">%(name)s</span><span class="s"> - </span><span class="si">%(levelname)s</span><span class="s"> - </span><span class="si">%(message)s</span><span class="s">'</span><span class="p">)</span> <span class="c"># add formatter to ch</span> <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> <span class="c"># add ch to logger</span> <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> <span class="c"># 'application' code</span> <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">'debug message'</span><span class="p">)</span> <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">'info message'</span><span class="p">)</span> <span class="n">logger</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s">'warn message'</span><span class="p">)</span> <span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s">'error message'</span><span class="p">)</span> <span class="n">logger</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s">'critical message'</span><span class="p">)</span> </pre></div> </div> <p>Running this module from the command line produces the following output:</p> <div class="highlight-python"><pre>$ python simple_logging_module.py 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message 2005-03-19 15:10:26,620 - simple_example - INFO - info message 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message 2005-03-19 15:10:26,697 - simple_example - ERROR - error message 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message</pre> </div> <p>The following Python module creates a logger, handler, and formatter nearly identical to those in the example listed above, with the only difference being the names of the objects:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span> <span class="kn">import</span> <span class="nn">logging.config</span> <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="s">'logging.conf'</span><span class="p">)</span> <span class="c"># create logger</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="s">'simpleExample'</span><span class="p">)</span> <span class="c"># 'application' code</span> <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">'debug message'</span><span class="p">)</span> <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">'info message'</span><span class="p">)</span> <span class="n">logger</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s">'warn message'</span><span class="p">)</span> <span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s">'error message'</span><span class="p">)</span> <span class="n">logger</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s">'critical message'</span><span class="p">)</span> </pre></div> </div> <p>Here is the logging.conf file:</p> <div class="highlight-python"><pre>[loggers] keys=root,simpleExample [handlers] keys=consoleHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG handlers=consoleHandler [logger_simpleExample] level=DEBUG handlers=consoleHandler qualname=simpleExample propagate=0 [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=simpleFormatter args=(sys.stdout,) [formatter_simpleFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt=</pre> </div> <p>The output is nearly identical to that of the non-config-file-based example:</p> <div class="highlight-python"><pre>$ python simple_logging_config.py 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message 2005-03-19 15:38:55,979 - simpleExample - INFO - info message 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message</pre> </div> <p>You can see that the config file approach has a few advantages over the Python code approach, mainly separation of configuration and code and the ability of noncoders to easily modify the logging properties.</p> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p>The <a class="reference internal" href="../library/logging.config.html#logging.config.fileConfig" title="logging.config.fileConfig"><tt class="xref py py-func docutils literal"><span class="pre">fileConfig()</span></tt></a> function takes a default parameter, <tt class="docutils literal"><span class="pre">disable_existing_loggers</span></tt>, which defaults to <tt class="docutils literal"><span class="pre">True</span></tt> for reasons of backward compatibility. This may or may not be what you want, since it will cause any loggers existing before the <a class="reference internal" href="../library/logging.config.html#logging.config.fileConfig" title="logging.config.fileConfig"><tt class="xref py py-func docutils literal"><span class="pre">fileConfig()</span></tt></a> call to be disabled unless they (or an ancestor) are explicitly named in the configuration. Please refer to the reference documentation for more information, and specify <tt class="docutils literal"><span class="pre">False</span></tt> for this parameter if you wish.</p> <p class="last">The dictionary passed to <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><tt class="xref py py-func docutils literal"><span class="pre">dictConfig()</span></tt></a> can also specify a Boolean value with key <tt class="docutils literal"><span class="pre">disable_existing_loggers</span></tt>, which if not specified explicitly in the dictionary also defaults to being interpreted as <tt class="docutils literal"><span class="pre">True</span></tt>. This leads to the logger-disabling behaviour described above, which may not be what you want - in which case, provide the key explicitly with a value of <tt class="docutils literal"><span class="pre">False</span></tt>.</p> </div> <p>Note that the class names referenced in config files need to be either relative to the logging module, or absolute values which can be resolved using normal import mechanisms. Thus, you could use either <a class="reference internal" href="../library/logging.handlers.html#logging.handlers.WatchedFileHandler" title="logging.handlers.WatchedFileHandler"><tt class="xref py py-class docutils literal"><span class="pre">WatchedFileHandler</span></tt></a> (relative to the logging module) or <tt class="docutils literal"><span class="pre">mypackage.mymodule.MyHandler</span></tt> (for a class defined in package <tt class="docutils literal"><span class="pre">mypackage</span></tt> and module <tt class="docutils literal"><span class="pre">mymodule</span></tt>, where <tt class="docutils literal"><span class="pre">mypackage</span></tt> is available on the Python import path).</p> <p>In Python 2.7, a new means of configuring logging has been introduced, using dictionaries to hold configuration information. This provides a superset of the functionality of the config-file-based approach outlined above, and is the recommended configuration method for new applications and deployments. Because a Python dictionary is used to hold configuration information, and since you can populate that dictionary using different means, you have more options for configuration. For example, you can use a configuration file in JSON format, or, if you have access to YAML processing functionality, a file in YAML format, to populate the configuration dictionary. Or, of course, you can construct the dictionary in Python code, receive it in pickled form over a socket, or use whatever approach makes sense for your application.</p> <p>Here’s an example of the same configuration as above, in YAML format for the new dictionary-based approach:</p> <div class="highlight-python"><pre>version: 1 formatters: simple: format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' handlers: console: class: logging.StreamHandler level: DEBUG formatter: simple stream: ext://sys.stdout loggers: simpleExample: level: DEBUG handlers: [console] propagate: no root: level: DEBUG handlers: [console]</pre> </div> <p>For more information about logging using a dictionary, see <a class="reference internal" href="../library/logging.config.html#logging-config-api"><em>Configuration functions</em></a>.</p> </div> <div class="section" id="what-happens-if-no-configuration-is-provided"> <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> <p>If no logging configuration is provided, it is possible to have a situation where a logging event needs to be output, but no handlers can be found to output the event. The behaviour of the logging package in these circumstances is dependent on the Python version.</p> <p>For Python 2.x, the behaviour is as follows:</p> <ul class="simple"> <li>If <em>logging.raiseExceptions</em> is <em>False</em> (production mode), the event is silently dropped.</li> <li>If <em>logging.raiseExceptions</em> is <em>True</em> (development mode), a message ‘No handlers could be found for logger X.Y.Z’ is printed once.</li> </ul> </div> <div class="section" id="configuring-logging-for-a-library"> <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> <p>When developing a library which uses logging, you should take care to document how the library uses logging - for example, the names of loggers used. Some consideration also needs to be given to its logging configuration. If the using application does not configure logging, and library code makes logging calls, then (as described in the previous section) an error message will be printed to <tt class="docutils literal"><span class="pre">sys.stderr</span></tt>.</p> <p>If for some reason you <em>don’t</em> want this message printed in the absence of any logging configuration, you can attach a do-nothing handler to the top-level logger for your library. This avoids the message being printed, since a handler will be always be found for the library’s events: it just doesn’t produce any output. If the library user configures logging for application use, presumably that configuration will add some handlers, and if levels are suitably configured then logging calls made in library code will send output to those handlers, as normal.</p> <p>A do-nothing handler is included in the logging package: <a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><tt class="xref py py-class docutils literal"><span class="pre">NullHandler</span></tt></a> (since Python 2.7). An instance of this handler could be added to the top-level logger of the logging namespace used by the library (<em>if</em> you want to prevent an error message being output to <tt class="docutils literal"><span class="pre">sys.stderr</span></tt> in the absence of logging configuration). If all logging by a library <em>foo</em> is done using loggers with names matching ‘foo.x’, ‘foo.x.y’, etc. then the code:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">'foo'</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> </pre></div> </div> <p>should have the desired effect. If an organisation produces a number of libraries, then the logger name specified can be ‘orgname.foo’ rather than just ‘foo’.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">It is strongly advised that you <em>do not add any handlers other than</em> <a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><tt class="xref py py-class docutils literal"><span class="pre">NullHandler</span></tt></a> <em>to your library’s loggers</em>. This is because the configuration of handlers is the prerogative of the application developer who uses your library. The application developer knows their target audience and what handlers are most appropriate for their application: if you add handlers ‘under the hood’, you might well interfere with their ability to carry out unit tests and deliver logs which suit their requirements.</p> </div> </div> </div> <div class="section" id="logging-levels"> <h2>Logging Levels<a class="headerlink" href="#logging-levels" title="Permalink to this headline">¶</a></h2> <p>The numeric values of logging levels are given in the following table. These are primarily of interest if you want to define your own levels, and need them to have specific values relative to the predefined levels. If you define a level with the same numeric value, it overwrites the predefined value; the predefined name is lost.</p> <table border="1" class="docutils"> <colgroup> <col width="48%" /> <col width="52%" /> </colgroup> <thead valign="bottom"> <tr class="row-odd"><th class="head">Level</th> <th class="head">Numeric value</th> </tr> </thead> <tbody valign="top"> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">CRITICAL</span></tt></td> <td>50</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">ERROR</span></tt></td> <td>40</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">WARNING</span></tt></td> <td>30</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">INFO</span></tt></td> <td>20</td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">DEBUG</span></tt></td> <td>10</td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">NOTSET</span></tt></td> <td>0</td> </tr> </tbody> </table> <p>Levels can also be associated with loggers, being set either by the developer or through loading a saved logging configuration. When a logging method is called on a logger, the logger compares its own level with the level associated with the method call. If the logger’s level is higher than the method call’s, no logging message is actually generated. This is the basic mechanism controlling the verbosity of logging output.</p> <p>Logging messages are encoded as instances of the <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> class. When a logger decides to actually log an event, a <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> instance is created from the logging message.</p> <p>Logging messages are subjected to a dispatch mechanism through the use of <em class="dfn">handlers</em>, which are instances of subclasses of the <tt class="xref py py-class docutils literal"><span class="pre">Handler</span></tt> class. Handlers are responsible for ensuring that a logged message (in the form of a <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a>) ends up in a particular location (or set of locations) which is useful for the target audience for that message (such as end users, support desk staff, system administrators, developers). Handlers are passed <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> instances intended for particular destinations. Each logger can have zero, one or more handlers associated with it (via the <a class="reference internal" href="../library/logging.html#logging.Logger.addHandler" title="logging.Logger.addHandler"><tt class="xref py py-meth docutils literal"><span class="pre">addHandler()</span></tt></a> method of <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt></a>). In addition to any handlers directly associated with a logger, <em>all handlers associated with all ancestors of the logger</em> are called to dispatch the message (unless the <em>propagate</em> flag for a logger is set to a false value, at which point the passing to ancestor handlers stops).</p> <p>Just as for loggers, handlers can have levels associated with them. A handler’s level acts as a filter in the same way as a logger’s level does. If a handler decides to actually dispatch an event, the <a class="reference internal" href="../library/logging.html#logging.Handler.emit" title="logging.Handler.emit"><tt class="xref py py-meth docutils literal"><span class="pre">emit()</span></tt></a> method is used to send the message to its destination. Most user-defined subclasses of <tt class="xref py py-class docutils literal"><span class="pre">Handler</span></tt> will need to override this <a class="reference internal" href="../library/logging.html#logging.Handler.emit" title="logging.Handler.emit"><tt class="xref py py-meth docutils literal"><span class="pre">emit()</span></tt></a>.</p> <div class="section" id="custom-levels"> <span id="id1"></span><h3>Custom Levels<a class="headerlink" href="#custom-levels" title="Permalink to this headline">¶</a></h3> <p>Defining your own levels is possible, but should not be necessary, as the existing levels have been chosen on the basis of practical experience. However, if you are convinced that you need custom levels, great care should be exercised when doing this, and it is possibly <em>a very bad idea to define custom levels if you are developing a library</em>. That’s because if multiple library authors all define their own custom levels, there is a chance that the logging output from such multiple libraries used together will be difficult for the using developer to control and/or interpret, because a given numeric value might mean different things for different libraries.</p> </div> </div> <div class="section" id="useful-handlers"> <span id="id2"></span><h2>Useful Handlers<a class="headerlink" href="#useful-handlers" title="Permalink to this headline">¶</a></h2> <p>In addition to the base <tt class="xref py py-class docutils literal"><span class="pre">Handler</span></tt> class, many useful subclasses are provided:</p> <ol class="arabic simple"> <li><a class="reference internal" href="../library/logging.handlers.html#logging.StreamHandler" title="logging.StreamHandler"><tt class="xref py py-class docutils literal"><span class="pre">StreamHandler</span></tt></a> instances send messages to streams (file-like objects).</li> <li><a class="reference internal" href="../library/logging.handlers.html#logging.FileHandler" title="logging.FileHandler"><tt class="xref py py-class docutils literal"><span class="pre">FileHandler</span></tt></a> instances send messages to disk files.</li> <li><tt class="xref py py-class docutils literal"><span class="pre">BaseRotatingHandler</span></tt> is the base class for handlers that rotate log files at a certain point. It is not meant to be instantiated directly. Instead, use <a class="reference internal" href="../library/logging.handlers.html#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><tt class="xref py py-class docutils literal"><span class="pre">RotatingFileHandler</span></tt></a> or <a class="reference internal" href="../library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler" title="logging.handlers.TimedRotatingFileHandler"><tt class="xref py py-class docutils literal"><span class="pre">TimedRotatingFileHandler</span></tt></a>.</li> <li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><tt class="xref py py-class docutils literal"><span class="pre">RotatingFileHandler</span></tt></a> instances send messages to disk files, with support for maximum log file sizes and log file rotation.</li> <li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler" title="logging.handlers.TimedRotatingFileHandler"><tt class="xref py py-class docutils literal"><span class="pre">TimedRotatingFileHandler</span></tt></a> instances send messages to disk files, rotating the log file at certain timed intervals.</li> <li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><tt class="xref py py-class docutils literal"><span class="pre">SocketHandler</span></tt></a> instances send messages to TCP/IP sockets.</li> <li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.DatagramHandler" title="logging.handlers.DatagramHandler"><tt class="xref py py-class docutils literal"><span class="pre">DatagramHandler</span></tt></a> instances send messages to UDP sockets.</li> <li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SMTPHandler" title="logging.handlers.SMTPHandler"><tt class="xref py py-class docutils literal"><span class="pre">SMTPHandler</span></tt></a> instances send messages to a designated email address.</li> <li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><tt class="xref py py-class docutils literal"><span class="pre">SysLogHandler</span></tt></a> instances send messages to a Unix syslog daemon, possibly on a remote machine.</li> <li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.NTEventLogHandler" title="logging.handlers.NTEventLogHandler"><tt class="xref py py-class docutils literal"><span class="pre">NTEventLogHandler</span></tt></a> instances send messages to a Windows NT/2000/XP event log.</li> <li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.MemoryHandler" title="logging.handlers.MemoryHandler"><tt class="xref py py-class docutils literal"><span class="pre">MemoryHandler</span></tt></a> instances send messages to a buffer in memory, which is flushed whenever specific criteria are met.</li> <li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.HTTPHandler" title="logging.handlers.HTTPHandler"><tt class="xref py py-class docutils literal"><span class="pre">HTTPHandler</span></tt></a> instances send messages to an HTTP server using either <tt class="docutils literal"><span class="pre">GET</span></tt> or <tt class="docutils literal"><span class="pre">POST</span></tt> semantics.</li> <li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.WatchedFileHandler" title="logging.handlers.WatchedFileHandler"><tt class="xref py py-class docutils literal"><span class="pre">WatchedFileHandler</span></tt></a> instances watch the file they are logging to. If the file changes, it is closed and reopened using the file name. This handler is only useful on Unix-like systems; Windows does not support the underlying mechanism used.</li> <li><a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><tt class="xref py py-class docutils literal"><span class="pre">NullHandler</span></tt></a> instances do nothing with error messages. They are used by library developers who want to use logging, but want to avoid the ‘No handlers could be found for logger XXX’ message which can be displayed if the library user has not configured logging. See <a class="reference internal" href="#library-config"><em>Configuring Logging for a Library</em></a> for more information.</li> </ol> <p class="versionadded"> <span class="versionmodified">New in version 2.7: </span>The <a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><tt class="xref py py-class docutils literal"><span class="pre">NullHandler</span></tt></a> class.</p> <p>The <a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><tt class="xref py py-class docutils literal"><span class="pre">NullHandler</span></tt></a>, <a class="reference internal" href="../library/logging.handlers.html#logging.StreamHandler" title="logging.StreamHandler"><tt class="xref py py-class docutils literal"><span class="pre">StreamHandler</span></tt></a> and <a class="reference internal" href="../library/logging.handlers.html#logging.FileHandler" title="logging.FileHandler"><tt class="xref py py-class docutils literal"><span class="pre">FileHandler</span></tt></a> classes are defined in the core logging package. The other handlers are 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."><tt class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></tt></a>. (There is also another sub-module, <a class="reference internal" href="../library/logging.config.html#module-logging.config" title="logging.config: Configuration of the logging module."><tt class="xref py py-mod docutils literal"><span class="pre">logging.config</span></tt></a>, for configuration functionality.)</p> <p>Logged messages are formatted for presentation through instances of the <a class="reference internal" href="../library/logging.html#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> class. They are initialized with a format string suitable for use with the % operator and a dictionary.</p> <p>For formatting multiple messages in a batch, instances of <tt class="xref py py-class docutils literal"><span class="pre">BufferingFormatter</span></tt> can be used. In addition to the format string (which is applied to each message in the batch), there is provision for header and trailer format strings.</p> <p>When filtering based on logger level and/or handler level is not enough, instances of <a class="reference internal" href="../library/logging.html#logging.Filter" title="logging.Filter"><tt class="xref py py-class docutils literal"><span class="pre">Filter</span></tt></a> can be added to both <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt></a> and <tt class="xref py py-class docutils literal"><span class="pre">Handler</span></tt> instances (through their <tt class="xref py py-meth docutils literal"><span class="pre">addFilter()</span></tt> method). Before deciding to process a message further, both loggers and handlers consult all their filters for permission. If any filter returns a false value, the message is not processed further.</p> <p>The basic <a class="reference internal" href="../library/logging.html#logging.Filter" title="logging.Filter"><tt class="xref py py-class docutils literal"><span class="pre">Filter</span></tt></a> functionality allows filtering by specific logger name. If this feature is used, messages sent to the named logger and its children are allowed through the filter, and all others dropped.</p> </div> <div class="section" id="exceptions-raised-during-logging"> <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> <p>The logging package is designed to swallow exceptions which occur while logging in production. This is so that errors which occur while handling logging events - such as logging misconfiguration, network or other similar errors - do not cause the application using logging to terminate prematurely.</p> <p><tt class="xref py py-class docutils literal"><span class="pre">SystemExit</span></tt> and <tt class="xref py py-class docutils literal"><span class="pre">KeyboardInterrupt</span></tt> exceptions are never swallowed. Other exceptions which occur during the <tt class="xref py py-meth docutils literal"><span class="pre">emit()</span></tt> method of a <tt class="xref py py-class docutils literal"><span class="pre">Handler</span></tt> subclass are passed to its <tt class="xref py py-meth docutils literal"><span class="pre">handleError()</span></tt> method.</p> <p>The default implementation of <tt class="xref py py-meth docutils literal"><span class="pre">handleError()</span></tt> in <tt class="xref py py-class docutils literal"><span class="pre">Handler</span></tt> checks to see if a module-level variable, <tt class="xref py py-data docutils literal"><span class="pre">raiseExceptions</span></tt>, is set. If set, a traceback is printed to <a class="reference internal" href="../library/sys.html#sys.stderr" title="sys.stderr"><tt class="xref py py-data docutils literal"><span class="pre">sys.stderr</span></tt></a>. If not set, the exception is swallowed.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">The default value of <tt class="xref py py-data docutils literal"><span class="pre">raiseExceptions</span></tt> is <tt class="docutils literal"><span class="pre">True</span></tt>. This is because during development, you typically want to be notified of any exceptions that occur. It’s advised that you set <tt class="xref py py-data docutils literal"><span class="pre">raiseExceptions</span></tt> to <tt class="docutils literal"><span class="pre">False</span></tt> for production usage.</p> </div> </div> <div class="section" id="using-arbitrary-objects-as-messages"> <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> <p>In the preceding sections and examples, it has been assumed that the message passed when logging the event is a string. However, this is not the only possibility. You can pass an arbitrary object as a message, and its <a class="reference internal" href="../reference/datamodel.html#object.__str__" title="object.__str__"><tt class="xref py py-meth docutils literal"><span class="pre">__str__()</span></tt></a> method will be called when the logging system needs to convert it to a string representation. In fact, if you want to, you can avoid computing a string representation altogether - for example, the <tt class="xref py py-class docutils literal"><span class="pre">SocketHandler</span></tt> emits an event by pickling it and sending it over the wire.</p> </div> <div class="section" id="optimization"> <h2>Optimization<a class="headerlink" href="#optimization" title="Permalink to this headline">¶</a></h2> <p>Formatting of message arguments is deferred until it cannot be avoided. However, computing the arguments passed to the logging method can also be expensive, and you may want to avoid doing it if the logger will just throw away your event. To decide what to do, you can call the <tt class="xref py py-meth docutils literal"><span class="pre">isEnabledFor()</span></tt> method which takes a level argument and returns true if the event would be created by the Logger for that level of call. You can write code like this:</p> <div class="highlight-python"><div class="highlight"><pre><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> <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">'Message with </span><span class="si">%s</span><span class="s">, </span><span class="si">%s</span><span class="s">'</span><span class="p">,</span> <span class="n">expensive_func1</span><span class="p">(),</span> <span class="n">expensive_func2</span><span class="p">())</span> </pre></div> </div> <p>so that if the logger’s threshold is set above <tt class="docutils literal"><span class="pre">DEBUG</span></tt>, the calls to <tt class="xref py py-func docutils literal"><span class="pre">expensive_func1()</span></tt> and <tt class="xref py py-func docutils literal"><span class="pre">expensive_func2()</span></tt> are never made.</p> <p>There are other optimizations which can be made for specific applications which need more precise control over what logging information is collected. Here’s a list of things you can do to avoid processing during logging which you don’t need:</p> <table border="1" class="docutils"> <colgroup> <col width="54%" /> <col width="46%" /> </colgroup> <thead valign="bottom"> <tr class="row-odd"><th class="head">What you don’t want to collect</th> <th class="head">How to avoid collecting it</th> </tr> </thead> <tbody valign="top"> <tr class="row-even"><td>Information about where calls were made from.</td> <td>Set <tt class="docutils literal"><span class="pre">logging._srcfile</span></tt> to <tt class="docutils literal"><span class="pre">None</span></tt>.</td> </tr> <tr class="row-odd"><td>Threading information.</td> <td>Set <tt class="docutils literal"><span class="pre">logging.logThreads</span></tt> to <tt class="docutils literal"><span class="pre">0</span></tt>.</td> </tr> <tr class="row-even"><td>Process information.</td> <td>Set <tt class="docutils literal"><span class="pre">logging.logProcesses</span></tt> to <tt class="docutils literal"><span class="pre">0</span></tt>.</td> </tr> </tbody> </table> <p>Also note that the core logging module only includes the basic handlers. If you don’t import <a class="reference internal" href="../library/logging.handlers.html#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><tt class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></tt></a> and <a class="reference internal" href="../library/logging.config.html#module-logging.config" title="logging.config: Configuration of the logging module."><tt class="xref py py-mod docutils literal"><span class="pre">logging.config</span></tt></a>, they won’t take up any memory.</p> <div class="admonition-see-also admonition seealso"> <p class="first admonition-title">See also</p> <dl class="docutils"> <dt>Module <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><tt class="xref py py-mod docutils literal"><span class="pre">logging</span></tt></a></dt> <dd>API reference for the logging module.</dd> <dt>Module <a class="reference internal" href="../library/logging.config.html#module-logging.config" title="logging.config: Configuration of the logging module."><tt class="xref py py-mod docutils literal"><span class="pre">logging.config</span></tt></a></dt> <dd>Configuration API for the logging module.</dd> <dt>Module <a class="reference internal" href="../library/logging.handlers.html#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><tt class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></tt></a></dt> <dd>Useful handlers included with the logging module.</dd> </dl> <p class="last"><a class="reference internal" href="logging-cookbook.html#logging-cookbook"><em>A logging cookbook</em></a></p> </div> </div> </div> </div> </div> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <h3><a href="../contents.html">Table Of Contents</a></h3> <ul> <li><a class="reference internal" href="#">Logging HOWTO</a><ul> <li><a class="reference internal" href="#basic-logging-tutorial">Basic Logging Tutorial</a><ul> <li><a class="reference internal" href="#when-to-use-logging">When to use logging</a></li> <li><a class="reference internal" href="#a-simple-example">A simple example</a></li> <li><a class="reference internal" href="#logging-to-a-file">Logging to a file</a></li> <li><a class="reference internal" href="#logging-from-multiple-modules">Logging from multiple modules</a></li> <li><a class="reference internal" href="#logging-variable-data">Logging variable data</a></li> <li><a class="reference internal" href="#changing-the-format-of-displayed-messages">Changing the format of displayed messages</a></li> <li><a class="reference internal" href="#displaying-the-date-time-in-messages">Displaying the date/time in messages</a></li> <li><a class="reference internal" href="#next-steps">Next Steps</a></li> </ul> </li> <li><a class="reference internal" href="#advanced-logging-tutorial">Advanced Logging Tutorial</a><ul> <li><a class="reference internal" href="#logging-flow">Logging Flow</a></li> <li><a class="reference internal" href="#loggers">Loggers</a></li> <li><a class="reference internal" href="#handlers">Handlers</a></li> <li><a class="reference internal" href="#formatters">Formatters</a></li> <li><a class="reference internal" href="#configuring-logging">Configuring Logging</a></li> <li><a class="reference internal" href="#what-happens-if-no-configuration-is-provided">What happens if no configuration is provided</a></li> <li><a class="reference internal" href="#configuring-logging-for-a-library">Configuring Logging for a Library</a></li> </ul> </li> <li><a class="reference internal" href="#logging-levels">Logging Levels</a><ul> <li><a class="reference internal" href="#custom-levels">Custom Levels</a></li> </ul> </li> <li><a class="reference internal" href="#useful-handlers">Useful Handlers</a></li> <li><a class="reference internal" href="#exceptions-raised-during-logging">Exceptions raised during logging</a></li> <li><a class="reference internal" href="#using-arbitrary-objects-as-messages">Using arbitrary objects as messages</a></li> <li><a class="reference internal" href="#optimization">Optimization</a></li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="functional.html" title="previous chapter">Functional Programming HOWTO</a></p> <h4>Next topic</h4> <p class="topless"><a href="logging-cookbook.html" title="next chapter">Logging Cookbook</a></p> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a Bug</a></li> <li><a href="../_sources/howto/logging.txt" rel="nofollow">Show Source</a></li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="logging-cookbook.html" title="Logging Cookbook" >next</a> |</li> <li class="right" > <a href="functional.html" title="Functional Programming HOWTO" >previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="http://www.python.org/">Python</a> »</li> <li> <a href="../index.html">Python 2.7.5 documentation</a> » </li> <li><a href="index.html" >Python HOWTOs</a> »</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 1990-2020, Python Software Foundation. <br /> The Python Software Foundation is a non-profit corporation. <a href="http://www.python.org/psf/donations/">Please donate.</a> <br /> Last updated on Oct 13, 2020. <a href="../bugs.html">Found a bug</a>? <br /> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3. </div> </body> </html>
Close