<!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>15.7. logging — Logging facility for Python — Python v2.7 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', 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> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python v2.7 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 v2.7 documentation" href="../index.html" /> <link rel="up" title="15. Generic Operating System Services" href="allos.html" /> <link rel="next" title="15.8. getpass — Portable password input" href="getpass.html" /> <link rel="prev" title="15.6. getopt — C-style parser for command line options" href="getopt.html" /> <link rel="shortcut icon" type="image/png" href="../_static/py.png" /> </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="getpass.html" title="15.8. getpass — Portable password input" accesskey="N">next</a> |</li> <li class="right" > <a href="getopt.html" title="15.6. getopt — C-style parser for command line options" accesskey="P">previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="../index.html">Python v2.7 documentation</a> »</li> <li><a href="index.html" >The Python Standard Library</a> »</li> <li><a href="allos.html" accesskey="U">15. Generic Operating System Services</a> »</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <div class="section" id="module-logging"> <span id="logging-logging-facility-for-python"></span><h1>15.7. <a class="reference internal" href="#module-logging" title="Flexible error logging system for applications."><tt class="xref py py-mod docutils literal"><span class="pre">logging</span></tt></a> — Logging facility for Python<a class="headerlink" href="#module-logging" title="Permalink to this headline">¶</a></h1> <p class="versionadded" id="index-0"> <span class="versionmodified">New in version 2.3.</span></p> <p>This module defines functions and classes which implement a flexible error logging system for applications.</p> <p>Logging is performed by calling methods on instances of the <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt> 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>Logged messages also have levels of importance associated with them. The default levels provided are <tt class="xref py py-const docutils literal"><span class="pre">DEBUG</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">INFO</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">WARNING</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">ERROR</span></tt> and <tt class="xref py py-const docutils literal"><span class="pre">CRITICAL</span></tt>. As a convenience, you indicate the importance of a logged message by calling an appropriate method of <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt>. The methods are <a class="reference internal" href="#logging.debug" title="logging.debug"><tt class="xref py py-meth docutils literal"><span class="pre">debug()</span></tt></a>, <a class="reference internal" href="#logging.info" title="logging.info"><tt class="xref py py-meth docutils literal"><span class="pre">info()</span></tt></a>, <a class="reference internal" href="#logging.warning" title="logging.warning"><tt class="xref py py-meth docutils literal"><span class="pre">warning()</span></tt></a>, <a class="reference internal" href="#logging.error" title="logging.error"><tt class="xref py py-meth docutils literal"><span class="pre">error()</span></tt></a> and <a class="reference internal" href="#logging.critical" title="logging.critical"><tt class="xref py py-meth docutils literal"><span class="pre">critical()</span></tt></a>, which mirror the default levels. You are not constrained to use these levels: you can specify your own and use a more general <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt> method, <a class="reference internal" href="#logging.log" title="logging.log"><tt class="xref py py-meth docutils literal"><span class="pre">log()</span></tt></a>, which takes an explicit level argument.</p> <div class="section" id="logging-tutorial"> <h2>15.7.1. Logging tutorial<a class="headerlink" href="#logging-tutorial" title="Permalink to this headline">¶</a></h2> <p>The key benefit of having the logging API provided by a standard library module is that all Python modules can participate in logging, so your application log can include messages from third-party modules.</p> <p>It is, of course, possible to log messages with different verbosity levels or to different destinations. Support for writing log messages to files, HTTP GET/POST locations, email via SMTP, generic sockets, or OS-specific logging mechanisms are all supported by the standard module. You can also create your own log destination class if you have special requirements not met by any of the built-in classes.</p> <div class="section" id="simple-examples"> <h3>15.7.1.1. Simple examples<a class="headerlink" href="#simple-examples" title="Permalink to this headline">¶</a></h3> <p>Most applications are probably going to want to log to a file, so let’s start with that case. Using the <a class="reference internal" href="#logging.basicConfig" title="logging.basicConfig"><tt class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></tt></a> function, we can set up the default handler so that debug messages are written to a file (in the example, we assume that you have the appropriate permissions to create a file called <em>example.log</em> in the current directory):</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span> <span class="n">LOG_FILENAME</span> <span class="o">=</span> <span class="s">'example.log'</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="n">LOG_FILENAME</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> </pre></div> </div> <p>And now if we open the file and look at what we have, we should find the log message:</p> <div class="highlight-python"><pre>DEBUG:root:This message should go to the log file</pre> </div> <p>If you run the script repeatedly, the additional log messages are appended to the file. To create a new file each time, you can pass a <em>filemode</em> argument to <a class="reference internal" href="#logging.basicConfig" title="logging.basicConfig"><tt class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></tt></a> with a value of <tt class="docutils literal"><span class="pre">'w'</span></tt>. Rather than managing the file size yourself, though, it is simpler to use a <tt class="xref py py-class docutils literal"><span class="pre">RotatingFileHandler</span></tt>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">glob</span> <span class="kn">import</span> <span class="nn">logging</span> <span class="kn">import</span> <span class="nn">logging.handlers</span> <span class="n">LOG_FILENAME</span> <span class="o">=</span> <span class="s">'logging_rotatingfile_example.out'</span> <span class="c"># Set up a specific logger with our desired output level</span> <span class="n">my_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">'MyLogger'</span><span class="p">)</span> <span class="n">my_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"># Add the log message handler to the logger</span> <span class="n">handler</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">handlers</span><span class="o">.</span><span class="n">RotatingFileHandler</span><span class="p">(</span> <span class="n">LOG_FILENAME</span><span class="p">,</span> <span class="n">maxBytes</span><span class="o">=</span><span class="mi">20</span><span class="p">,</span> <span class="n">backupCount</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span> <span class="n">my_logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">handler</span><span class="p">)</span> <span class="c"># Log some messages</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">20</span><span class="p">):</span> <span class="n">my_logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">'i = </span><span class="si">%d</span><span class="s">'</span> <span class="o">%</span> <span class="n">i</span><span class="p">)</span> <span class="c"># See what files are created</span> <span class="n">logfiles</span> <span class="o">=</span> <span class="n">glob</span><span class="o">.</span><span class="n">glob</span><span class="p">(</span><span class="s">'</span><span class="si">%s</span><span class="s">*'</span> <span class="o">%</span> <span class="n">LOG_FILENAME</span><span class="p">)</span> <span class="k">for</span> <span class="n">filename</span> <span class="ow">in</span> <span class="n">logfiles</span><span class="p">:</span> <span class="k">print</span> <span class="n">filename</span> </pre></div> </div> <p>The result should be 6 separate files, each with part of the log history for the application:</p> <div class="highlight-python"><pre>logging_rotatingfile_example.out logging_rotatingfile_example.out.1 logging_rotatingfile_example.out.2 logging_rotatingfile_example.out.3 logging_rotatingfile_example.out.4 logging_rotatingfile_example.out.5</pre> </div> <p>The most current file is always <tt class="file docutils literal"><span class="pre">logging_rotatingfile_example.out</span></tt>, and each time it reaches the size limit it is renamed with the suffix <tt class="docutils literal"><span class="pre">.1</span></tt>. Each of the existing backup files is renamed to increment the suffix (<tt class="docutils literal"><span class="pre">.1</span></tt> becomes <tt class="docutils literal"><span class="pre">.2</span></tt>, etc.) and the <tt class="docutils literal"><span class="pre">.6</span></tt> file is erased.</p> <p>Obviously this example sets the log length much much too small as an extreme example. You would want to set <em>maxBytes</em> to an appropriate value.</p> <p>Another useful feature of the logging API is the ability to produce different messages at different log levels. This allows you to instrument your code with debug messages, for example, but turning the log level down so that those debug messages are not written for your production system. The default levels are <tt class="docutils literal"><span class="pre">NOTSET</span></tt>, <tt class="docutils literal"><span class="pre">DEBUG</span></tt>, <tt class="docutils literal"><span class="pre">INFO</span></tt>, <tt class="docutils literal"><span class="pre">WARNING</span></tt>, <tt class="docutils literal"><span class="pre">ERROR</span></tt> and <tt class="docutils literal"><span class="pre">CRITICAL</span></tt>.</p> <p>The logger, handler, and log message call each specify a level. The log message is only emitted if the handler and logger are configured to emit messages of that level or lower. For example, if a message is <tt class="docutils literal"><span class="pre">CRITICAL</span></tt>, and the logger is set to <tt class="docutils literal"><span class="pre">ERROR</span></tt>, the message is emitted. If a message is a <tt class="docutils literal"><span class="pre">WARNING</span></tt>, and the logger is set to produce only <tt class="docutils literal"><span class="pre">ERROR</span></tt>s, the message is not emitted:</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">sys</span> <span class="n">LEVELS</span> <span class="o">=</span> <span class="p">{</span><span class="s">'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">'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">'warning'</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">'error'</span><span class="p">:</span> <span class="n">logging</span><span class="o">.</span><span class="n">ERROR</span><span class="p">,</span> <span class="s">'critical'</span><span class="p">:</span> <span class="n">logging</span><span class="o">.</span><span class="n">CRITICAL</span><span class="p">}</span> <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">)</span> <span class="o">></span> <span class="mi">1</span><span class="p">:</span> <span class="n">level_name</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="n">level</span> <span class="o">=</span> <span class="n">LEVELS</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">level_name</span><span class="p">,</span> <span class="n">logging</span><span class="o">.</span><span class="n">NOTSET</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">level</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 is a debug message'</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">'This is an info message'</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">'This is a warning message'</span><span class="p">)</span> <span class="n">logging</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s">'This is an error message'</span><span class="p">)</span> <span class="n">logging</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s">'This is a critical error message'</span><span class="p">)</span> </pre></div> </div> <p>Run the script with an argument like ‘debug’ or ‘warning’ to see which messages show up at different levels:</p> <div class="highlight-python"><pre>$ python logging_level_example.py debug DEBUG:root:This is a debug message INFO:root:This is an info message WARNING:root:This is a warning message ERROR:root:This is an error message CRITICAL:root:This is a critical error message $ python logging_level_example.py info INFO:root:This is an info message WARNING:root:This is a warning message ERROR:root:This is an error message CRITICAL:root:This is a critical error message</pre> </div> <p>You will notice that these log messages all have <tt class="docutils literal"><span class="pre">root</span></tt> embedded in them. The logging module supports a hierarchy of loggers with different names. An easy way to tell where a specific log message comes from is to use a separate logger object for each of your modules. Each new logger “inherits” the configuration of its parent, and log messages sent to a logger include the name of that logger. Optionally, each logger can be configured differently, so that messages from different modules are handled in different ways. Let’s look at a simple example of how to log from different modules so it is easy to trace the source of the message:</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">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">WARNING</span><span class="p">)</span> <span class="n">logger1</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">'package1.module1'</span><span class="p">)</span> <span class="n">logger2</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">'package2.module2'</span><span class="p">)</span> <span class="n">logger1</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s">'This message comes from one module'</span><span class="p">)</span> <span class="n">logger2</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s">'And this message comes from another module'</span><span class="p">)</span> </pre></div> </div> <p>And the output:</p> <div class="highlight-python"><pre>$ python logging_modules_example.py WARNING:package1.module1:This message comes from one module WARNING:package2.module2:And this message comes from another module</pre> </div> <p>There are many more options for configuring logging, including different log message formatting options, having messages delivered to multiple destinations, and changing the configuration of a long-running application on the fly using a socket interface. All of these options are covered in depth in the library module documentation.</p> </div> <div class="section" id="loggers"> <h3>15.7.1.2. Loggers<a class="headerlink" href="#loggers" title="Permalink to this headline">¶</a></h3> <p>The logging library takes a modular approach and offers the several categories of components: loggers, handlers, filters, and formatters. Loggers expose the interface that application code directly uses. Handlers send the log records to the appropriate destination. Filters provide a finer grained facility for determining which log records to send on to a handler. Formatters specify the layout of the resultant log record.</p> <p><tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt> 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> <ul class="simple"> <li><a class="reference internal" href="#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="#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="#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. This tutorial does not address filters.</li> </ul> <p>With the logger object configured, the following methods create log messages:</p> <ul class="simple"> <li><a class="reference internal" href="#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="#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="#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="#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="#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="#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="#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="#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="#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="#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 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="#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>. 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.</p> </div> <div class="section" id="handlers"> <h3>15.7.1.3. 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; this tutorial uses only <a class="reference internal" href="#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="#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="#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>15.7.1.4. 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. 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="#formatter"><em>Formatter Objects</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> </div> <div class="section" id="configuring-logging"> <h3>15.7.1.5. 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="#logging.fileConfig" title="logging.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="#logging.dictConfig" title="logging.dictConfig"><tt class="xref py py-func docutils literal"><span class="pre">dictConfig()</span></tt></a> function.</li> </ol> <p>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> <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="#logging.handlers.WatchedFileHandler" title="logging.handlers.WatchedFileHandler"><tt class="xref py py-class docutils literal"><span class="pre">handlers.WatchedFileHandler</span></tt></a> (relative to the logging module) or <tt class="xref py py-class docutils literal"><span class="pre">mypackage.mymodule.MyHandler</span></tt> (for a class defined in package <tt class="xref py py-mod docutils literal"><span class="pre">mypackage</span></tt> and module <tt class="xref py py-mod docutils literal"><span class="pre">mymodule</span></tt>, where <tt class="xref py py-mod docutils literal"><span class="pre">mypackage</span></tt> is available on the Python import path).</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.7.</span></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: 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="#logging-config-api"><em>Configuration functions</em></a>.</p> </div> <div class="section" id="configuring-logging-for-a-library"> <span id="library-config"></span><h3>15.7.1.6. 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, some consideration needs to be given to its configuration. If the using application does not use logging, and library code makes logging calls, then a one-off message “No handlers could be found for logger X.Y.Z” is printed to the console. This message is intended to catch mistakes in logging configuration, but will confuse an application developer who is not aware of logging by the library.</p> <p>In addition to documenting how a library uses logging, a good way to configure library logging so that it does not cause a spurious message is to add a handler which does nothing. This avoids the message being printed, since a handler will be found: 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 can be simply defined as follows:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span> <span class="k">class</span> <span class="nc">NullHandler</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">Handler</span><span class="p">):</span> <span class="k">def</span> <span class="nf">emit</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">record</span><span class="p">):</span> <span class="k">pass</span> </pre></div> </div> <p>An instance of this handler should be added to the top-level logger of the logging namespace used by the library. If all logging by a library <em>foo</em> is done using loggers with names matching “foo.x.y”, 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">h</span> <span class="o">=</span> <span class="n">NullHandler</span><span class="p">()</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">h</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> <p class="versionadded"> <span class="versionmodified">New in version 2.7.</span></p> <p>The <a class="reference internal" href="#logging.NullHandler" title="logging.NullHandler"><tt class="xref py py-class docutils literal"><span class="pre">NullHandler</span></tt></a> class was not present in previous versions, but is now included, so that it need not be defined in library code.</p> </div> </div> <div class="section" id="logging-levels"> <h2>15.7.2. 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><th class="head">Level</th> <th class="head">Numeric value</th> </tr> </thead> <tbody valign="top"> <tr><td><tt class="docutils literal"><span class="pre">CRITICAL</span></tt></td> <td>50</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">ERROR</span></tt></td> <td>40</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">WARNING</span></tt></td> <td>30</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">INFO</span></tt></td> <td>20</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">DEBUG</span></tt></td> <td>10</td> </tr> <tr><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="#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="#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="#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="#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 <tt class="xref py py-meth docutils literal"><span class="pre">addHandler()</span></tt> method of <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt>). 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 <tt class="xref py py-meth docutils literal"><span class="pre">emit()</span></tt> 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 <tt class="xref py py-meth docutils literal"><span class="pre">emit()</span></tt>.</p> </div> <div class="section" id="useful-handlers"> <h2>15.7.3. 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="#stream-handler"><em>StreamHandler</em></a> instances send error messages to streams (file-like objects).</li> <li><a class="reference internal" href="#file-handler"><em>FileHandler</em></a> instances send error 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="#rotating-file-handler"><em>RotatingFileHandler</em></a> or <a class="reference internal" href="#timed-rotating-file-handler"><em>TimedRotatingFileHandler</em></a>.</li> <li><a class="reference internal" href="#rotating-file-handler"><em>RotatingFileHandler</em></a> instances send error messages to disk files, with support for maximum log file sizes and log file rotation.</li> <li><a class="reference internal" href="#timed-rotating-file-handler"><em>TimedRotatingFileHandler</em></a> instances send error messages to disk files, rotating the log file at certain timed intervals.</li> <li><a class="reference internal" href="#socket-handler"><em>SocketHandler</em></a> instances send error messages to TCP/IP sockets.</li> <li><a class="reference internal" href="#datagram-handler"><em>DatagramHandler</em></a> instances send error messages to UDP sockets.</li> <li><a class="reference internal" href="#smtp-handler"><em>SMTPHandler</em></a> instances send error messages to a designated email address.</li> <li><a class="reference internal" href="#syslog-handler"><em>SysLogHandler</em></a> instances send error messages to a Unix syslog daemon, possibly on a remote machine.</li> <li><a class="reference internal" href="#nt-eventlog-handler"><em>NTEventLogHandler</em></a> instances send error messages to a Windows NT/2000/XP event log.</li> <li><a class="reference internal" href="#memory-handler"><em>MemoryHandler</em></a> instances send error messages to a buffer in memory, which is flushed whenever specific criteria are met.</li> <li><a class="reference internal" href="#http-handler"><em>HTTPHandler</em></a> instances send error 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="#watched-file-handler"><em>WatchedFileHandler</em></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="#null-handler"><em>NullHandler</em></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></p> <p>The <a class="reference internal" href="#logging.NullHandler" title="logging.NullHandler"><tt class="xref py py-class docutils literal"><span class="pre">NullHandler</span></tt></a> class was not present in previous versions.</p> <p>The <a class="reference internal" href="#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="#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="#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, <tt class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></tt>. (There is also another sub-module, <tt class="xref py py-mod docutils literal"><span class="pre">logging.config</span></tt>, for configuration functionality.)</p> <p>Logged messages are formatted for presentation through instances of the <a class="reference internal" href="#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="#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 <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt> 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="#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="module-level-functions"> <h2>15.7.4. Module-Level Functions<a class="headerlink" href="#module-level-functions" title="Permalink to this headline">¶</a></h2> <p>In addition to the classes described above, there are a number of module- level functions.</p> <dl class="function"> <dt id="logging.getLogger"> <tt class="descclassname">logging.</tt><tt class="descname">getLogger</tt><big>(</big><span class="optional">[</span><em>name</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.getLogger" title="Permalink to this definition">¶</a></dt> <dd><p>Return a logger with the specified name or, if no name is specified, return a logger which is the root logger of the hierarchy. If specified, the name is typically a dot-separated hierarchical name like <em>“a”</em>, <em>“a.b”</em> or <em>“a.b.c.d”</em>. Choice of these names is entirely up to the developer who is using logging.</p> <p>All calls to this function with a given name return the same logger instance. This means that logger instances never need to be passed between different parts of an application.</p> </dd></dl> <dl class="function"> <dt id="logging.getLoggerClass"> <tt class="descclassname">logging.</tt><tt class="descname">getLoggerClass</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.getLoggerClass" title="Permalink to this definition">¶</a></dt> <dd><p>Return either the standard <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt> class, or the last class passed to <a class="reference internal" href="#logging.setLoggerClass" title="logging.setLoggerClass"><tt class="xref py py-func docutils literal"><span class="pre">setLoggerClass()</span></tt></a>. This function may be called from within a new class definition, to ensure that installing a customised <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt> class will not undo customisations already applied by other code. For example:</p> <div class="highlight-python"><pre>class MyLogger(logging.getLoggerClass()): # ... override behaviour here</pre> </div> </dd></dl> <dl class="function"> <dt id="logging.debug"> <tt class="descclassname">logging.</tt><tt class="descname">debug</tt><big>(</big><em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.debug" title="Permalink to this definition">¶</a></dt> <dd><p>Logs a message with level <tt class="xref py py-const docutils literal"><span class="pre">DEBUG</span></tt> on the root logger. The <em>msg</em> is the message format string, and the <em>args</em> are the arguments which are merged into <em>msg</em> using the string formatting operator. (Note that this means that you can use keywords in the format string, together with a single dictionary argument.)</p> <p>There are two keyword arguments in <em>kwargs</em> which are inspected: <em>exc_info</em> which, if it does not evaluate as false, causes exception information to be added to the logging message. If an exception tuple (in the format returned by <a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><tt class="xref py py-func docutils literal"><span class="pre">sys.exc_info()</span></tt></a>) is provided, it is used; otherwise, <a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><tt class="xref py py-func docutils literal"><span class="pre">sys.exc_info()</span></tt></a> is called to get the exception information.</p> <p>The other optional keyword argument is <em>extra</em> which can be used to pass a dictionary which is used to populate the __dict__ of the LogRecord created for the logging event with user-defined attributes. These custom attributes can then be used as you like. For example, they could be incorporated into logged messages. For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">FORMAT</span> <span class="o">=</span> <span class="s">"</span><span class="si">%(asctime)-15s</span><span class="s"> </span><span class="si">%(clientip)s</span><span class="s"> </span><span class="si">%(user)-8s</span><span class="s"> </span><span class="si">%(message)s</span><span class="s">"</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="n">FORMAT</span><span class="p">)</span> <span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s">'clientip'</span><span class="p">:</span> <span class="s">'192.168.0.1'</span><span class="p">,</span> <span class="s">'user'</span><span class="p">:</span> <span class="s">'fbloggs'</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">"Protocol problem: </span><span class="si">%s</span><span class="s">"</span><span class="p">,</span> <span class="s">"connection reset"</span><span class="p">,</span> <span class="n">extra</span><span class="o">=</span><span class="n">d</span><span class="p">)</span> </pre></div> </div> <p>would print something like</p> <div class="highlight-python"><pre>2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset</pre> </div> <p>The keys in the dictionary passed in <em>extra</em> should not clash with the keys used by the logging system. (See the <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> documentation for more information on which keys are used by the logging system.)</p> <p>If you choose to use these attributes in logged messages, you need to exercise some care. In the above example, for instance, the <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> has been set up with a format string which expects ‘clientip’ and ‘user’ in the attribute dictionary of the LogRecord. If these are missing, the message will not be logged because a string formatting exception will occur. So in this case, you always need to pass the <em>extra</em> dictionary with these keys.</p> <p>While this might be annoying, this feature is intended for use in specialized circumstances, such as multi-threaded servers where the same code executes in many contexts, and interesting conditions which arise are dependent on this context (such as remote client IP address and authenticated user name, in the above example). In such circumstances, it is likely that specialized <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a>s would be used with particular <tt class="xref py py-class docutils literal"><span class="pre">Handler</span></tt>s.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.5: </span><em>extra</em> was added.</p> </dd></dl> <dl class="function"> <dt id="logging.info"> <tt class="descclassname">logging.</tt><tt class="descname">info</tt><big>(</big><em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.info" title="Permalink to this definition">¶</a></dt> <dd><p>Logs a message with level <tt class="xref py py-const docutils literal"><span class="pre">INFO</span></tt> on the root logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><tt class="xref py py-func docutils literal"><span class="pre">debug()</span></tt></a>.</p> </dd></dl> <dl class="function"> <dt id="logging.warning"> <tt class="descclassname">logging.</tt><tt class="descname">warning</tt><big>(</big><em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.warning" title="Permalink to this definition">¶</a></dt> <dd><p>Logs a message with level <tt class="xref py py-const docutils literal"><span class="pre">WARNING</span></tt> on the root logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><tt class="xref py py-func docutils literal"><span class="pre">debug()</span></tt></a>.</p> </dd></dl> <dl class="function"> <dt id="logging.error"> <tt class="descclassname">logging.</tt><tt class="descname">error</tt><big>(</big><em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.error" title="Permalink to this definition">¶</a></dt> <dd><p>Logs a message with level <tt class="xref py py-const docutils literal"><span class="pre">ERROR</span></tt> on the root logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><tt class="xref py py-func docutils literal"><span class="pre">debug()</span></tt></a>.</p> </dd></dl> <dl class="function"> <dt id="logging.critical"> <tt class="descclassname">logging.</tt><tt class="descname">critical</tt><big>(</big><em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.critical" title="Permalink to this definition">¶</a></dt> <dd><p>Logs a message with level <tt class="xref py py-const docutils literal"><span class="pre">CRITICAL</span></tt> on the root logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><tt class="xref py py-func docutils literal"><span class="pre">debug()</span></tt></a>.</p> </dd></dl> <dl class="function"> <dt id="logging.exception"> <tt class="descclassname">logging.</tt><tt class="descname">exception</tt><big>(</big><em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.exception" title="Permalink to this definition">¶</a></dt> <dd><p>Logs a message with level <tt class="xref py py-const docutils literal"><span class="pre">ERROR</span></tt> on the root logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><tt class="xref py py-func docutils literal"><span class="pre">debug()</span></tt></a>. Exception info is added to the logging message. This function should only be called from an exception handler.</p> </dd></dl> <dl class="function"> <dt id="logging.log"> <tt class="descclassname">logging.</tt><tt class="descname">log</tt><big>(</big><em>level</em>, <em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.log" title="Permalink to this definition">¶</a></dt> <dd><p>Logs a message with level <em>level</em> on the root logger. The other arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><tt class="xref py py-func docutils literal"><span class="pre">debug()</span></tt></a>.</p> </dd></dl> <dl class="function"> <dt id="logging.disable"> <tt class="descclassname">logging.</tt><tt class="descname">disable</tt><big>(</big><em>lvl</em><big>)</big><a class="headerlink" href="#logging.disable" title="Permalink to this definition">¶</a></dt> <dd><p>Provides an overriding level <em>lvl</em> for all loggers which takes precedence over the logger’s own level. When the need arises to temporarily throttle logging output down across the whole application, this function can be useful. Its effect is to disable all logging calls of severity <em>lvl</em> and below, so that if you call it with a value of INFO, then all INFO and DEBUG events would be discarded, whereas those of severity WARNING and above would be processed according to the logger’s effective level.</p> </dd></dl> <dl class="function"> <dt id="logging.addLevelName"> <tt class="descclassname">logging.</tt><tt class="descname">addLevelName</tt><big>(</big><em>lvl</em>, <em>levelName</em><big>)</big><a class="headerlink" href="#logging.addLevelName" title="Permalink to this definition">¶</a></dt> <dd><p>Associates level <em>lvl</em> with text <em>levelName</em> in an internal dictionary, which is used to map numeric levels to a textual representation, for example when a <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> formats a message. This function can also be used to define your own levels. The only constraints are that all levels used must be registered using this function, levels should be positive integers and they should increase in increasing order of severity.</p> </dd></dl> <dl class="function"> <dt id="logging.getLevelName"> <tt class="descclassname">logging.</tt><tt class="descname">getLevelName</tt><big>(</big><em>lvl</em><big>)</big><a class="headerlink" href="#logging.getLevelName" title="Permalink to this definition">¶</a></dt> <dd><p>Returns the textual representation of logging level <em>lvl</em>. If the level is one of the predefined levels <tt class="xref py py-const docutils literal"><span class="pre">CRITICAL</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">ERROR</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">WARNING</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">INFO</span></tt> or <tt class="xref py py-const docutils literal"><span class="pre">DEBUG</span></tt> then you get the corresponding string. If you have associated levels with names using <a class="reference internal" href="#logging.addLevelName" title="logging.addLevelName"><tt class="xref py py-func docutils literal"><span class="pre">addLevelName()</span></tt></a> then the name you have associated with <em>lvl</em> is returned. If a numeric value corresponding to one of the defined levels is passed in, the corresponding string representation is returned. Otherwise, the string “Level %s” % lvl is returned.</p> </dd></dl> <dl class="function"> <dt id="logging.makeLogRecord"> <tt class="descclassname">logging.</tt><tt class="descname">makeLogRecord</tt><big>(</big><em>attrdict</em><big>)</big><a class="headerlink" href="#logging.makeLogRecord" title="Permalink to this definition">¶</a></dt> <dd><p>Creates and returns a new <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> instance whose attributes are defined by <em>attrdict</em>. This function is useful for taking a pickled <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> attribute dictionary, sent over a socket, and reconstituting it as a <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> instance at the receiving end.</p> </dd></dl> <dl class="function"> <dt id="logging.basicConfig"> <tt class="descclassname">logging.</tt><tt class="descname">basicConfig</tt><big>(</big><span class="optional">[</span><em>**kwargs</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.basicConfig" title="Permalink to this definition">¶</a></dt> <dd><p>Does basic configuration for the logging system by creating a <a class="reference internal" href="#logging.StreamHandler" title="logging.StreamHandler"><tt class="xref py py-class docutils literal"><span class="pre">StreamHandler</span></tt></a> with a default <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> and adding it to the root logger. The functions <a class="reference internal" href="#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="#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="#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="#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="#logging.critical" title="logging.critical"><tt class="xref py py-func docutils literal"><span class="pre">critical()</span></tt></a> will call <a class="reference internal" href="#logging.basicConfig" title="logging.basicConfig"><tt class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></tt></a> automatically if no handlers are defined for the root logger.</p> <p>This function does nothing if the root logger already has handlers configured for it.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.4: </span>Formerly, <a class="reference internal" href="#logging.basicConfig" title="logging.basicConfig"><tt class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></tt></a> did not take any keyword arguments.</p> <p>The following keyword arguments are supported.</p> <table border="1" class="docutils"> <colgroup> <col width="24%" /> <col width="76%" /> </colgroup> <thead valign="bottom"> <tr><th class="head">Format</th> <th class="head">Description</th> </tr> </thead> <tbody valign="top"> <tr><td><tt class="docutils literal"><span class="pre">filename</span></tt></td> <td>Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler.</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">filemode</span></tt></td> <td>Specifies the mode to open the file, if filename is specified (if filemode is unspecified, it defaults to ‘a’).</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">format</span></tt></td> <td>Use the specified format string for the handler.</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">datefmt</span></tt></td> <td>Use the specified date/time format.</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">level</span></tt></td> <td>Set the root logger level to the specified level.</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">stream</span></tt></td> <td>Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with ‘filename’ - if both are present, ‘stream’ is ignored.</td> </tr> </tbody> </table> </dd></dl> <dl class="function"> <dt id="logging.shutdown"> <tt class="descclassname">logging.</tt><tt class="descname">shutdown</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.shutdown" title="Permalink to this definition">¶</a></dt> <dd><p>Informs the logging system to perform an orderly shutdown by flushing and closing all handlers. This should be called at application exit and no further use of the logging system should be made after this call.</p> </dd></dl> <dl class="function"> <dt id="logging.setLoggerClass"> <tt class="descclassname">logging.</tt><tt class="descname">setLoggerClass</tt><big>(</big><em>klass</em><big>)</big><a class="headerlink" href="#logging.setLoggerClass" title="Permalink to this definition">¶</a></dt> <dd><p>Tells the logging system to use the class <em>klass</em> when instantiating a logger. The class should define <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> such that only a name argument is required, and the <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> should call <tt class="xref py py-meth docutils literal"><span class="pre">Logger.__init__()</span></tt>. This function is typically called before any loggers are instantiated by applications which need to use custom logger behavior.</p> </dd></dl> <div class="admonition-see-also admonition seealso"> <p class="first admonition-title">See also</p> <dl class="last docutils"> <dt><span class="target" id="index-1"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0282"><strong>PEP 282</strong></a> - A Logging System</dt> <dd>The proposal which described this feature for inclusion in the Python standard library.</dd> <dt><a class="reference external" href="http://www.red-dove.com/python_logging.html">Original Python logging package</a></dt> <dd>This is the original source for the <a class="reference internal" href="#module-logging" title="Flexible error logging system for applications."><tt class="xref py py-mod docutils literal"><span class="pre">logging</span></tt></a> package. The version of the package available from this site is suitable for use with Python 1.5.2, 2.1.x and 2.2.x, which do not include the <a class="reference internal" href="#module-logging" title="Flexible error logging system for applications."><tt class="xref py py-mod docutils literal"><span class="pre">logging</span></tt></a> package in the standard library.</dd> </dl> </div> </div> <div class="section" id="logger-objects"> <span id="logger"></span><h2>15.7.5. Logger Objects<a class="headerlink" href="#logger-objects" title="Permalink to this headline">¶</a></h2> <p>Loggers have the following attributes and methods. Note that Loggers are never instantiated directly, but always through the module-level function <tt class="docutils literal"><span class="pre">logging.getLogger(name)</span></tt>.</p> <dl class="attribute"> <dt id="logging.Logger.propagate"> <tt class="descclassname">Logger.</tt><tt class="descname">propagate</tt><a class="headerlink" href="#logging.Logger.propagate" title="Permalink to this definition">¶</a></dt> <dd><p>If this evaluates to false, logging messages are not passed by this logger or by its child loggers to the handlers of higher level (ancestor) loggers. The constructor sets this attribute to 1.</p> </dd></dl> <dl class="method"> <dt id="logging.Logger.setLevel"> <tt class="descclassname">Logger.</tt><tt class="descname">setLevel</tt><big>(</big><em>lvl</em><big>)</big><a class="headerlink" href="#logging.Logger.setLevel" title="Permalink to this definition">¶</a></dt> <dd><p>Sets the threshold for this logger to <em>lvl</em>. Logging messages which are less severe than <em>lvl</em> will be ignored. When a logger is created, the level is set to <tt class="xref py py-const docutils literal"><span class="pre">NOTSET</span></tt> (which causes all messages to be processed when the logger is the root logger, or delegation to the parent when the logger is a non-root logger). Note that the root logger is created with level <tt class="xref py py-const docutils literal"><span class="pre">WARNING</span></tt>.</p> <p>The term “delegation to the parent” means that if a logger has a level of NOTSET, its chain of ancestor loggers is traversed until either an ancestor with a level other than NOTSET is found, or the root is reached.</p> <p>If an ancestor is found with a level other than NOTSET, then that ancestor’s level is treated as the effective level of the logger where the ancestor search began, and is used to determine how a logging event is handled.</p> <p>If the root is reached, and it has a level of NOTSET, then all messages will be processed. Otherwise, the root’s level will be used as the effective level.</p> </dd></dl> <dl class="method"> <dt id="logging.Logger.isEnabledFor"> <tt class="descclassname">Logger.</tt><tt class="descname">isEnabledFor</tt><big>(</big><em>lvl</em><big>)</big><a class="headerlink" href="#logging.Logger.isEnabledFor" title="Permalink to this definition">¶</a></dt> <dd><p>Indicates if a message of severity <em>lvl</em> would be processed by this logger. This method checks first the module-level level set by <tt class="docutils literal"><span class="pre">logging.disable(lvl)</span></tt> and then the logger’s effective level as determined by <a class="reference internal" href="#logging.Logger.getEffectiveLevel" title="logging.Logger.getEffectiveLevel"><tt class="xref py py-meth docutils literal"><span class="pre">getEffectiveLevel()</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="logging.Logger.getEffectiveLevel"> <tt class="descclassname">Logger.</tt><tt class="descname">getEffectiveLevel</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.Logger.getEffectiveLevel" title="Permalink to this definition">¶</a></dt> <dd><p>Indicates the effective level for this logger. If a value other than <tt class="xref py py-const docutils literal"><span class="pre">NOTSET</span></tt> has been set using <a class="reference internal" href="#logging.Logger.setLevel" title="logging.Logger.setLevel"><tt class="xref py py-meth docutils literal"><span class="pre">setLevel()</span></tt></a>, it is returned. Otherwise, the hierarchy is traversed towards the root until a value other than <tt class="xref py py-const docutils literal"><span class="pre">NOTSET</span></tt> is found, and that value is returned.</p> </dd></dl> <dl class="method"> <dt id="logging.Logger.getChild"> <tt class="descclassname">Logger.</tt><tt class="descname">getChild</tt><big>(</big><em>suffix</em><big>)</big><a class="headerlink" href="#logging.Logger.getChild" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a logger which is a descendant to this logger, as determined by the suffix. Thus, <tt class="docutils literal"><span class="pre">logging.getLogger('abc').getChild('def.ghi')</span></tt> would return the same logger as would be returned by <tt class="docutils literal"><span class="pre">logging.getLogger('abc.def.ghi')</span></tt>. This is a convenience method, useful when the parent logger is named using e.g. <tt class="docutils literal"><span class="pre">__name__</span></tt> rather than a literal string.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.7.</span></p> </dd></dl> <dl class="method"> <dt id="logging.Logger.debug"> <tt class="descclassname">Logger.</tt><tt class="descname">debug</tt><big>(</big><em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.Logger.debug" title="Permalink to this definition">¶</a></dt> <dd><p>Logs a message with level <tt class="xref py py-const docutils literal"><span class="pre">DEBUG</span></tt> on this logger. The <em>msg</em> is the message format string, and the <em>args</em> are the arguments which are merged into <em>msg</em> using the string formatting operator. (Note that this means that you can use keywords in the format string, together with a single dictionary argument.)</p> <p>There are two keyword arguments in <em>kwargs</em> which are inspected: <em>exc_info</em> which, if it does not evaluate as false, causes exception information to be added to the logging message. If an exception tuple (in the format returned by <a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><tt class="xref py py-func docutils literal"><span class="pre">sys.exc_info()</span></tt></a>) is provided, it is used; otherwise, <a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><tt class="xref py py-func docutils literal"><span class="pre">sys.exc_info()</span></tt></a> is called to get the exception information.</p> <p>The other optional keyword argument is <em>extra</em> which can be used to pass a dictionary which is used to populate the __dict__ of the LogRecord created for the logging event with user-defined attributes. These custom attributes can then be used as you like. For example, they could be incorporated into logged messages. For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">FORMAT</span> <span class="o">=</span> <span class="s">"</span><span class="si">%(asctime)-15s</span><span class="s"> </span><span class="si">%(clientip)s</span><span class="s"> </span><span class="si">%(user)-8s</span><span class="s"> </span><span class="si">%(message)s</span><span class="s">"</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="n">FORMAT</span><span class="p">)</span> <span class="n">d</span> <span class="o">=</span> <span class="p">{</span> <span class="s">'clientip'</span> <span class="p">:</span> <span class="s">'192.168.0.1'</span><span class="p">,</span> <span class="s">'user'</span> <span class="p">:</span> <span class="s">'fbloggs'</span> <span class="p">}</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">"tcpserver"</span><span class="p">)</span> <span class="n">logger</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s">"Protocol problem: </span><span class="si">%s</span><span class="s">"</span><span class="p">,</span> <span class="s">"connection reset"</span><span class="p">,</span> <span class="n">extra</span><span class="o">=</span><span class="n">d</span><span class="p">)</span> </pre></div> </div> <p>would print something like</p> <div class="highlight-python"><pre>2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset</pre> </div> <p>The keys in the dictionary passed in <em>extra</em> should not clash with the keys used by the logging system. (See the <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> documentation for more information on which keys are used by the logging system.)</p> <p>If you choose to use these attributes in logged messages, you need to exercise some care. In the above example, for instance, the <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> has been set up with a format string which expects ‘clientip’ and ‘user’ in the attribute dictionary of the LogRecord. If these are missing, the message will not be logged because a string formatting exception will occur. So in this case, you always need to pass the <em>extra</em> dictionary with these keys.</p> <p>While this might be annoying, this feature is intended for use in specialized circumstances, such as multi-threaded servers where the same code executes in many contexts, and interesting conditions which arise are dependent on this context (such as remote client IP address and authenticated user name, in the above example). In such circumstances, it is likely that specialized <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a>s would be used with particular <tt class="xref py py-class docutils literal"><span class="pre">Handler</span></tt>s.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.5: </span><em>extra</em> was added.</p> </dd></dl> <dl class="method"> <dt id="logging.Logger.info"> <tt class="descclassname">Logger.</tt><tt class="descname">info</tt><big>(</big><em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.Logger.info" title="Permalink to this definition">¶</a></dt> <dd><p>Logs a message with level <tt class="xref py py-const docutils literal"><span class="pre">INFO</span></tt> on this logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><tt class="xref py py-meth docutils literal"><span class="pre">debug()</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="logging.Logger.warning"> <tt class="descclassname">Logger.</tt><tt class="descname">warning</tt><big>(</big><em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.Logger.warning" title="Permalink to this definition">¶</a></dt> <dd><p>Logs a message with level <tt class="xref py py-const docutils literal"><span class="pre">WARNING</span></tt> on this logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><tt class="xref py py-meth docutils literal"><span class="pre">debug()</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="logging.Logger.error"> <tt class="descclassname">Logger.</tt><tt class="descname">error</tt><big>(</big><em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.Logger.error" title="Permalink to this definition">¶</a></dt> <dd><p>Logs a message with level <tt class="xref py py-const docutils literal"><span class="pre">ERROR</span></tt> on this logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><tt class="xref py py-meth docutils literal"><span class="pre">debug()</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="logging.Logger.critical"> <tt class="descclassname">Logger.</tt><tt class="descname">critical</tt><big>(</big><em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.Logger.critical" title="Permalink to this definition">¶</a></dt> <dd><p>Logs a message with level <tt class="xref py py-const docutils literal"><span class="pre">CRITICAL</span></tt> on this logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><tt class="xref py py-meth docutils literal"><span class="pre">debug()</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="logging.Logger.log"> <tt class="descclassname">Logger.</tt><tt class="descname">log</tt><big>(</big><em>lvl</em>, <em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.Logger.log" title="Permalink to this definition">¶</a></dt> <dd><p>Logs a message with integer level <em>lvl</em> on this logger. The other arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><tt class="xref py py-meth docutils literal"><span class="pre">debug()</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="logging.Logger.exception"> <tt class="descclassname">Logger.</tt><tt class="descname">exception</tt><big>(</big><em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.Logger.exception" title="Permalink to this definition">¶</a></dt> <dd><p>Logs a message with level <tt class="xref py py-const docutils literal"><span class="pre">ERROR</span></tt> on this logger. The arguments are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><tt class="xref py py-meth docutils literal"><span class="pre">debug()</span></tt></a>. Exception info is added to the logging message. This method should only be called from an exception handler.</p> </dd></dl> <dl class="method"> <dt id="logging.Logger.addFilter"> <tt class="descclassname">Logger.</tt><tt class="descname">addFilter</tt><big>(</big><em>filt</em><big>)</big><a class="headerlink" href="#logging.Logger.addFilter" title="Permalink to this definition">¶</a></dt> <dd><p>Adds the specified filter <em>filt</em> to this logger.</p> </dd></dl> <dl class="method"> <dt id="logging.Logger.removeFilter"> <tt class="descclassname">Logger.</tt><tt class="descname">removeFilter</tt><big>(</big><em>filt</em><big>)</big><a class="headerlink" href="#logging.Logger.removeFilter" title="Permalink to this definition">¶</a></dt> <dd><p>Removes the specified filter <em>filt</em> from this logger.</p> </dd></dl> <dl class="method"> <dt id="logging.Logger.filter"> <tt class="descclassname">Logger.</tt><tt class="descname">filter</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.Logger.filter" title="Permalink to this definition">¶</a></dt> <dd><p>Applies this logger’s filters to the record and returns a true value if the record is to be processed.</p> </dd></dl> <dl class="method"> <dt id="logging.Logger.addHandler"> <tt class="descclassname">Logger.</tt><tt class="descname">addHandler</tt><big>(</big><em>hdlr</em><big>)</big><a class="headerlink" href="#logging.Logger.addHandler" title="Permalink to this definition">¶</a></dt> <dd><p>Adds the specified handler <em>hdlr</em> to this logger.</p> </dd></dl> <dl class="method"> <dt id="logging.Logger.removeHandler"> <tt class="descclassname">Logger.</tt><tt class="descname">removeHandler</tt><big>(</big><em>hdlr</em><big>)</big><a class="headerlink" href="#logging.Logger.removeHandler" title="Permalink to this definition">¶</a></dt> <dd><p>Removes the specified handler <em>hdlr</em> from this logger.</p> </dd></dl> <dl class="method"> <dt id="logging.Logger.findCaller"> <tt class="descclassname">Logger.</tt><tt class="descname">findCaller</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.Logger.findCaller" title="Permalink to this definition">¶</a></dt> <dd><p>Finds the caller’s source filename and line number. Returns the filename, line number and function name as a 3-element tuple.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.4: </span>The function name was added. In earlier versions, the filename and line number were returned as a 2-element tuple..</p> </dd></dl> <dl class="method"> <dt id="logging.Logger.handle"> <tt class="descclassname">Logger.</tt><tt class="descname">handle</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.Logger.handle" title="Permalink to this definition">¶</a></dt> <dd><p>Handles a record by passing it to all handlers associated with this logger and its ancestors (until a false value of <em>propagate</em> is found). This method is used for unpickled records received from a socket, as well as those created locally. Logger-level filtering is applied using <a class="reference internal" href="#logging.Logger.filter" title="logging.Logger.filter"><tt class="xref py py-meth docutils literal"><span class="pre">filter()</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="logging.Logger.makeRecord"> <tt class="descclassname">Logger.</tt><tt class="descname">makeRecord</tt><big>(</big><em>name</em>, <em>lvl</em>, <em>fn</em>, <em>lno</em>, <em>msg</em>, <em>args</em>, <em>exc_info</em><span class="optional">[</span>, <em>func</em>, <em>extra</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.Logger.makeRecord" title="Permalink to this definition">¶</a></dt> <dd><p>This is a factory method which can be overridden in subclasses to create specialized <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> instances.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.5: </span><em>func</em> and <em>extra</em> were added.</p> </dd></dl> </div> <div class="section" id="basic-example"> <span id="minimal-example"></span><h2>15.7.6. Basic example<a class="headerlink" href="#basic-example" title="Permalink to this headline">¶</a></h2> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.4: </span>formerly <a class="reference internal" href="#logging.basicConfig" title="logging.basicConfig"><tt class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></tt></a> did not take any keyword arguments.</p> <p>The <a class="reference internal" href="#module-logging" title="Flexible error logging system for applications."><tt class="xref py py-mod docutils literal"><span class="pre">logging</span></tt></a> package provides a lot of flexibility, and its configuration can appear daunting. This section demonstrates that simple use of the logging package is possible.</p> <p>The simplest example shows logging to the console:</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">debug</span><span class="p">(</span><span class="s">'A debug message'</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">'Some information'</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">'A shot across the bows'</span><span class="p">)</span> </pre></div> </div> <p>If you run the above script, you’ll see this:</p> <div class="highlight-python"><pre>WARNING:root:A shot across the bows</pre> </div> <p>Because no particular logger was specified, the system used the root logger. The debug and info messages didn’t appear because by default, the root logger is configured to only handle messages with a severity of WARNING or above. The message format is also a configuration default, as is the output destination of the messages - <tt class="docutils literal"><span class="pre">sys.stderr</span></tt>. The severity level, the message format and destination can be easily changed, as shown in the example below:</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">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">format</span><span class="o">=</span><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><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">filemode</span><span class="o">=</span><span class="s">'w'</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">'A debug message'</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">'Some information'</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">'A shot across the bows'</span><span class="p">)</span> </pre></div> </div> <p>The <a class="reference internal" href="#logging.basicConfig" title="logging.basicConfig"><tt class="xref py py-meth docutils literal"><span class="pre">basicConfig()</span></tt></a> method is used to change the configuration defaults, which results in output (written to <tt class="docutils literal"><span class="pre">myapp.log</span></tt>) which should look something like the following:</p> <div class="highlight-python"><pre>2004-07-02 13:00:08,743 DEBUG A debug message 2004-07-02 13:00:08,743 INFO Some information 2004-07-02 13:00:08,743 WARNING A shot across the bows</pre> </div> <p>This time, all messages with a severity of DEBUG or above were handled, and the format of the messages was also changed, and output went to the specified file rather than the console.</p> <p>Formatting uses standard Python string formatting - see section <a class="reference internal" href="stdtypes.html#string-formatting"><em>String Formatting Operations</em></a>. The format string takes the following common specifiers. For a complete list of specifiers, consult the <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> documentation.</p> <table border="1" class="docutils"> <colgroup> <col width="29%" /> <col width="71%" /> </colgroup> <thead valign="bottom"> <tr><th class="head">Format</th> <th class="head">Description</th> </tr> </thead> <tbody valign="top"> <tr><td><tt class="docutils literal"><span class="pre">%(name)s</span></tt></td> <td>Name of the logger (logging channel).</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">%(levelname)s</span></tt></td> <td>Text logging level for the message (<tt class="docutils literal"><span class="pre">'DEBUG'</span></tt>, <tt class="docutils literal"><span class="pre">'INFO'</span></tt>, <tt class="docutils literal"><span class="pre">'WARNING'</span></tt>, <tt class="docutils literal"><span class="pre">'ERROR'</span></tt>, <tt class="docutils literal"><span class="pre">'CRITICAL'</span></tt>).</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">%(asctime)s</span></tt></td> <td>Human-readable time when the <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> was created. By default this is of the form “2003-07-08 16:49:45,896” (the numbers after the comma are millisecond portion of the time).</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">%(message)s</span></tt></td> <td>The logged message.</td> </tr> </tbody> </table> <p>To change the date/time format, you can pass an additional keyword parameter, <em>datefmt</em>, as in the following:</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">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">format</span><span class="o">=</span><span class="s">'</span><span class="si">%(asctime)s</span><span class="s"> </span><span class="si">%(levelname)-8s</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">'%a, </span><span class="si">%d</span><span class="s"> %b %Y %H:%M:%S'</span><span class="p">,</span> <span class="n">filename</span><span class="o">=</span><span class="s">'/temp/myapp.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">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">'A debug message'</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">'Some information'</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">'A shot across the bows'</span><span class="p">)</span> </pre></div> </div> <p>which would result in output like</p> <div class="highlight-python"><pre>Fri, 02 Jul 2004 13:06:18 DEBUG A debug message Fri, 02 Jul 2004 13:06:18 INFO Some information Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows</pre> </div> <p>The date format string follows the requirements of <tt class="xref py py-func docutils literal"><span class="pre">strftime()</span></tt> - see the documentation for the <a class="reference internal" href="time.html#module-time" title="Time access and conversions."><tt class="xref py py-mod docutils literal"><span class="pre">time</span></tt></a> module.</p> <p>If, instead of sending logging output to the console or a file, you’d rather use a file-like object which you have created separately, you can pass it to <a class="reference internal" href="#logging.basicConfig" title="logging.basicConfig"><tt class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></tt></a> using the <em>stream</em> keyword argument. Note that if both <em>stream</em> and <em>filename</em> keyword arguments are passed, the <em>stream</em> argument is ignored.</p> <p>Of course, you can put variable information in your output. To do this, simply have the message be a format string and pass in additional arguments containing the variable information, as in the following 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">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">format</span><span class="o">=</span><span class="s">'</span><span class="si">%(asctime)s</span><span class="s"> </span><span class="si">%(levelname)-8s</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">'%a, </span><span class="si">%d</span><span class="s"> %b %Y %H:%M:%S'</span><span class="p">,</span> <span class="n">filename</span><span class="o">=</span><span class="s">'/temp/myapp.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">logging</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s">'Pack my box with </span><span class="si">%d</span><span class="s"> dozen </span><span class="si">%s</span><span class="s">'</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="s">'liquor jugs'</span><span class="p">)</span> </pre></div> </div> <p>which would result in</p> <div class="highlight-python"><pre>Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs</pre> </div> </div> <div class="section" id="logging-to-multiple-destinations"> <span id="multiple-destinations"></span><h2>15.7.7. Logging to multiple destinations<a class="headerlink" href="#logging-to-multiple-destinations" title="Permalink to this headline">¶</a></h2> <p>Let’s say you want to log to console and file with different message formats and in differing circumstances. Say you want to log messages with levels of DEBUG and higher to file, and those messages at level INFO and higher to the console. Let’s also assume that the file should contain timestamps, but the console messages should not. Here’s how you can achieve this:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span> <span class="c"># set up logging to file - see previous section for more details</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">logging</span><span class="o">.</span><span class="n">DEBUG</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">%(name)-12s</span><span class="s"> </span><span class="si">%(levelname)-8s</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"> %H:%M'</span><span class="p">,</span> <span class="n">filename</span><span class="o">=</span><span class="s">'/temp/myapp.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="c"># define a Handler which writes INFO messages or higher to the sys.stderr</span> <span class="n">console</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">console</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">INFO</span><span class="p">)</span> <span class="c"># set a format which is simpler for console use</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">%(name)-12s</span><span class="s">: </span><span class="si">%(levelname)-8s</span><span class="s"> </span><span class="si">%(message)s</span><span class="s">'</span><span class="p">)</span> <span class="c"># tell the handler to use this format</span> <span class="n">console</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 the handler to the root logger</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">''</span><span class="p">)</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">console</span><span class="p">)</span> <span class="c"># Now, we can log to the root logger, or any other logger. First the root...</span> <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">'Jackdaws love my big sphinx of quartz.'</span><span class="p">)</span> <span class="c"># Now, define a couple of other loggers which might represent areas in your</span> <span class="c"># application:</span> <span class="n">logger1</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">'myapp.area1'</span><span class="p">)</span> <span class="n">logger2</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">'myapp.area2'</span><span class="p">)</span> <span class="n">logger1</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">'Quick zephyrs blow, vexing daft Jim.'</span><span class="p">)</span> <span class="n">logger1</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">'How quickly daft jumping zebras vex.'</span><span class="p">)</span> <span class="n">logger2</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s">'Jail zesty vixen who grabbed pay from quack.'</span><span class="p">)</span> <span class="n">logger2</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s">'The five boxing wizards jump quickly.'</span><span class="p">)</span> </pre></div> </div> <p>When you run this, on the console you will see</p> <div class="highlight-python"><pre>root : INFO Jackdaws love my big sphinx of quartz. myapp.area1 : INFO How quickly daft jumping zebras vex. myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack. myapp.area2 : ERROR The five boxing wizards jump quickly.</pre> </div> <p>and in the file you will see something like</p> <div class="highlight-python"><pre>10-22 22:19 root INFO Jackdaws love my big sphinx of quartz. 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim. 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex. 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack. 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.</pre> </div> <p>As you can see, the DEBUG message only shows up in the file. The other messages are sent to both destinations.</p> <p>This example uses console and file handlers, but you can use any number and combination of handlers you choose.</p> </div> <div class="section" id="exceptions-raised-during-logging"> <span id="logging-exceptions"></span><h2>15.7.8. 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="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> <p><strong>Note:</strong> The default value of <tt class="xref py py-data docutils literal"><span class="pre">raiseExceptions</span></tt> is <tt class="xref 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="xref docutils literal"><span class="pre">False</span></tt> for production usage.</p> </div> <div class="section" id="adding-contextual-information-to-your-logging-output"> <span id="context-info"></span><h2>15.7.9. Adding contextual information to your logging output<a class="headerlink" href="#adding-contextual-information-to-your-logging-output" title="Permalink to this headline">¶</a></h2> <p>Sometimes you want logging output to contain contextual information in addition to the parameters passed to the logging call. For example, in a networked application, it may be desirable to log client-specific information in the log (e.g. remote client’s username, or IP address). Although you could use the <em>extra</em> parameter to achieve this, it’s not always convenient to pass the information in this way. While it might be tempting to create <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt> instances on a per-connection basis, this is not a good idea because these instances are not garbage collected. While this is not a problem in practice, when the number of <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt> instances is dependent on the level of granularity you want to use in logging an application, it could be hard to manage if the number of <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt> instances becomes effectively unbounded.</p> <p>An easy way in which you can pass contextual information to be output along with logging event information is to use the <a class="reference internal" href="#logging.LoggerAdapter" title="logging.LoggerAdapter"><tt class="xref py py-class docutils literal"><span class="pre">LoggerAdapter</span></tt></a> class. This class is designed to look like a <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt>, so that you can call <a class="reference internal" href="#logging.debug" title="logging.debug"><tt class="xref py py-meth docutils literal"><span class="pre">debug()</span></tt></a>, <a class="reference internal" href="#logging.info" title="logging.info"><tt class="xref py py-meth docutils literal"><span class="pre">info()</span></tt></a>, <a class="reference internal" href="#logging.warning" title="logging.warning"><tt class="xref py py-meth docutils literal"><span class="pre">warning()</span></tt></a>, <a class="reference internal" href="#logging.error" title="logging.error"><tt class="xref py py-meth docutils literal"><span class="pre">error()</span></tt></a>, <a class="reference internal" href="#logging.exception" title="logging.exception"><tt class="xref py py-meth docutils literal"><span class="pre">exception()</span></tt></a>, <a class="reference internal" href="#logging.critical" title="logging.critical"><tt class="xref py py-meth docutils literal"><span class="pre">critical()</span></tt></a> and <a class="reference internal" href="#logging.log" title="logging.log"><tt class="xref py py-meth docutils literal"><span class="pre">log()</span></tt></a>. These methods have the same signatures as their counterparts in <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt>, so you can use the two types of instances interchangeably.</p> <p>When you create an instance of <a class="reference internal" href="#logging.LoggerAdapter" title="logging.LoggerAdapter"><tt class="xref py py-class docutils literal"><span class="pre">LoggerAdapter</span></tt></a>, you pass it a <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt> instance and a dict-like object which contains your contextual information. When you call one of the logging methods on an instance of <a class="reference internal" href="#logging.LoggerAdapter" title="logging.LoggerAdapter"><tt class="xref py py-class docutils literal"><span class="pre">LoggerAdapter</span></tt></a>, it delegates the call to the underlying instance of <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt> passed to its constructor, and arranges to pass the contextual information in the delegated call. Here’s a snippet from the code of <a class="reference internal" href="#logging.LoggerAdapter" title="logging.LoggerAdapter"><tt class="xref py py-class docutils literal"><span class="pre">LoggerAdapter</span></tt></a>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">debug</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">msg</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span> <span class="sd">"""</span> <span class="sd"> Delegate a debug call to the underlying logger, after adding</span> <span class="sd"> contextual information from this adapter instance.</span> <span class="sd"> """</span> <span class="n">msg</span><span class="p">,</span> <span class="n">kwargs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">process</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="n">kwargs</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span> </pre></div> </div> <p>The <tt class="xref py py-meth docutils literal"><span class="pre">process()</span></tt> method of <a class="reference internal" href="#logging.LoggerAdapter" title="logging.LoggerAdapter"><tt class="xref py py-class docutils literal"><span class="pre">LoggerAdapter</span></tt></a> is where the contextual information is added to the logging output. It’s passed the message and keyword arguments of the logging call, and it passes back (potentially) modified versions of these to use in the call to the underlying logger. The default implementation of this method leaves the message alone, but inserts an “extra” key in the keyword argument whose value is the dict-like object passed to the constructor. Of course, if you had passed an “extra” keyword argument in the call to the adapter, it will be silently overwritten.</p> <p>The advantage of using “extra” is that the values in the dict-like object are merged into the <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> instance’s __dict__, allowing you to use customized strings with your <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> instances which know about the keys of the dict-like object. If you need a different method, e.g. if you want to prepend or append the contextual information to the message string, you just need to subclass <a class="reference internal" href="#logging.LoggerAdapter" title="logging.LoggerAdapter"><tt class="xref py py-class docutils literal"><span class="pre">LoggerAdapter</span></tt></a> and override <tt class="xref py py-meth docutils literal"><span class="pre">process()</span></tt> to do what you need. Here’s an example script which uses this class, which also illustrates what dict-like behaviour is needed from an arbitrary “dict-like” object for use in the constructor:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span> <span class="k">class</span> <span class="nc">ConnInfo</span><span class="p">:</span> <span class="sd">"""</span> <span class="sd"> An example class which shows how an arbitrary class can be used as</span> <span class="sd"> the 'extra' context information repository passed to a LoggerAdapter.</span> <span class="sd"> """</span> <span class="k">def</span> <span class="nf">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span> <span class="sd">"""</span> <span class="sd"> To allow this instance to look like a dict.</span> <span class="sd"> """</span> <span class="kn">from</span> <span class="nn">random</span> <span class="kn">import</span> <span class="n">choice</span> <span class="k">if</span> <span class="n">name</span> <span class="o">==</span> <span class="s">"ip"</span><span class="p">:</span> <span class="n">result</span> <span class="o">=</span> <span class="n">choice</span><span class="p">([</span><span class="s">"127.0.0.1"</span><span class="p">,</span> <span class="s">"192.168.0.1"</span><span class="p">])</span> <span class="k">elif</span> <span class="n">name</span> <span class="o">==</span> <span class="s">"user"</span><span class="p">:</span> <span class="n">result</span> <span class="o">=</span> <span class="n">choice</span><span class="p">([</span><span class="s">"jim"</span><span class="p">,</span> <span class="s">"fred"</span><span class="p">,</span> <span class="s">"sheila"</span><span class="p">])</span> <span class="k">else</span><span class="p">:</span> <span class="n">result</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">__dict__</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="s">"?"</span><span class="p">)</span> <span class="k">return</span> <span class="n">result</span> <span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="sd">"""</span> <span class="sd"> To allow iteration over keys, which will be merged into</span> <span class="sd"> the LogRecord dict before formatting and output.</span> <span class="sd"> """</span> <span class="n">keys</span> <span class="o">=</span> <span class="p">[</span><span class="s">"ip"</span><span class="p">,</span> <span class="s">"user"</span><span class="p">]</span> <span class="n">keys</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">__dict__</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span> <span class="k">return</span> <span class="n">keys</span><span class="o">.</span><span class="n">__iter__</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="kn">from</span> <span class="nn">random</span> <span class="kn">import</span> <span class="n">choice</span> <span class="n">levels</span> <span class="o">=</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">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">WARNING</span><span class="p">,</span> <span class="n">logging</span><span class="o">.</span><span class="n">ERROR</span><span class="p">,</span> <span class="n">logging</span><span class="o">.</span><span class="n">CRITICAL</span><span class="p">)</span> <span class="n">a1</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">LoggerAdapter</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">"a.b.c"</span><span class="p">),</span> <span class="p">{</span> <span class="s">"ip"</span> <span class="p">:</span> <span class="s">"123.231.231.123"</span><span class="p">,</span> <span class="s">"user"</span> <span class="p">:</span> <span class="s">"sheila"</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">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">,</span> <span class="n">format</span><span class="o">=</span><span class="s">"</span><span class="si">%(asctime)-15s</span><span class="s"> </span><span class="si">%(name)-5s</span><span class="s"> </span><span class="si">%(levelname)-8s</span><span class="s"> IP: </span><span class="si">%(ip)-15s</span><span class="s"> User: </span><span class="si">%(user)-8s</span><span class="s"> </span><span class="si">%(message)s</span><span class="s">"</span><span class="p">)</span> <span class="n">a1</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">"A debug message"</span><span class="p">)</span> <span class="n">a1</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">"An info message with </span><span class="si">%s</span><span class="s">"</span><span class="p">,</span> <span class="s">"some parameters"</span><span class="p">)</span> <span class="n">a2</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">LoggerAdapter</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">"d.e.f"</span><span class="p">),</span> <span class="n">ConnInfo</span><span class="p">())</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span> <span class="n">lvl</span> <span class="o">=</span> <span class="n">choice</span><span class="p">(</span><span class="n">levels</span><span class="p">)</span> <span class="n">lvlname</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLevelName</span><span class="p">(</span><span class="n">lvl</span><span class="p">)</span> <span class="n">a2</span><span class="o">.</span><span class="n">log</span><span class="p">(</span><span class="n">lvl</span><span class="p">,</span> <span class="s">"A message at </span><span class="si">%s</span><span class="s"> level with </span><span class="si">%d</span><span class="s"> </span><span class="si">%s</span><span class="s">"</span><span class="p">,</span> <span class="n">lvlname</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="s">"parameters"</span><span class="p">)</span> </pre></div> </div> <p>When this script is run, the output should look something like this:</p> <div class="highlight-python"><pre>2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters 2008-01-18 14:49:54,023 d.e.f CRITICAL IP: 192.168.0.1 User: jim A message at CRITICAL level with 2 parameters 2008-01-18 14:49:54,033 d.e.f INFO IP: 192.168.0.1 User: jim A message at INFO level with 2 parameters 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: sheila A message at WARNING level with 2 parameters 2008-01-18 14:49:54,033 d.e.f ERROR IP: 127.0.0.1 User: fred A message at ERROR level with 2 parameters 2008-01-18 14:49:54,033 d.e.f ERROR IP: 127.0.0.1 User: sheila A message at ERROR level with 2 parameters 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: sheila A message at WARNING level with 2 parameters 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: jim A message at WARNING level with 2 parameters 2008-01-18 14:49:54,033 d.e.f INFO IP: 192.168.0.1 User: fred A message at INFO level with 2 parameters 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: sheila A message at WARNING level with 2 parameters 2008-01-18 14:49:54,033 d.e.f WARNING IP: 127.0.0.1 User: jim A message at WARNING level with 2 parameters</pre> </div> <p class="versionadded"> <span class="versionmodified">New in version 2.6.</span></p> <p>The <a class="reference internal" href="#logging.LoggerAdapter" title="logging.LoggerAdapter"><tt class="xref py py-class docutils literal"><span class="pre">LoggerAdapter</span></tt></a> class was not present in previous versions.</p> </div> <div class="section" id="logging-to-a-single-file-from-multiple-processes"> <span id="multiple-processes"></span><h2>15.7.10. Logging to a single file from multiple processes<a class="headerlink" href="#logging-to-a-single-file-from-multiple-processes" title="Permalink to this headline">¶</a></h2> <p>Although logging is thread-safe, and logging to a single file from multiple threads in a single process <em>is</em> supported, logging to a single file from <em>multiple processes</em> is <em>not</em> supported, because there is no standard way to serialize access to a single file across multiple processes in Python. If you need to log to a single file from multiple processes, the best way of doing this is to have all the processes log to a <tt class="xref py py-class docutils literal"><span class="pre">SocketHandler</span></tt>, and have a separate process which implements a socket server which reads from the socket and logs to file. (If you prefer, you can dedicate one thread in one of the existing processes to perform this function.) The following section documents this approach in more detail and includes a working socket receiver which can be used as a starting point for you to adapt in your own applications.</p> <p>If you are using a recent version of Python which includes the <a class="reference internal" href="multiprocessing.html#module-multiprocessing" title="Process-based "threading" interface."><tt class="xref py py-mod docutils literal"><span class="pre">multiprocessing</span></tt></a> module, you can write your own handler which uses the <tt class="xref py py-class docutils literal"><span class="pre">Lock</span></tt> class from this module to serialize access to the file from your processes. The existing <a class="reference internal" href="#logging.FileHandler" title="logging.FileHandler"><tt class="xref py py-class docutils literal"><span class="pre">FileHandler</span></tt></a> and subclasses do not make use of <a class="reference internal" href="multiprocessing.html#module-multiprocessing" title="Process-based "threading" interface."><tt class="xref py py-mod docutils literal"><span class="pre">multiprocessing</span></tt></a> at present, though they may do so in the future. Note that at present, the <a class="reference internal" href="multiprocessing.html#module-multiprocessing" title="Process-based "threading" interface."><tt class="xref py py-mod docutils literal"><span class="pre">multiprocessing</span></tt></a> module does not provide working lock functionality on all platforms (see <a class="reference external" href="http://bugs.python.org/issue3770">http://bugs.python.org/issue3770</a>).</p> </div> <div class="section" id="sending-and-receiving-logging-events-across-a-network"> <span id="network-logging"></span><h2>15.7.11. Sending and receiving logging events across a network<a class="headerlink" href="#sending-and-receiving-logging-events-across-a-network" title="Permalink to this headline">¶</a></h2> <p>Let’s say you want to send logging events across a network, and handle them at the receiving end. A simple way of doing this is attaching a <tt class="xref py py-class docutils literal"><span class="pre">SocketHandler</span></tt> instance to the root logger at the sending end:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span><span class="o">,</span> <span class="nn">logging.handlers</span> <span class="n">rootLogger</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">''</span><span class="p">)</span> <span class="n">rootLogger</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="n">socketHandler</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">handlers</span><span class="o">.</span><span class="n">SocketHandler</span><span class="p">(</span><span class="s">'localhost'</span><span class="p">,</span> <span class="n">logging</span><span class="o">.</span><span class="n">handlers</span><span class="o">.</span><span class="n">DEFAULT_TCP_LOGGING_PORT</span><span class="p">)</span> <span class="c"># don't bother with a formatter, since a socket handler sends the event as</span> <span class="c"># an unformatted pickle</span> <span class="n">rootLogger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">socketHandler</span><span class="p">)</span> <span class="c"># Now, we can log to the root logger, or any other logger. First the root...</span> <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">'Jackdaws love my big sphinx of quartz.'</span><span class="p">)</span> <span class="c"># Now, define a couple of other loggers which might represent areas in your</span> <span class="c"># application:</span> <span class="n">logger1</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">'myapp.area1'</span><span class="p">)</span> <span class="n">logger2</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">'myapp.area2'</span><span class="p">)</span> <span class="n">logger1</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">'Quick zephyrs blow, vexing daft Jim.'</span><span class="p">)</span> <span class="n">logger1</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">'How quickly daft jumping zebras vex.'</span><span class="p">)</span> <span class="n">logger2</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s">'Jail zesty vixen who grabbed pay from quack.'</span><span class="p">)</span> <span class="n">logger2</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s">'The five boxing wizards jump quickly.'</span><span class="p">)</span> </pre></div> </div> <p>At the receiving end, you can set up a receiver using the <a class="reference internal" href="socketserver.html#module-SocketServer" title="A framework for network servers."><tt class="xref py py-mod docutils literal"><span class="pre">SocketServer</span></tt></a> module. Here is a basic working example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">cPickle</span> <span class="kn">import</span> <span class="nn">logging</span> <span class="kn">import</span> <span class="nn">logging.handlers</span> <span class="kn">import</span> <span class="nn">SocketServer</span> <span class="kn">import</span> <span class="nn">struct</span> <span class="k">class</span> <span class="nc">LogRecordStreamHandler</span><span class="p">(</span><span class="n">SocketServer</span><span class="o">.</span><span class="n">StreamRequestHandler</span><span class="p">):</span> <span class="sd">"""Handler for a streaming logging request.</span> <span class="sd"> This basically logs the record using whatever logging policy is</span> <span class="sd"> configured locally.</span> <span class="sd"> """</span> <span class="k">def</span> <span class="nf">handle</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="sd">"""</span> <span class="sd"> Handle multiple requests - each expected to be a 4-byte length,</span> <span class="sd"> followed by the LogRecord in pickle format. Logs the record</span> <span class="sd"> according to whatever policy is configured locally.</span> <span class="sd"> """</span> <span class="k">while</span> <span class="mi">1</span><span class="p">:</span> <span class="n">chunk</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">connection</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span> <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span> <span class="o"><</span> <span class="mi">4</span><span class="p">:</span> <span class="k">break</span> <span class="n">slen</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">unpack</span><span class="p">(</span><span class="s">">L"</span><span class="p">,</span> <span class="n">chunk</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span> <span class="n">chunk</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">connection</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="n">slen</span><span class="p">)</span> <span class="k">while</span> <span class="nb">len</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span> <span class="o"><</span> <span class="n">slen</span><span class="p">:</span> <span class="n">chunk</span> <span class="o">=</span> <span class="n">chunk</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">connection</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="n">slen</span> <span class="o">-</span> <span class="nb">len</span><span class="p">(</span><span class="n">chunk</span><span class="p">))</span> <span class="n">obj</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">unPickle</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span> <span class="n">record</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">makeLogRecord</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">handleLogRecord</span><span class="p">(</span><span class="n">record</span><span class="p">)</span> <span class="k">def</span> <span class="nf">unPickle</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span> <span class="k">return</span> <span class="n">cPickle</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="n">data</span><span class="p">)</span> <span class="k">def</span> <span class="nf">handleLogRecord</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">record</span><span class="p">):</span> <span class="c"># if a name is specified, we use the named logger rather than the one</span> <span class="c"># implied by the record.</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">server</span><span class="o">.</span><span class="n">logname</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span> <span class="n">name</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">server</span><span class="o">.</span><span class="n">logname</span> <span class="k">else</span><span class="p">:</span> <span class="n">name</span> <span class="o">=</span> <span class="n">record</span><span class="o">.</span><span class="n">name</span> <span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="n">name</span><span class="p">)</span> <span class="c"># N.B. EVERY record gets logged. This is because Logger.handle</span> <span class="c"># is normally called AFTER logger-level filtering. If you want</span> <span class="c"># to do filtering, do it at the client end to save wasting</span> <span class="c"># cycles and network bandwidth!</span> <span class="n">logger</span><span class="o">.</span><span class="n">handle</span><span class="p">(</span><span class="n">record</span><span class="p">)</span> <span class="k">class</span> <span class="nc">LogRecordSocketReceiver</span><span class="p">(</span><span class="n">SocketServer</span><span class="o">.</span><span class="n">ThreadingTCPServer</span><span class="p">):</span> <span class="sd">"""simple TCP socket-based logging receiver suitable for testing.</span> <span class="sd"> """</span> <span class="n">allow_reuse_address</span> <span class="o">=</span> <span class="mi">1</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">host</span><span class="o">=</span><span class="s">'localhost'</span><span class="p">,</span> <span class="n">port</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">handlers</span><span class="o">.</span><span class="n">DEFAULT_TCP_LOGGING_PORT</span><span class="p">,</span> <span class="n">handler</span><span class="o">=</span><span class="n">LogRecordStreamHandler</span><span class="p">):</span> <span class="n">SocketServer</span><span class="o">.</span><span class="n">ThreadingTCPServer</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="p">(</span><span class="n">host</span><span class="p">,</span> <span class="n">port</span><span class="p">),</span> <span class="n">handler</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">abort</span> <span class="o">=</span> <span class="mi">0</span> <span class="bp">self</span><span class="o">.</span><span class="n">timeout</span> <span class="o">=</span> <span class="mi">1</span> <span class="bp">self</span><span class="o">.</span><span class="n">logname</span> <span class="o">=</span> <span class="bp">None</span> <span class="k">def</span> <span class="nf">serve_until_stopped</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="kn">import</span> <span class="nn">select</span> <span class="n">abort</span> <span class="o">=</span> <span class="mi">0</span> <span class="k">while</span> <span class="ow">not</span> <span class="n">abort</span><span class="p">:</span> <span class="n">rd</span><span class="p">,</span> <span class="n">wr</span><span class="p">,</span> <span class="n">ex</span> <span class="o">=</span> <span class="n">select</span><span class="o">.</span><span class="n">select</span><span class="p">([</span><span class="bp">self</span><span class="o">.</span><span class="n">socket</span><span class="o">.</span><span class="n">fileno</span><span class="p">()],</span> <span class="p">[],</span> <span class="p">[],</span> <span class="bp">self</span><span class="o">.</span><span class="n">timeout</span><span class="p">)</span> <span class="k">if</span> <span class="n">rd</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">handle_request</span><span class="p">()</span> <span class="n">abort</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">abort</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">format</span><span class="o">=</span><span class="s">"</span><span class="si">%(relativeCreated)5d</span><span class="s"> </span><span class="si">%(name)-15s</span><span class="s"> </span><span class="si">%(levelname)-8s</span><span class="s"> </span><span class="si">%(message)s</span><span class="s">"</span><span class="p">)</span> <span class="n">tcpserver</span> <span class="o">=</span> <span class="n">LogRecordSocketReceiver</span><span class="p">()</span> <span class="k">print</span> <span class="s">"About to start TCP server..."</span> <span class="n">tcpserver</span><span class="o">.</span><span class="n">serve_until_stopped</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> <p>First run the server, and then the client. On the client side, nothing is printed on the console; on the server side, you should see something like:</p> <div class="highlight-python"><pre>About to start TCP server... 59 root INFO Jackdaws love my big sphinx of quartz. 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim. 69 myapp.area1 INFO How quickly daft jumping zebras vex. 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack. 69 myapp.area2 ERROR The five boxing wizards jump quickly.</pre> </div> </div> <div class="section" id="using-arbitrary-objects-as-messages"> <h2>15.7.12. 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>15.7.13. 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><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><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="xref docutils literal"><span class="pre">None</span></tt>.</td> </tr> <tr><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><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 <tt class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></tt> and <tt class="xref py py-mod docutils literal"><span class="pre">logging.config</span></tt>, they won’t take up any memory.</p> </div> <div class="section" id="handler-objects"> <span id="handler"></span><h2>15.7.14. Handler Objects<a class="headerlink" href="#handler-objects" title="Permalink to this headline">¶</a></h2> <p>Handlers have the following attributes and methods. Note that <tt class="xref py py-class docutils literal"><span class="pre">Handler</span></tt> is never instantiated directly; this class acts as a base for more useful subclasses. However, the <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> method in subclasses needs to call <a class="reference internal" href="#logging.Handler.__init__" title="logging.Handler.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">Handler.__init__()</span></tt></a>.</p> <dl class="method"> <dt id="logging.Handler.__init__"> <tt class="descclassname">Handler.</tt><tt class="descname">__init__</tt><big>(</big><em>level=NOTSET</em><big>)</big><a class="headerlink" href="#logging.Handler.__init__" title="Permalink to this definition">¶</a></dt> <dd><p>Initializes the <tt class="xref py py-class docutils literal"><span class="pre">Handler</span></tt> instance by setting its level, setting the list of filters to the empty list and creating a lock (using <a class="reference internal" href="#logging.Handler.createLock" title="logging.Handler.createLock"><tt class="xref py py-meth docutils literal"><span class="pre">createLock()</span></tt></a>) for serializing access to an I/O mechanism.</p> </dd></dl> <dl class="method"> <dt id="logging.Handler.createLock"> <tt class="descclassname">Handler.</tt><tt class="descname">createLock</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.Handler.createLock" title="Permalink to this definition">¶</a></dt> <dd><p>Initializes a thread lock which can be used to serialize access to underlying I/O functionality which may not be threadsafe.</p> </dd></dl> <dl class="method"> <dt id="logging.Handler.acquire"> <tt class="descclassname">Handler.</tt><tt class="descname">acquire</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.Handler.acquire" title="Permalink to this definition">¶</a></dt> <dd><p>Acquires the thread lock created with <a class="reference internal" href="#logging.Handler.createLock" title="logging.Handler.createLock"><tt class="xref py py-meth docutils literal"><span class="pre">createLock()</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="logging.Handler.release"> <tt class="descclassname">Handler.</tt><tt class="descname">release</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.Handler.release" title="Permalink to this definition">¶</a></dt> <dd><p>Releases the thread lock acquired with <a class="reference internal" href="#logging.Handler.acquire" title="logging.Handler.acquire"><tt class="xref py py-meth docutils literal"><span class="pre">acquire()</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="logging.Handler.setLevel"> <tt class="descclassname">Handler.</tt><tt class="descname">setLevel</tt><big>(</big><em>lvl</em><big>)</big><a class="headerlink" href="#logging.Handler.setLevel" title="Permalink to this definition">¶</a></dt> <dd><p>Sets the threshold for this handler to <em>lvl</em>. Logging messages which are less severe than <em>lvl</em> will be ignored. When a handler is created, the level is set to <tt class="xref py py-const docutils literal"><span class="pre">NOTSET</span></tt> (which causes all messages to be processed).</p> </dd></dl> <dl class="method"> <dt id="logging.Handler.setFormatter"> <tt class="descclassname">Handler.</tt><tt class="descname">setFormatter</tt><big>(</big><em>form</em><big>)</big><a class="headerlink" href="#logging.Handler.setFormatter" title="Permalink to this definition">¶</a></dt> <dd><p>Sets the <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> for this handler to <em>form</em>.</p> </dd></dl> <dl class="method"> <dt id="logging.Handler.addFilter"> <tt class="descclassname">Handler.</tt><tt class="descname">addFilter</tt><big>(</big><em>filt</em><big>)</big><a class="headerlink" href="#logging.Handler.addFilter" title="Permalink to this definition">¶</a></dt> <dd><p>Adds the specified filter <em>filt</em> to this handler.</p> </dd></dl> <dl class="method"> <dt id="logging.Handler.removeFilter"> <tt class="descclassname">Handler.</tt><tt class="descname">removeFilter</tt><big>(</big><em>filt</em><big>)</big><a class="headerlink" href="#logging.Handler.removeFilter" title="Permalink to this definition">¶</a></dt> <dd><p>Removes the specified filter <em>filt</em> from this handler.</p> </dd></dl> <dl class="method"> <dt id="logging.Handler.filter"> <tt class="descclassname">Handler.</tt><tt class="descname">filter</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.Handler.filter" title="Permalink to this definition">¶</a></dt> <dd><p>Applies this handler’s filters to the record and returns a true value if the record is to be processed.</p> </dd></dl> <dl class="method"> <dt id="logging.Handler.flush"> <tt class="descclassname">Handler.</tt><tt class="descname">flush</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.Handler.flush" title="Permalink to this definition">¶</a></dt> <dd><p>Ensure all logging output has been flushed. This version does nothing and is intended to be implemented by subclasses.</p> </dd></dl> <dl class="method"> <dt id="logging.Handler.close"> <tt class="descclassname">Handler.</tt><tt class="descname">close</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.Handler.close" title="Permalink to this definition">¶</a></dt> <dd><p>Tidy up any resources used by the handler. This version does no output but removes the handler from an internal list of handlers which is closed when <a class="reference internal" href="#logging.shutdown" title="logging.shutdown"><tt class="xref py py-func docutils literal"><span class="pre">shutdown()</span></tt></a> is called. Subclasses should ensure that this gets called from overridden <a class="reference internal" href="#logging.Handler.close" title="logging.Handler.close"><tt class="xref py py-meth docutils literal"><span class="pre">close()</span></tt></a> methods.</p> </dd></dl> <dl class="method"> <dt id="logging.Handler.handle"> <tt class="descclassname">Handler.</tt><tt class="descname">handle</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.Handler.handle" title="Permalink to this definition">¶</a></dt> <dd><p>Conditionally emits the specified logging record, depending on filters which may have been added to the handler. Wraps the actual emission of the record with acquisition/release of the I/O thread lock.</p> </dd></dl> <dl class="method"> <dt id="logging.Handler.handleError"> <tt class="descclassname">Handler.</tt><tt class="descname">handleError</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.Handler.handleError" title="Permalink to this definition">¶</a></dt> <dd><p>This method should be called from handlers when an exception is encountered during an <a class="reference internal" href="#logging.Handler.emit" title="logging.Handler.emit"><tt class="xref py py-meth docutils literal"><span class="pre">emit()</span></tt></a> call. By default it does nothing, which means that exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The specified record is the one which was being processed when the exception occurred.</p> </dd></dl> <dl class="method"> <dt id="logging.Handler.format"> <tt class="descclassname">Handler.</tt><tt class="descname">format</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.Handler.format" title="Permalink to this definition">¶</a></dt> <dd><p>Do formatting for a record - if a formatter is set, use it. Otherwise, use the default formatter for the module.</p> </dd></dl> <dl class="method"> <dt id="logging.Handler.emit"> <tt class="descclassname">Handler.</tt><tt class="descname">emit</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.Handler.emit" title="Permalink to this definition">¶</a></dt> <dd><p>Do whatever it takes to actually log the specified logging record. This version is intended to be implemented by subclasses and so raises a <a class="reference internal" href="exceptions.html#exceptions.NotImplementedError" title="exceptions.NotImplementedError"><tt class="xref py py-exc docutils literal"><span class="pre">NotImplementedError</span></tt></a>.</p> </dd></dl> <div class="section" id="streamhandler"> <span id="stream-handler"></span><h3>15.7.14.1. StreamHandler<a class="headerlink" href="#streamhandler" title="Permalink to this headline">¶</a></h3> <p>The <a class="reference internal" href="#logging.StreamHandler" title="logging.StreamHandler"><tt class="xref py py-class docutils literal"><span class="pre">StreamHandler</span></tt></a> class, located in the core <a class="reference internal" href="#module-logging" title="Flexible error logging system for applications."><tt class="xref py py-mod docutils literal"><span class="pre">logging</span></tt></a> package, sends logging output to streams such as <em>sys.stdout</em>, <em>sys.stderr</em> or any file-like object (or, more precisely, any object which supports <tt class="xref py py-meth docutils literal"><span class="pre">write()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt> methods).</p> <dl class="class"> <dt id="logging.StreamHandler"> <em class="property">class </em><tt class="descclassname">logging.</tt><tt class="descname">StreamHandler</tt><big>(</big><span class="optional">[</span><em>stream</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.StreamHandler" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a new instance of the <a class="reference internal" href="#logging.StreamHandler" title="logging.StreamHandler"><tt class="xref py py-class docutils literal"><span class="pre">StreamHandler</span></tt></a> class. If <em>stream</em> is specified, the instance will use it for logging output; otherwise, <em>sys.stderr</em> will be used.</p> <dl class="method"> <dt id="logging.StreamHandler.emit"> <tt class="descname">emit</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.StreamHandler.emit" title="Permalink to this definition">¶</a></dt> <dd><p>If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using <a class="reference internal" href="traceback.html#traceback.print_exception" title="traceback.print_exception"><tt class="xref py py-func docutils literal"><span class="pre">traceback.print_exception()</span></tt></a> and appended to the stream.</p> </dd></dl> <dl class="method"> <dt id="logging.StreamHandler.flush"> <tt class="descname">flush</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.StreamHandler.flush" title="Permalink to this definition">¶</a></dt> <dd><p>Flushes the stream by calling its <a class="reference internal" href="#logging.StreamHandler.flush" title="logging.StreamHandler.flush"><tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt></a> method. Note that the <tt class="xref py py-meth docutils literal"><span class="pre">close()</span></tt> method is inherited from <tt class="xref py py-class docutils literal"><span class="pre">Handler</span></tt> and so does no output, so an explicit <a class="reference internal" href="#logging.StreamHandler.flush" title="logging.StreamHandler.flush"><tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt></a> call may be needed at times.</p> </dd></dl> </dd></dl> </div> <div class="section" id="filehandler"> <span id="file-handler"></span><h3>15.7.14.2. FileHandler<a class="headerlink" href="#filehandler" title="Permalink to this headline">¶</a></h3> <p>The <a class="reference internal" href="#logging.FileHandler" title="logging.FileHandler"><tt class="xref py py-class docutils literal"><span class="pre">FileHandler</span></tt></a> class, located in the core <a class="reference internal" href="#module-logging" title="Flexible error logging system for applications."><tt class="xref py py-mod docutils literal"><span class="pre">logging</span></tt></a> package, sends logging output to a disk file. It inherits the output functionality from <a class="reference internal" href="#logging.StreamHandler" title="logging.StreamHandler"><tt class="xref py py-class docutils literal"><span class="pre">StreamHandler</span></tt></a>.</p> <dl class="class"> <dt id="logging.FileHandler"> <em class="property">class </em><tt class="descclassname">logging.</tt><tt class="descname">FileHandler</tt><big>(</big><em>filename</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>encoding</em><span class="optional">[</span>, <em>delay</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.FileHandler" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a new instance of the <a class="reference internal" href="#logging.FileHandler" title="logging.FileHandler"><tt class="xref py py-class docutils literal"><span class="pre">FileHandler</span></tt></a> class. The specified file is opened and used as the stream for logging. If <em>mode</em> is not specified, <tt class="xref py py-const docutils literal"><span class="pre">'a'</span></tt> is used. If <em>encoding</em> is not <em>None</em>, it is used to open the file with that encoding. If <em>delay</em> is true, then file opening is deferred until the first call to <a class="reference internal" href="#logging.FileHandler.emit" title="logging.FileHandler.emit"><tt class="xref py py-meth docutils literal"><span class="pre">emit()</span></tt></a>. By default, the file grows indefinitely.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.6: </span><em>delay</em> was added.</p> <dl class="method"> <dt id="logging.FileHandler.close"> <tt class="descname">close</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.FileHandler.close" title="Permalink to this definition">¶</a></dt> <dd><p>Closes the file.</p> </dd></dl> <dl class="method"> <dt id="logging.FileHandler.emit"> <tt class="descname">emit</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.FileHandler.emit" title="Permalink to this definition">¶</a></dt> <dd><p>Outputs the record to the file.</p> </dd></dl> </dd></dl> </div> <div class="section" id="nullhandler"> <span id="null-handler"></span><h3>15.7.14.3. NullHandler<a class="headerlink" href="#nullhandler" title="Permalink to this headline">¶</a></h3> <p class="versionadded"> <span class="versionmodified">New in version 2.7.</span></p> <p>The <a class="reference internal" href="#logging.NullHandler" title="logging.NullHandler"><tt class="xref py py-class docutils literal"><span class="pre">NullHandler</span></tt></a> class, located in the core <a class="reference internal" href="#module-logging" title="Flexible error logging system for applications."><tt class="xref py py-mod docutils literal"><span class="pre">logging</span></tt></a> package, does not do any formatting or output. It is essentially a “no-op” handler for use by library developers.</p> <dl class="class"> <dt id="logging.NullHandler"> <em class="property">class </em><tt class="descclassname">logging.</tt><tt class="descname">NullHandler</tt><a class="headerlink" href="#logging.NullHandler" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a new instance of the <a class="reference internal" href="#logging.NullHandler" title="logging.NullHandler"><tt class="xref py py-class docutils literal"><span class="pre">NullHandler</span></tt></a> class.</p> <dl class="method"> <dt id="logging.NullHandler.emit"> <tt class="descname">emit</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.NullHandler.emit" title="Permalink to this definition">¶</a></dt> <dd><p>This method does nothing.</p> </dd></dl> </dd></dl> <p>See <a class="reference internal" href="#library-config"><em>Configuring Logging for a Library</em></a> for more information on how to use <a class="reference internal" href="#logging.NullHandler" title="logging.NullHandler"><tt class="xref py py-class docutils literal"><span class="pre">NullHandler</span></tt></a>.</p> </div> <div class="section" id="watchedfilehandler"> <span id="watched-file-handler"></span><h3>15.7.14.4. WatchedFileHandler<a class="headerlink" href="#watchedfilehandler" title="Permalink to this headline">¶</a></h3> <p class="versionadded"> <span class="versionmodified">New in version 2.6.</span></p> <p>The <a class="reference internal" href="#logging.handlers.WatchedFileHandler" title="logging.handlers.WatchedFileHandler"><tt class="xref py py-class docutils literal"><span class="pre">WatchedFileHandler</span></tt></a> class, located in the <tt class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></tt> module, is a <tt class="xref py py-class docutils literal"><span class="pre">FileHandler</span></tt> which watches the file it is logging to. If the file changes, it is closed and reopened using the file name.</p> <p>A file change can happen because of usage of programs such as <em>newsyslog</em> and <em>logrotate</em> which perform log file rotation. This handler, intended for use under Unix/Linux, watches the file to see if it has changed since the last emit. (A file is deemed to have changed if its device or inode have changed.) If the file has changed, the old file stream is closed, and the file opened to get a new stream.</p> <p>This handler is not appropriate for use under Windows, because under Windows open log files cannot be moved or renamed - logging opens the files with exclusive locks - and so there is no need for such a handler. Furthermore, <em>ST_INO</em> is not supported under Windows; <tt class="xref py py-func docutils literal"><span class="pre">stat()</span></tt> always returns zero for this value.</p> <dl class="class"> <dt id="logging.handlers.WatchedFileHandler"> <em class="property">class </em><tt class="descclassname">logging.handlers.</tt><tt class="descname">WatchedFileHandler</tt><big>(</big><em>filename</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>encoding</em><span class="optional">[</span>, <em>delay</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.handlers.WatchedFileHandler" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.WatchedFileHandler" title="logging.handlers.WatchedFileHandler"><tt class="xref py py-class docutils literal"><span class="pre">WatchedFileHandler</span></tt></a> class. The specified file is opened and used as the stream for logging. If <em>mode</em> is not specified, <tt class="xref py py-const docutils literal"><span class="pre">'a'</span></tt> is used. If <em>encoding</em> is not <em>None</em>, it is used to open the file with that encoding. If <em>delay</em> is true, then file opening is deferred until the first call to <a class="reference internal" href="#logging.handlers.WatchedFileHandler.emit" title="logging.handlers.WatchedFileHandler.emit"><tt class="xref py py-meth docutils literal"><span class="pre">emit()</span></tt></a>. By default, the file grows indefinitely.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.6: </span><em>delay</em> was added.</p> <dl class="method"> <dt id="logging.handlers.WatchedFileHandler.emit"> <tt class="descname">emit</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.handlers.WatchedFileHandler.emit" title="Permalink to this definition">¶</a></dt> <dd><p>Outputs the record to the file, but first checks to see if the file has changed. If it has, the existing stream is flushed and closed and the file opened again, before outputting the record to the file.</p> </dd></dl> </dd></dl> </div> <div class="section" id="rotatingfilehandler"> <span id="rotating-file-handler"></span><h3>15.7.14.5. RotatingFileHandler<a class="headerlink" href="#rotatingfilehandler" title="Permalink to this headline">¶</a></h3> <p>The <a class="reference internal" href="#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><tt class="xref py py-class docutils literal"><span class="pre">RotatingFileHandler</span></tt></a> class, located in the <tt class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></tt> module, supports rotation of disk log files.</p> <dl class="class"> <dt id="logging.handlers.RotatingFileHandler"> <em class="property">class </em><tt class="descclassname">logging.handlers.</tt><tt class="descname">RotatingFileHandler</tt><big>(</big><em>filename</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>maxBytes</em><span class="optional">[</span>, <em>backupCount</em><span class="optional">[</span>, <em>encoding</em><span class="optional">[</span>, <em>delay</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.handlers.RotatingFileHandler" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><tt class="xref py py-class docutils literal"><span class="pre">RotatingFileHandler</span></tt></a> class. The specified file is opened and used as the stream for logging. If <em>mode</em> is not specified, <tt class="docutils literal"><span class="pre">'a'</span></tt> is used. If <em>encoding</em> is not <em>None</em>, it is used to open the file with that encoding. If <em>delay</em> is true, then file opening is deferred until the first call to <a class="reference internal" href="#logging.handlers.RotatingFileHandler.emit" title="logging.handlers.RotatingFileHandler.emit"><tt class="xref py py-meth docutils literal"><span class="pre">emit()</span></tt></a>. By default, the file grows indefinitely.</p> <p>You can use the <em>maxBytes</em> and <em>backupCount</em> values to allow the file to <em class="dfn">rollover</em> at a predetermined size. When the size is about to be exceeded, the file is closed and a new file is silently opened for output. Rollover occurs whenever the current log file is nearly <em>maxBytes</em> in length; if <em>maxBytes</em> is zero, rollover never occurs. If <em>backupCount</em> is non-zero, the system will save old log files by appending the extensions “.1”, “.2” etc., to the filename. For example, with a <em>backupCount</em> of 5 and a base file name of <tt class="file docutils literal"><span class="pre">app.log</span></tt>, you would get <tt class="file docutils literal"><span class="pre">app.log</span></tt>, <tt class="file docutils literal"><span class="pre">app.log.1</span></tt>, <tt class="file docutils literal"><span class="pre">app.log.2</span></tt>, up to <tt class="file docutils literal"><span class="pre">app.log.5</span></tt>. The file being written to is always <tt class="file docutils literal"><span class="pre">app.log</span></tt>. When this file is filled, it is closed and renamed to <tt class="file docutils literal"><span class="pre">app.log.1</span></tt>, and if files <tt class="file docutils literal"><span class="pre">app.log.1</span></tt>, <tt class="file docutils literal"><span class="pre">app.log.2</span></tt>, etc. exist, then they are renamed to <tt class="file docutils literal"><span class="pre">app.log.2</span></tt>, <tt class="file docutils literal"><span class="pre">app.log.3</span></tt> etc. respectively.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.6: </span><em>delay</em> was added.</p> <dl class="method"> <dt id="logging.handlers.RotatingFileHandler.doRollover"> <tt class="descname">doRollover</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.handlers.RotatingFileHandler.doRollover" title="Permalink to this definition">¶</a></dt> <dd><p>Does a rollover, as described above.</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.RotatingFileHandler.emit"> <tt class="descname">emit</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.handlers.RotatingFileHandler.emit" title="Permalink to this definition">¶</a></dt> <dd><p>Outputs the record to the file, catering for rollover as described previously.</p> </dd></dl> </dd></dl> </div> <div class="section" id="timedrotatingfilehandler"> <span id="timed-rotating-file-handler"></span><h3>15.7.14.6. TimedRotatingFileHandler<a class="headerlink" href="#timedrotatingfilehandler" title="Permalink to this headline">¶</a></h3> <p>The <a class="reference internal" href="#logging.handlers.TimedRotatingFileHandler" title="logging.handlers.TimedRotatingFileHandler"><tt class="xref py py-class docutils literal"><span class="pre">TimedRotatingFileHandler</span></tt></a> class, located in the <tt class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></tt> module, supports rotation of disk log files at certain timed intervals.</p> <dl class="class"> <dt id="logging.handlers.TimedRotatingFileHandler"> <em class="property">class </em><tt class="descclassname">logging.handlers.</tt><tt class="descname">TimedRotatingFileHandler</tt><big>(</big><em>filename</em><span class="optional">[</span>, <em>when</em><span class="optional">[</span>, <em>interval</em><span class="optional">[</span>, <em>backupCount</em><span class="optional">[</span>, <em>encoding</em><span class="optional">[</span>, <em>delay</em><span class="optional">[</span>, <em>utc</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.handlers.TimedRotatingFileHandler" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.TimedRotatingFileHandler" title="logging.handlers.TimedRotatingFileHandler"><tt class="xref py py-class docutils literal"><span class="pre">TimedRotatingFileHandler</span></tt></a> class. The specified file is opened and used as the stream for logging. On rotating it also sets the filename suffix. Rotating happens based on the product of <em>when</em> and <em>interval</em>.</p> <p>You can use the <em>when</em> to specify the type of <em>interval</em>. The list of possible values is below. Note that they are not case sensitive.</p> <table border="1" class="docutils"> <colgroup> <col width="41%" /> <col width="59%" /> </colgroup> <thead valign="bottom"> <tr><th class="head">Value</th> <th class="head">Type of interval</th> </tr> </thead> <tbody valign="top"> <tr><td><tt class="docutils literal"><span class="pre">'S'</span></tt></td> <td>Seconds</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">'M'</span></tt></td> <td>Minutes</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">'H'</span></tt></td> <td>Hours</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">'D'</span></tt></td> <td>Days</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">'W'</span></tt></td> <td>Week day (0=Monday)</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">'midnight'</span></tt></td> <td>Roll over at midnight</td> </tr> </tbody> </table> <p>The system will save old log files by appending extensions to the filename. The extensions are date-and-time based, using the strftime format <tt class="docutils literal"><span class="pre">%Y-%m-%d_%H-%M-%S</span></tt> or a leading portion thereof, depending on the rollover interval.</p> <p>When computing the next rollover time for the first time (when the handler is created), the last modification time of an existing log file, or else the current time, is used to compute when the next rotation will occur.</p> <p>If the <em>utc</em> argument is true, times in UTC will be used; otherwise local time is used.</p> <p>If <em>backupCount</em> is nonzero, at most <em>backupCount</em> files will be kept, and if more would be created when rollover occurs, the oldest one is deleted. The deletion logic uses the interval to determine which files to delete, so changing the interval may leave old files lying around.</p> <p>If <em>delay</em> is true, then file opening is deferred until the first call to <a class="reference internal" href="#logging.handlers.TimedRotatingFileHandler.emit" title="logging.handlers.TimedRotatingFileHandler.emit"><tt class="xref py py-meth docutils literal"><span class="pre">emit()</span></tt></a>.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.6: </span><em>delay</em> was added.</p> <dl class="method"> <dt id="logging.handlers.TimedRotatingFileHandler.doRollover"> <tt class="descname">doRollover</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.handlers.TimedRotatingFileHandler.doRollover" title="Permalink to this definition">¶</a></dt> <dd><p>Does a rollover, as described above.</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.TimedRotatingFileHandler.emit"> <tt class="descname">emit</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.handlers.TimedRotatingFileHandler.emit" title="Permalink to this definition">¶</a></dt> <dd><p>Outputs the record to the file, catering for rollover as described above.</p> </dd></dl> </dd></dl> </div> <div class="section" id="sockethandler"> <span id="socket-handler"></span><h3>15.7.14.7. SocketHandler<a class="headerlink" href="#sockethandler" title="Permalink to this headline">¶</a></h3> <p>The <a class="reference internal" href="#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><tt class="xref py py-class docutils literal"><span class="pre">SocketHandler</span></tt></a> class, located in the <tt class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></tt> module, sends logging output to a network socket. The base class uses a TCP socket.</p> <dl class="class"> <dt id="logging.handlers.SocketHandler"> <em class="property">class </em><tt class="descclassname">logging.handlers.</tt><tt class="descname">SocketHandler</tt><big>(</big><em>host</em>, <em>port</em><big>)</big><a class="headerlink" href="#logging.handlers.SocketHandler" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><tt class="xref py py-class docutils literal"><span class="pre">SocketHandler</span></tt></a> class intended to communicate with a remote machine whose address is given by <em>host</em> and <em>port</em>.</p> <dl class="method"> <dt id="logging.handlers.SocketHandler.close"> <tt class="descname">close</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.handlers.SocketHandler.close" title="Permalink to this definition">¶</a></dt> <dd><p>Closes the socket.</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.SocketHandler.emit"> <tt class="descname">emit</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.handlers.SocketHandler.emit" title="Permalink to this definition">¶</a></dt> <dd><p>Pickles the record’s attribute dictionary and writes it to the socket in binary format. If there is an error with the socket, silently drops the packet. If the connection was previously lost, re-establishes the connection. To unpickle the record at the receiving end into a <tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt>, use the <tt class="xref py py-func docutils literal"><span class="pre">makeLogRecord()</span></tt> function.</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.SocketHandler.handleError"> <tt class="descname">handleError</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.handlers.SocketHandler.handleError" title="Permalink to this definition">¶</a></dt> <dd><p>Handles an error which has occurred during <a class="reference internal" href="#logging.handlers.SocketHandler.emit" title="logging.handlers.SocketHandler.emit"><tt class="xref py py-meth docutils literal"><span class="pre">emit()</span></tt></a>. The most likely cause is a lost connection. Closes the socket so that we can retry on the next event.</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.SocketHandler.makeSocket"> <tt class="descname">makeSocket</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.handlers.SocketHandler.makeSocket" title="Permalink to this definition">¶</a></dt> <dd><p>This is a factory method which allows subclasses to define the precise type of socket they want. The default implementation creates a TCP socket (<a class="reference internal" href="socket.html#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><tt class="xref py py-const docutils literal"><span class="pre">socket.SOCK_STREAM</span></tt></a>).</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.SocketHandler.makePickle"> <tt class="descname">makePickle</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.handlers.SocketHandler.makePickle" title="Permalink to this definition">¶</a></dt> <dd><p>Pickles the record’s attribute dictionary in binary format with a length prefix, and returns it ready for transmission across the socket.</p> <p>Note that pickles aren’t completely secure. If you are concerned about security, you may want to override this method to implement a more secure mechanism. For example, you can sign pickles using HMAC and then verify them on the receiving end, or alternatively you can disable unpickling of global objects on the receiving end.</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.SocketHandler.send"> <tt class="descname">send</tt><big>(</big><em>packet</em><big>)</big><a class="headerlink" href="#logging.handlers.SocketHandler.send" title="Permalink to this definition">¶</a></dt> <dd><p>Send a pickled string <em>packet</em> to the socket. This function allows for partial sends which can happen when the network is busy.</p> </dd></dl> </dd></dl> </div> <div class="section" id="datagramhandler"> <span id="datagram-handler"></span><h3>15.7.14.8. DatagramHandler<a class="headerlink" href="#datagramhandler" title="Permalink to this headline">¶</a></h3> <p>The <a class="reference internal" href="#logging.handlers.DatagramHandler" title="logging.handlers.DatagramHandler"><tt class="xref py py-class docutils literal"><span class="pre">DatagramHandler</span></tt></a> class, located in the <tt class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></tt> module, inherits from <a class="reference internal" href="#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><tt class="xref py py-class docutils literal"><span class="pre">SocketHandler</span></tt></a> to support sending logging messages over UDP sockets.</p> <dl class="class"> <dt id="logging.handlers.DatagramHandler"> <em class="property">class </em><tt class="descclassname">logging.handlers.</tt><tt class="descname">DatagramHandler</tt><big>(</big><em>host</em>, <em>port</em><big>)</big><a class="headerlink" href="#logging.handlers.DatagramHandler" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.DatagramHandler" title="logging.handlers.DatagramHandler"><tt class="xref py py-class docutils literal"><span class="pre">DatagramHandler</span></tt></a> class intended to communicate with a remote machine whose address is given by <em>host</em> and <em>port</em>.</p> <dl class="method"> <dt id="logging.handlers.DatagramHandler.emit"> <tt class="descname">emit</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.handlers.DatagramHandler.emit" title="Permalink to this definition">¶</a></dt> <dd><p>Pickles the record’s attribute dictionary and writes it to the socket in binary format. If there is an error with the socket, silently drops the packet. To unpickle the record at the receiving end into a <tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt>, use the <tt class="xref py py-func docutils literal"><span class="pre">makeLogRecord()</span></tt> function.</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.DatagramHandler.makeSocket"> <tt class="descname">makeSocket</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.handlers.DatagramHandler.makeSocket" title="Permalink to this definition">¶</a></dt> <dd><p>The factory method of <a class="reference internal" href="#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><tt class="xref py py-class docutils literal"><span class="pre">SocketHandler</span></tt></a> is here overridden to create a UDP socket (<a class="reference internal" href="socket.html#socket.SOCK_DGRAM" title="socket.SOCK_DGRAM"><tt class="xref py py-const docutils literal"><span class="pre">socket.SOCK_DGRAM</span></tt></a>).</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.DatagramHandler.send"> <tt class="descname">send</tt><big>(</big><em>s</em><big>)</big><a class="headerlink" href="#logging.handlers.DatagramHandler.send" title="Permalink to this definition">¶</a></dt> <dd><p>Send a pickled string to a socket.</p> </dd></dl> </dd></dl> </div> <div class="section" id="sysloghandler"> <span id="syslog-handler"></span><h3>15.7.14.9. SysLogHandler<a class="headerlink" href="#sysloghandler" title="Permalink to this headline">¶</a></h3> <p>The <a class="reference internal" href="#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><tt class="xref py py-class docutils literal"><span class="pre">SysLogHandler</span></tt></a> class, located in the <tt class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></tt> module, supports sending logging messages to a remote or local Unix syslog.</p> <dl class="class"> <dt id="logging.handlers.SysLogHandler"> <em class="property">class </em><tt class="descclassname">logging.handlers.</tt><tt class="descname">SysLogHandler</tt><big>(</big><span class="optional">[</span><em>address</em><span class="optional">[</span>, <em>facility</em><span class="optional">[</span>, <em>socktype</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.handlers.SysLogHandler" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><tt class="xref py py-class docutils literal"><span class="pre">SysLogHandler</span></tt></a> class intended to communicate with a remote Unix machine whose address is given by <em>address</em> in the form of a <tt class="docutils literal"><span class="pre">(host,</span> <span class="pre">port)</span></tt> tuple. If <em>address</em> is not specified, <tt class="docutils literal"><span class="pre">('localhost',</span> <span class="pre">514)</span></tt> is used. The address is used to open a socket. An alternative to providing a <tt class="docutils literal"><span class="pre">(host,</span> <span class="pre">port)</span></tt> tuple is providing an address as a string, for example “/dev/log”. In this case, a Unix domain socket is used to send the message to the syslog. If <em>facility</em> is not specified, <tt class="xref py py-const docutils literal"><span class="pre">LOG_USER</span></tt> is used. The type of socket opened depends on the <em>socktype</em> argument, which defaults to <a class="reference internal" href="socket.html#socket.SOCK_DGRAM" title="socket.SOCK_DGRAM"><tt class="xref py py-const docutils literal"><span class="pre">socket.SOCK_DGRAM</span></tt></a> and thus opens a UDP socket. To open a TCP socket (for use with the newer syslog daemons such as rsyslog), specify a value of <a class="reference internal" href="socket.html#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><tt class="xref py py-const docutils literal"><span class="pre">socket.SOCK_STREAM</span></tt></a>.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.7: </span><em>socktype</em> was added.</p> <dl class="method"> <dt id="logging.handlers.SysLogHandler.close"> <tt class="descname">close</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.handlers.SysLogHandler.close" title="Permalink to this definition">¶</a></dt> <dd><p>Closes the socket to the remote host.</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.SysLogHandler.emit"> <tt class="descname">emit</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.handlers.SysLogHandler.emit" title="Permalink to this definition">¶</a></dt> <dd><p>The record is formatted, and then sent to the syslog server. If exception information is present, it is <em>not</em> sent to the server.</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.SysLogHandler.encodePriority"> <tt class="descname">encodePriority</tt><big>(</big><em>facility</em>, <em>priority</em><big>)</big><a class="headerlink" href="#logging.handlers.SysLogHandler.encodePriority" title="Permalink to this definition">¶</a></dt> <dd><p>Encodes the facility and priority into an integer. You can pass in strings or integers - if strings are passed, internal mapping dictionaries are used to convert them to integers.</p> <p>The symbolic <tt class="docutils literal"><span class="pre">LOG_</span></tt> values are defined in <a class="reference internal" href="#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><tt class="xref py py-class docutils literal"><span class="pre">SysLogHandler</span></tt></a> and mirror the values defined in the <tt class="docutils literal"><span class="pre">sys/syslog.h</span></tt> header file.</p> <p><strong>Priorities</strong></p> <table border="1" class="docutils"> <colgroup> <col width="63%" /> <col width="37%" /> </colgroup> <thead valign="bottom"> <tr><th class="head">Name (string)</th> <th class="head">Symbolic value</th> </tr> </thead> <tbody valign="top"> <tr><td><tt class="docutils literal"><span class="pre">alert</span></tt></td> <td>LOG_ALERT</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">crit</span></tt> or <tt class="docutils literal"><span class="pre">critical</span></tt></td> <td>LOG_CRIT</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">debug</span></tt></td> <td>LOG_DEBUG</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">emerg</span></tt> or <tt class="docutils literal"><span class="pre">panic</span></tt></td> <td>LOG_EMERG</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">err</span></tt> or <tt class="docutils literal"><span class="pre">error</span></tt></td> <td>LOG_ERR</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">info</span></tt></td> <td>LOG_INFO</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">notice</span></tt></td> <td>LOG_NOTICE</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">warn</span></tt> or <tt class="docutils literal"><span class="pre">warning</span></tt></td> <td>LOG_WARNING</td> </tr> </tbody> </table> <p><strong>Facilities</strong></p> <table border="1" class="docutils"> <colgroup> <col width="50%" /> <col width="50%" /> </colgroup> <thead valign="bottom"> <tr><th class="head">Name (string)</th> <th class="head">Symbolic value</th> </tr> </thead> <tbody valign="top"> <tr><td><tt class="docutils literal"><span class="pre">auth</span></tt></td> <td>LOG_AUTH</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">authpriv</span></tt></td> <td>LOG_AUTHPRIV</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">cron</span></tt></td> <td>LOG_CRON</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">daemon</span></tt></td> <td>LOG_DAEMON</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">ftp</span></tt></td> <td>LOG_FTP</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">kern</span></tt></td> <td>LOG_KERN</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">lpr</span></tt></td> <td>LOG_LPR</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">mail</span></tt></td> <td>LOG_MAIL</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">news</span></tt></td> <td>LOG_NEWS</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">syslog</span></tt></td> <td>LOG_SYSLOG</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">user</span></tt></td> <td>LOG_USER</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">uucp</span></tt></td> <td>LOG_UUCP</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">local0</span></tt></td> <td>LOG_LOCAL0</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">local1</span></tt></td> <td>LOG_LOCAL1</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">local2</span></tt></td> <td>LOG_LOCAL2</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">local3</span></tt></td> <td>LOG_LOCAL3</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">local4</span></tt></td> <td>LOG_LOCAL4</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">local5</span></tt></td> <td>LOG_LOCAL5</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">local6</span></tt></td> <td>LOG_LOCAL6</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">local7</span></tt></td> <td>LOG_LOCAL7</td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="logging.handlers.SysLogHandler.mapPriority"> <tt class="descname">mapPriority</tt><big>(</big><em>levelname</em><big>)</big><a class="headerlink" href="#logging.handlers.SysLogHandler.mapPriority" title="Permalink to this definition">¶</a></dt> <dd><p>Maps a logging level name to a syslog priority name. You may need to override this if you are using custom levels, or if the default algorithm is not suitable for your needs. The default algorithm maps <tt class="docutils literal"><span class="pre">DEBUG</span></tt>, <tt class="docutils literal"><span class="pre">INFO</span></tt>, <tt class="docutils literal"><span class="pre">WARNING</span></tt>, <tt class="docutils literal"><span class="pre">ERROR</span></tt> and <tt class="docutils literal"><span class="pre">CRITICAL</span></tt> to the equivalent syslog names, and all other level names to “warning”.</p> </dd></dl> </dd></dl> </div> <div class="section" id="nteventloghandler"> <span id="nt-eventlog-handler"></span><h3>15.7.14.10. NTEventLogHandler<a class="headerlink" href="#nteventloghandler" title="Permalink to this headline">¶</a></h3> <p>The <a class="reference internal" href="#logging.handlers.NTEventLogHandler" title="logging.handlers.NTEventLogHandler"><tt class="xref py py-class docutils literal"><span class="pre">NTEventLogHandler</span></tt></a> class, located in the <tt class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></tt> module, supports sending logging messages to a local Windows NT, Windows 2000 or Windows XP event log. Before you can use it, you need Mark Hammond’s Win32 extensions for Python installed.</p> <dl class="class"> <dt id="logging.handlers.NTEventLogHandler"> <em class="property">class </em><tt class="descclassname">logging.handlers.</tt><tt class="descname">NTEventLogHandler</tt><big>(</big><em>appname</em><span class="optional">[</span>, <em>dllname</em><span class="optional">[</span>, <em>logtype</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.handlers.NTEventLogHandler" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.NTEventLogHandler" title="logging.handlers.NTEventLogHandler"><tt class="xref py py-class docutils literal"><span class="pre">NTEventLogHandler</span></tt></a> class. The <em>appname</em> is used to define the application name as it appears in the event log. An appropriate registry entry is created using this name. The <em>dllname</em> should give the fully qualified pathname of a .dll or .exe which contains message definitions to hold in the log (if not specified, <tt class="docutils literal"><span class="pre">'win32service.pyd'</span></tt> is used - this is installed with the Win32 extensions and contains some basic placeholder message definitions. Note that use of these placeholders will make your event logs big, as the entire message source is held in the log. If you want slimmer logs, you have to pass in the name of your own .dll or .exe which contains the message definitions you want to use in the event log). The <em>logtype</em> is one of <tt class="docutils literal"><span class="pre">'Application'</span></tt>, <tt class="docutils literal"><span class="pre">'System'</span></tt> or <tt class="docutils literal"><span class="pre">'Security'</span></tt>, and defaults to <tt class="docutils literal"><span class="pre">'Application'</span></tt>.</p> <dl class="method"> <dt id="logging.handlers.NTEventLogHandler.close"> <tt class="descname">close</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.handlers.NTEventLogHandler.close" title="Permalink to this definition">¶</a></dt> <dd><p>At this point, you can remove the application name from the registry as a source of event log entries. However, if you do this, you will not be able to see the events as you intended in the Event Log Viewer - it needs to be able to access the registry to get the .dll name. The current version does not do this.</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.NTEventLogHandler.emit"> <tt class="descname">emit</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.handlers.NTEventLogHandler.emit" title="Permalink to this definition">¶</a></dt> <dd><p>Determines the message ID, event category and event type, and then logs the message in the NT event log.</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.NTEventLogHandler.getEventCategory"> <tt class="descname">getEventCategory</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.handlers.NTEventLogHandler.getEventCategory" title="Permalink to this definition">¶</a></dt> <dd><p>Returns the event category for the record. Override this if you want to specify your own categories. This version returns 0.</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.NTEventLogHandler.getEventType"> <tt class="descname">getEventType</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.handlers.NTEventLogHandler.getEventType" title="Permalink to this definition">¶</a></dt> <dd><p>Returns the event type for the record. Override this if you want to specify your own types. This version does a mapping using the handler’s typemap attribute, which is set up in <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> to a dictionary which contains mappings for <tt class="xref py py-const docutils literal"><span class="pre">DEBUG</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">INFO</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">WARNING</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">ERROR</span></tt> and <tt class="xref py py-const docutils literal"><span class="pre">CRITICAL</span></tt>. If you are using your own levels, you will either need to override this method or place a suitable dictionary in the handler’s <em>typemap</em> attribute.</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.NTEventLogHandler.getMessageID"> <tt class="descname">getMessageID</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.handlers.NTEventLogHandler.getMessageID" title="Permalink to this definition">¶</a></dt> <dd><p>Returns the message ID for the record. If you are using your own messages, you could do this by having the <em>msg</em> passed to the logger being an ID rather than a format string. Then, in here, you could use a dictionary lookup to get the message ID. This version returns 1, which is the base message ID in <tt class="file docutils literal"><span class="pre">win32service.pyd</span></tt>.</p> </dd></dl> </dd></dl> </div> <div class="section" id="smtphandler"> <span id="smtp-handler"></span><h3>15.7.14.11. SMTPHandler<a class="headerlink" href="#smtphandler" title="Permalink to this headline">¶</a></h3> <p>The <a class="reference internal" href="#logging.handlers.SMTPHandler" title="logging.handlers.SMTPHandler"><tt class="xref py py-class docutils literal"><span class="pre">SMTPHandler</span></tt></a> class, located in the <tt class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></tt> module, supports sending logging messages to an email address via SMTP.</p> <dl class="class"> <dt id="logging.handlers.SMTPHandler"> <em class="property">class </em><tt class="descclassname">logging.handlers.</tt><tt class="descname">SMTPHandler</tt><big>(</big><em>mailhost</em>, <em>fromaddr</em>, <em>toaddrs</em>, <em>subject</em><span class="optional">[</span>, <em>credentials</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.handlers.SMTPHandler" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.SMTPHandler" title="logging.handlers.SMTPHandler"><tt class="xref py py-class docutils literal"><span class="pre">SMTPHandler</span></tt></a> class. The instance is initialized with the from and to addresses and subject line of the email. The <em>toaddrs</em> should be a list of strings. To specify a non-standard SMTP port, use the (host, port) tuple format for the <em>mailhost</em> argument. If you use a string, the standard SMTP port is used. If your SMTP server requires authentication, you can specify a (username, password) tuple for the <em>credentials</em> argument.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.6: </span><em>credentials</em> was added.</p> <dl class="method"> <dt id="logging.handlers.SMTPHandler.emit"> <tt class="descname">emit</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.handlers.SMTPHandler.emit" title="Permalink to this definition">¶</a></dt> <dd><p>Formats the record and sends it to the specified addressees.</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.SMTPHandler.getSubject"> <tt class="descname">getSubject</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.handlers.SMTPHandler.getSubject" title="Permalink to this definition">¶</a></dt> <dd><p>If you want to specify a subject line which is record-dependent, override this method.</p> </dd></dl> </dd></dl> </div> <div class="section" id="memoryhandler"> <span id="memory-handler"></span><h3>15.7.14.12. MemoryHandler<a class="headerlink" href="#memoryhandler" title="Permalink to this headline">¶</a></h3> <p>The <a class="reference internal" href="#logging.handlers.MemoryHandler" title="logging.handlers.MemoryHandler"><tt class="xref py py-class docutils literal"><span class="pre">MemoryHandler</span></tt></a> class, located in the <tt class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></tt> module, supports buffering of logging records in memory, periodically flushing them to a <em class="dfn">target</em> handler. Flushing occurs whenever the buffer is full, or when an event of a certain severity or greater is seen.</p> <p><a class="reference internal" href="#logging.handlers.MemoryHandler" title="logging.handlers.MemoryHandler"><tt class="xref py py-class docutils literal"><span class="pre">MemoryHandler</span></tt></a> is a subclass of the more general <a class="reference internal" href="#logging.handlers.BufferingHandler" title="logging.handlers.BufferingHandler"><tt class="xref py py-class docutils literal"><span class="pre">BufferingHandler</span></tt></a>, which is an abstract class. This buffers logging records in memory. Whenever each record is added to the buffer, a check is made by calling <tt class="xref py py-meth docutils literal"><span class="pre">shouldFlush()</span></tt> to see if the buffer should be flushed. If it should, then <tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt> is expected to do the needful.</p> <dl class="class"> <dt id="logging.handlers.BufferingHandler"> <em class="property">class </em><tt class="descclassname">logging.handlers.</tt><tt class="descname">BufferingHandler</tt><big>(</big><em>capacity</em><big>)</big><a class="headerlink" href="#logging.handlers.BufferingHandler" title="Permalink to this definition">¶</a></dt> <dd><p>Initializes the handler with a buffer of the specified capacity.</p> <dl class="method"> <dt id="logging.handlers.BufferingHandler.emit"> <tt class="descname">emit</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.handlers.BufferingHandler.emit" title="Permalink to this definition">¶</a></dt> <dd><p>Appends the record to the buffer. If <a class="reference internal" href="#logging.handlers.BufferingHandler.shouldFlush" title="logging.handlers.BufferingHandler.shouldFlush"><tt class="xref py py-meth docutils literal"><span class="pre">shouldFlush()</span></tt></a> returns true, calls <a class="reference internal" href="#logging.handlers.BufferingHandler.flush" title="logging.handlers.BufferingHandler.flush"><tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt></a> to process the buffer.</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.BufferingHandler.flush"> <tt class="descname">flush</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.handlers.BufferingHandler.flush" title="Permalink to this definition">¶</a></dt> <dd><p>You can override this to implement custom flushing behavior. This version just zaps the buffer to empty.</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.BufferingHandler.shouldFlush"> <tt class="descname">shouldFlush</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.handlers.BufferingHandler.shouldFlush" title="Permalink to this definition">¶</a></dt> <dd><p>Returns true if the buffer is up to capacity. This method can be overridden to implement custom flushing strategies.</p> </dd></dl> </dd></dl> <dl class="class"> <dt id="logging.handlers.MemoryHandler"> <em class="property">class </em><tt class="descclassname">logging.handlers.</tt><tt class="descname">MemoryHandler</tt><big>(</big><em>capacity</em><span class="optional">[</span>, <em>flushLevel</em><span class="optional">[</span>, <em>target</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.handlers.MemoryHandler" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.MemoryHandler" title="logging.handlers.MemoryHandler"><tt class="xref py py-class docutils literal"><span class="pre">MemoryHandler</span></tt></a> class. The instance is initialized with a buffer size of <em>capacity</em>. If <em>flushLevel</em> is not specified, <tt class="xref py py-const docutils literal"><span class="pre">ERROR</span></tt> is used. If no <em>target</em> is specified, the target will need to be set using <a class="reference internal" href="#logging.handlers.MemoryHandler.setTarget" title="logging.handlers.MemoryHandler.setTarget"><tt class="xref py py-meth docutils literal"><span class="pre">setTarget()</span></tt></a> before this handler does anything useful.</p> <dl class="method"> <dt id="logging.handlers.MemoryHandler.close"> <tt class="descname">close</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.handlers.MemoryHandler.close" title="Permalink to this definition">¶</a></dt> <dd><p>Calls <a class="reference internal" href="#logging.handlers.MemoryHandler.flush" title="logging.handlers.MemoryHandler.flush"><tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt></a>, sets the target to <a class="reference internal" href="constants.html#None" title="None"><tt class="xref py py-const xref docutils literal"><span class="pre">None</span></tt></a> and clears the buffer.</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.MemoryHandler.flush"> <tt class="descname">flush</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.handlers.MemoryHandler.flush" title="Permalink to this definition">¶</a></dt> <dd><p>For a <a class="reference internal" href="#logging.handlers.MemoryHandler" title="logging.handlers.MemoryHandler"><tt class="xref py py-class docutils literal"><span class="pre">MemoryHandler</span></tt></a>, flushing means just sending the buffered records to the target, if there is one. Override if you want different behavior.</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.MemoryHandler.setTarget"> <tt class="descname">setTarget</tt><big>(</big><em>target</em><big>)</big><a class="headerlink" href="#logging.handlers.MemoryHandler.setTarget" title="Permalink to this definition">¶</a></dt> <dd><p>Sets the target handler for this handler.</p> </dd></dl> <dl class="method"> <dt id="logging.handlers.MemoryHandler.shouldFlush"> <tt class="descname">shouldFlush</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.handlers.MemoryHandler.shouldFlush" title="Permalink to this definition">¶</a></dt> <dd><p>Checks for buffer full or a record at the <em>flushLevel</em> or higher.</p> </dd></dl> </dd></dl> </div> <div class="section" id="httphandler"> <span id="http-handler"></span><h3>15.7.14.13. HTTPHandler<a class="headerlink" href="#httphandler" title="Permalink to this headline">¶</a></h3> <p>The <a class="reference internal" href="#logging.handlers.HTTPHandler" title="logging.handlers.HTTPHandler"><tt class="xref py py-class docutils literal"><span class="pre">HTTPHandler</span></tt></a> class, located in the <tt class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></tt> module, supports sending logging messages to a Web 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.</p> <dl class="class"> <dt id="logging.handlers.HTTPHandler"> <em class="property">class </em><tt class="descclassname">logging.handlers.</tt><tt class="descname">HTTPHandler</tt><big>(</big><em>host</em>, <em>url</em><span class="optional">[</span>, <em>method</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.handlers.HTTPHandler" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.HTTPHandler" title="logging.handlers.HTTPHandler"><tt class="xref py py-class docutils literal"><span class="pre">HTTPHandler</span></tt></a> class. The instance is initialized with a host address, url and HTTP method. The <em>host</em> can be of the form <tt class="docutils literal"><span class="pre">host:port</span></tt>, should you need to use a specific port number. If no <em>method</em> is specified, <tt class="docutils literal"><span class="pre">GET</span></tt> is used.</p> <dl class="method"> <dt id="logging.handlers.HTTPHandler.emit"> <tt class="descname">emit</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.handlers.HTTPHandler.emit" title="Permalink to this definition">¶</a></dt> <dd><p>Sends the record to the Web server as an URL-encoded dictionary.</p> </dd></dl> </dd></dl> </div> </div> <div class="section" id="formatter-objects"> <span id="formatter"></span><h2>15.7.15. Formatter Objects<a class="headerlink" href="#formatter-objects" title="Permalink to this headline">¶</a></h2> <p><a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a>s have the following attributes and methods. They are responsible for converting a <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> to (usually) a string which can be interpreted by either a human or an external system. The base <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> allows a formatting string to be specified. If none is supplied, the default value of <tt class="docutils literal"><span class="pre">'%(message)s'</span></tt> is used.</p> <p>A Formatter can be initialized with a format string which makes use of knowledge of the <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> attributes - such as the default value mentioned above making use of the fact that the user’s message and arguments are pre-formatted into a <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a>‘s <em>message</em> attribute. This format string contains standard Python %-style mapping keys. See section <a class="reference internal" href="stdtypes.html#string-formatting"><em>String Formatting Operations</em></a> for more information on string formatting.</p> <p>Currently, the useful mapping keys in a <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> are:</p> <table border="1" class="docutils"> <colgroup> <col width="35%" /> <col width="65%" /> </colgroup> <thead valign="bottom"> <tr><th class="head">Format</th> <th class="head">Description</th> </tr> </thead> <tbody valign="top"> <tr><td><tt class="docutils literal"><span class="pre">%(name)s</span></tt></td> <td>Name of the logger (logging channel).</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">%(levelno)s</span></tt></td> <td>Numeric logging level for the message (<tt class="xref py py-const docutils literal"><span class="pre">DEBUG</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">INFO</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">WARNING</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">ERROR</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">CRITICAL</span></tt>).</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">%(levelname)s</span></tt></td> <td>Text logging level for the message (<tt class="docutils literal"><span class="pre">'DEBUG'</span></tt>, <tt class="docutils literal"><span class="pre">'INFO'</span></tt>, <tt class="docutils literal"><span class="pre">'WARNING'</span></tt>, <tt class="docutils literal"><span class="pre">'ERROR'</span></tt>, <tt class="docutils literal"><span class="pre">'CRITICAL'</span></tt>).</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">%(pathname)s</span></tt></td> <td>Full pathname of the source file where the logging call was issued (if available).</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">%(filename)s</span></tt></td> <td>Filename portion of pathname.</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">%(module)s</span></tt></td> <td>Module (name portion of filename).</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">%(funcName)s</span></tt></td> <td>Name of function containing the logging call.</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">%(lineno)d</span></tt></td> <td>Source line number where the logging call was issued (if available).</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">%(created)f</span></tt></td> <td>Time when the <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> was created (as returned by <a class="reference internal" href="time.html#time.time" title="time.time"><tt class="xref py py-func docutils literal"><span class="pre">time.time()</span></tt></a>).</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">%(relativeCreated)d</span></tt></td> <td>Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">%(asctime)s</span></tt></td> <td>Human-readable time when the <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> was created. By default this is of the form “2003-07-08 16:49:45,896” (the numbers after the comma are millisecond portion of the time).</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">%(msecs)d</span></tt></td> <td>Millisecond portion of the time when the <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> was created.</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">%(thread)d</span></tt></td> <td>Thread ID (if available).</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">%(threadName)s</span></tt></td> <td>Thread name (if available).</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">%(process)d</span></tt></td> <td>Process ID (if available).</td> </tr> <tr><td><tt class="docutils literal"><span class="pre">%(message)s</span></tt></td> <td>The logged message, computed as <tt class="docutils literal"><span class="pre">msg</span> <span class="pre">%</span> <span class="pre">args</span></tt>.</td> </tr> </tbody> </table> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.5: </span><em>funcName</em> was added.</p> <dl class="class"> <dt id="logging.Formatter"> <em class="property">class </em><tt class="descclassname">logging.</tt><tt class="descname">Formatter</tt><big>(</big><span class="optional">[</span><em>fmt</em><span class="optional">[</span>, <em>datefmt</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.Formatter" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a new instance of the <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> class. The instance is initialized with a format string for the message as a whole, as well as a format string for the date/time portion of a message. If no <em>fmt</em> is specified, <tt class="docutils literal"><span class="pre">'%(message)s'</span></tt> is used. If no <em>datefmt</em> is specified, the ISO8601 date format is used.</p> <dl class="method"> <dt id="logging.Formatter.format"> <tt class="descname">format</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.Formatter.format" title="Permalink to this definition">¶</a></dt> <dd><p>The record’s attribute dictionary is used as the operand to a string formatting operation. Returns the resulting string. Before formatting the dictionary, a couple of preparatory steps are carried out. The <em>message</em> attribute of the record is computed using <em>msg</em> % <em>args</em>. If the formatting string contains <tt class="docutils literal"><span class="pre">'(asctime)'</span></tt>, <a class="reference internal" href="#logging.Formatter.formatTime" title="logging.Formatter.formatTime"><tt class="xref py py-meth docutils literal"><span class="pre">formatTime()</span></tt></a> is called to format the event time. If there is exception information, it is formatted using <a class="reference internal" href="#logging.Formatter.formatException" title="logging.Formatter.formatException"><tt class="xref py py-meth docutils literal"><span class="pre">formatException()</span></tt></a> and appended to the message. Note that the formatted exception information is cached in attribute <em>exc_text</em>. This is useful because the exception information can be pickled and sent across the wire, but you should be careful if you have more than one <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> subclass which customizes the formatting of exception information. In this case, you will have to clear the cached value after a formatter has done its formatting, so that the next formatter to handle the event doesn’t use the cached value but recalculates it afresh.</p> </dd></dl> <dl class="method"> <dt id="logging.Formatter.formatTime"> <tt class="descname">formatTime</tt><big>(</big><em>record</em><span class="optional">[</span>, <em>datefmt</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.Formatter.formatTime" title="Permalink to this definition">¶</a></dt> <dd><p>This method should be called from <a class="reference internal" href="functions.html#format" title="format"><tt class="xref py py-meth docutils literal"><span class="pre">format()</span></tt></a> by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behavior is as follows: if <em>datefmt</em> (a string) is specified, it is used with <a class="reference internal" href="time.html#time.strftime" title="time.strftime"><tt class="xref py py-func docutils literal"><span class="pre">time.strftime()</span></tt></a> to format the creation time of the record. Otherwise, the ISO8601 format is used. The resulting string is returned.</p> </dd></dl> <dl class="method"> <dt id="logging.Formatter.formatException"> <tt class="descname">formatException</tt><big>(</big><em>exc_info</em><big>)</big><a class="headerlink" href="#logging.Formatter.formatException" title="Permalink to this definition">¶</a></dt> <dd><p>Formats the specified exception information (a standard exception tuple as returned by <a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><tt class="xref py py-func docutils literal"><span class="pre">sys.exc_info()</span></tt></a>) as a string. This default implementation just uses <a class="reference internal" href="traceback.html#traceback.print_exception" title="traceback.print_exception"><tt class="xref py py-func docutils literal"><span class="pre">traceback.print_exception()</span></tt></a>. The resulting string is returned.</p> </dd></dl> </dd></dl> </div> <div class="section" id="filter-objects"> <span id="filter"></span><h2>15.7.16. Filter Objects<a class="headerlink" href="#filter-objects" title="Permalink to this headline">¶</a></h2> <p>Filters can be used by <tt class="xref py py-class docutils literal"><span class="pre">Handler</span></tt>s and <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt>s for more sophisticated filtering than is provided by levels. The base filter class only allows events which are below a certain point in the logger hierarchy. For example, a filter initialized with “A.B” will allow events logged by loggers “A.B”, “A.B.C”, “A.B.C.D”, “A.B.D” etc. but not “A.BB”, “B.A.B” etc. If initialized with the empty string, all events are passed.</p> <dl class="class"> <dt id="logging.Filter"> <em class="property">class </em><tt class="descclassname">logging.</tt><tt class="descname">Filter</tt><big>(</big><span class="optional">[</span><em>name</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.Filter" title="Permalink to this definition">¶</a></dt> <dd><p>Returns an instance of the <a class="reference internal" href="#logging.Filter" title="logging.Filter"><tt class="xref py py-class docutils literal"><span class="pre">Filter</span></tt></a> class. If <em>name</em> is specified, it names a logger which, together with its children, will have its events allowed through the filter. If no name is specified, allows every event.</p> <dl class="method"> <dt id="logging.Filter.filter"> <tt class="descname">filter</tt><big>(</big><em>record</em><big>)</big><a class="headerlink" href="#logging.Filter.filter" title="Permalink to this definition">¶</a></dt> <dd><p>Is the specified record to be logged? Returns zero for no, nonzero for yes. If deemed appropriate, the record may be modified in-place by this method.</p> </dd></dl> </dd></dl> </div> <div class="section" id="logrecord-objects"> <span id="log-record"></span><h2>15.7.17. LogRecord Objects<a class="headerlink" href="#logrecord-objects" title="Permalink to this headline">¶</a></h2> <p><a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> instances are created every time something is logged. They contain all the information pertinent to the event being logged. The main information passed in is in msg and args, which are combined using msg % args to create the message field of the record. The record also includes information such as when the record was created, the source line where the logging call was made, and any exception information to be logged.</p> <dl class="class"> <dt id="logging.LogRecord"> <em class="property">class </em><tt class="descclassname">logging.</tt><tt class="descname">LogRecord</tt><big>(</big><em>name</em>, <em>lvl</em>, <em>pathname</em>, <em>lineno</em>, <em>msg</em>, <em>args</em>, <em>exc_info</em><span class="optional">[</span>, <em>func</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.LogRecord" title="Permalink to this definition">¶</a></dt> <dd><p>Returns an instance of <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> initialized with interesting information. The <em>name</em> is the logger name; <em>lvl</em> is the numeric level; <em>pathname</em> is the absolute pathname of the source file in which the logging call was made; <em>lineno</em> is the line number in that file where the logging call is found; <em>msg</em> is the user-supplied message (a format string); <em>args</em> is the tuple which, together with <em>msg</em>, makes up the user message; and <em>exc_info</em> is the exception tuple obtained by calling <a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><tt class="xref py py-func docutils literal"><span class="pre">sys.exc_info()</span></tt></a> (or <a class="reference internal" href="constants.html#None" title="None"><tt class="xref py py-const xref docutils literal"><span class="pre">None</span></tt></a>, if no exception information is available). The <em>func</em> is the name of the function from which the logging call was made. If not specified, it defaults to <tt class="xref docutils literal"><span class="pre">None</span></tt>.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.5: </span><em>func</em> was added.</p> <dl class="method"> <dt id="logging.LogRecord.getMessage"> <tt class="descname">getMessage</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.LogRecord.getMessage" title="Permalink to this definition">¶</a></dt> <dd><p>Returns the message for this <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> instance after merging any user-supplied arguments with the message.</p> </dd></dl> </dd></dl> </div> <div class="section" id="loggeradapter-objects"> <span id="logger-adapter"></span><h2>15.7.18. LoggerAdapter Objects<a class="headerlink" href="#loggeradapter-objects" title="Permalink to this headline">¶</a></h2> <p class="versionadded"> <span class="versionmodified">New in version 2.6.</span></p> <p><a class="reference internal" href="#logging.LoggerAdapter" title="logging.LoggerAdapter"><tt class="xref py py-class docutils literal"><span class="pre">LoggerAdapter</span></tt></a> instances are used to conveniently pass contextual information into logging calls. For a usage example , see the section on <a class="reference external" href="#context-info">adding contextual information to your logging output</a>.</p> <dl class="class"> <dt id="logging.LoggerAdapter"> <em class="property">class </em><tt class="descclassname">logging.</tt><tt class="descname">LoggerAdapter</tt><big>(</big><em>logger</em>, <em>extra</em><big>)</big><a class="headerlink" href="#logging.LoggerAdapter" title="Permalink to this definition">¶</a></dt> <dd><p>Returns an instance of <a class="reference internal" href="#logging.LoggerAdapter" title="logging.LoggerAdapter"><tt class="xref py py-class docutils literal"><span class="pre">LoggerAdapter</span></tt></a> initialized with an underlying <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt> instance and a dict-like object.</p> <dl class="method"> <dt id="logging.LoggerAdapter.process"> <tt class="descname">process</tt><big>(</big><em>msg</em>, <em>kwargs</em><big>)</big><a class="headerlink" href="#logging.LoggerAdapter.process" title="Permalink to this definition">¶</a></dt> <dd><p>Modifies the message and/or keyword arguments passed to a logging call in order to insert contextual information. This implementation takes the object passed as <em>extra</em> to the constructor and adds it to <em>kwargs</em> using key ‘extra’. The return value is a (<em>msg</em>, <em>kwargs</em>) tuple which has the (possibly modified) versions of the arguments passed in.</p> </dd></dl> </dd></dl> <p>In addition to the above, <a class="reference internal" href="#logging.LoggerAdapter" title="logging.LoggerAdapter"><tt class="xref py py-class docutils literal"><span class="pre">LoggerAdapter</span></tt></a> supports all the logging methods of <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt>, i.e. <a class="reference internal" href="#logging.debug" title="logging.debug"><tt class="xref py py-meth docutils literal"><span class="pre">debug()</span></tt></a>, <a class="reference internal" href="#logging.info" title="logging.info"><tt class="xref py py-meth docutils literal"><span class="pre">info()</span></tt></a>, <a class="reference internal" href="#logging.warning" title="logging.warning"><tt class="xref py py-meth docutils literal"><span class="pre">warning()</span></tt></a>, <a class="reference internal" href="#logging.error" title="logging.error"><tt class="xref py py-meth docutils literal"><span class="pre">error()</span></tt></a>, <a class="reference internal" href="#logging.exception" title="logging.exception"><tt class="xref py py-meth docutils literal"><span class="pre">exception()</span></tt></a>, <a class="reference internal" href="#logging.critical" title="logging.critical"><tt class="xref py py-meth docutils literal"><span class="pre">critical()</span></tt></a> and <a class="reference internal" href="#logging.log" title="logging.log"><tt class="xref py py-meth docutils literal"><span class="pre">log()</span></tt></a>. These methods have the same signatures as their counterparts in <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt>, so you can use the two types of instances interchangeably.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.7.</span></p> <p>The <tt class="xref py py-meth docutils literal"><span class="pre">isEnabledFor()</span></tt> method was added to <a class="reference internal" href="#logging.LoggerAdapter" title="logging.LoggerAdapter"><tt class="xref py py-class docutils literal"><span class="pre">LoggerAdapter</span></tt></a>. This method delegates to the underlying logger.</p> </div> <div class="section" id="thread-safety"> <h2>15.7.19. Thread Safety<a class="headerlink" href="#thread-safety" title="Permalink to this headline">¶</a></h2> <p>The logging module is intended to be thread-safe without any special work needing to be done by its clients. It achieves this though using threading locks; there is one lock to serialize access to the module’s shared data, and each handler also creates a lock to serialize access to its underlying I/O.</p> <p>If you are implementing asynchronous signal handlers using the <a class="reference internal" href="signal.html#module-signal" title="Set handlers for asynchronous events."><tt class="xref py py-mod docutils literal"><span class="pre">signal</span></tt></a> module, you may not be able to use logging from within such handlers. This is because lock implementations in the <a class="reference internal" href="threading.html#module-threading" title="Higher-level threading interface."><tt class="xref py py-mod docutils literal"><span class="pre">threading</span></tt></a> module are not always re-entrant, and so cannot be invoked from such signal handlers.</p> </div> <div class="section" id="integration-with-the-warnings-module"> <h2>15.7.20. Integration with the warnings module<a class="headerlink" href="#integration-with-the-warnings-module" title="Permalink to this headline">¶</a></h2> <p>The <a class="reference internal" href="#logging.captureWarnings" title="logging.captureWarnings"><tt class="xref py py-func docutils literal"><span class="pre">captureWarnings()</span></tt></a> function can be used to integrate <a class="reference internal" href="#module-logging" title="Flexible error logging system for applications."><tt class="xref py py-mod docutils literal"><span class="pre">logging</span></tt></a> with the <a class="reference internal" href="warnings.html#module-warnings" title="Issue warning messages and control their disposition."><tt class="xref py py-mod docutils literal"><span class="pre">warnings</span></tt></a> module.</p> <dl class="function"> <dt id="logging.captureWarnings"> <tt class="descclassname">logging.</tt><tt class="descname">captureWarnings</tt><big>(</big><em>capture</em><big>)</big><a class="headerlink" href="#logging.captureWarnings" title="Permalink to this definition">¶</a></dt> <dd><p>This function is used to turn the capture of warnings by logging on and off.</p> <p>If <em>capture</em> is <tt class="xref docutils literal"><span class="pre">True</span></tt>, warnings issued by the <a class="reference internal" href="warnings.html#module-warnings" title="Issue warning messages and control their disposition."><tt class="xref py py-mod docutils literal"><span class="pre">warnings</span></tt></a> module will be redirected to the logging system. Specifically, a warning will be formatted using <a class="reference internal" href="warnings.html#warnings.formatwarning" title="warnings.formatwarning"><tt class="xref py py-func docutils literal"><span class="pre">warnings.formatwarning()</span></tt></a> and the resulting string logged to a logger named “py.warnings” with a severity of <tt class="docutils literal"><span class="pre">WARNING</span></tt>.</p> <p>If <em>capture</em> is <tt class="xref docutils literal"><span class="pre">False</span></tt>, the redirection of warnings to the logging system will stop, and warnings will be redirected to their original destinations (i.e. those in effect before <tt class="docutils literal"><span class="pre">captureWarnings(True)</span></tt> was called).</p> </dd></dl> </div> <div class="section" id="configuration"> <h2>15.7.21. Configuration<a class="headerlink" href="#configuration" title="Permalink to this headline">¶</a></h2> <div class="section" id="configuration-functions"> <span id="logging-config-api"></span><h3>15.7.21.1. Configuration functions<a class="headerlink" href="#configuration-functions" title="Permalink to this headline">¶</a></h3> <p>The following functions configure the logging module. They are located in the <tt class="xref py py-mod docutils literal"><span class="pre">logging.config</span></tt> module. Their use is optional — you can configure the logging module using these functions or by making calls to the main API (defined in <a class="reference internal" href="#module-logging" title="Flexible error logging system for applications."><tt class="xref py py-mod docutils literal"><span class="pre">logging</span></tt></a> itself) and defining handlers which are declared either in <a class="reference internal" href="#module-logging" title="Flexible error logging system for applications."><tt class="xref py py-mod docutils literal"><span class="pre">logging</span></tt></a> or <tt class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></tt>.</p> <dl class="function"> <dt id="logging.dictConfig"> <tt class="descclassname">logging.</tt><tt class="descname">dictConfig</tt><big>(</big><em>config</em><big>)</big><a class="headerlink" href="#logging.dictConfig" title="Permalink to this definition">¶</a></dt> <dd><p>Takes the logging configuration from a dictionary. The contents of this dictionary are described in <a class="reference internal" href="#logging-config-dictschema"><em>Configuration dictionary schema</em></a> below.</p> <p>If an error is encountered during configuration, this function will raise a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a>, <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a>, <a class="reference internal" href="exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><tt class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></tt></a> or <a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><tt class="xref py py-exc docutils literal"><span class="pre">ImportError</span></tt></a> with a suitably descriptive message. The following is a (possibly incomplete) list of conditions which will raise an error:</p> <ul class="simple"> <li>A <tt class="docutils literal"><span class="pre">level</span></tt> which is not a string or which is a string not corresponding to an actual logging level.</li> <li>A <tt class="docutils literal"><span class="pre">propagate</span></tt> value which is not a boolean.</li> <li>An id which does not have a corresponding destination.</li> <li>A non-existent handler id found during an incremental call.</li> <li>An invalid logger name.</li> <li>Inability to resolve to an internal or external object.</li> </ul> <p>Parsing is performed by the <tt class="xref py py-class docutils literal"><span class="pre">DictConfigurator</span></tt> class, whose constructor is passed the dictionary used for configuration, and has a <tt class="xref py py-meth docutils literal"><span class="pre">configure()</span></tt> method. The <tt class="xref py py-mod docutils literal"><span class="pre">logging.config</span></tt> module has a callable attribute <tt class="xref py py-attr docutils literal"><span class="pre">dictConfigClass</span></tt> which is initially set to <tt class="xref py py-class docutils literal"><span class="pre">DictConfigurator</span></tt>. You can replace the value of <tt class="xref py py-attr docutils literal"><span class="pre">dictConfigClass</span></tt> with a suitable implementation of your own.</p> <p><a class="reference internal" href="#logging.dictConfig" title="logging.dictConfig"><tt class="xref py py-func docutils literal"><span class="pre">dictConfig()</span></tt></a> calls <tt class="xref py py-attr docutils literal"><span class="pre">dictConfigClass</span></tt> passing the specified dictionary, and then calls the <tt class="xref py py-meth docutils literal"><span class="pre">configure()</span></tt> method on the returned object to put the configuration into effect:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">dictConfig</span><span class="p">(</span><span class="n">config</span><span class="p">):</span> <span class="n">dictConfigClass</span><span class="p">(</span><span class="n">config</span><span class="p">)</span><span class="o">.</span><span class="n">configure</span><span class="p">()</span> </pre></div> </div> <p>For example, a subclass of <tt class="xref py py-class docutils literal"><span class="pre">DictConfigurator</span></tt> could call <tt class="docutils literal"><span class="pre">DictConfigurator.__init__()</span></tt> in its own <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a>, then set up custom prefixes which would be usable in the subsequent <tt class="xref py py-meth docutils literal"><span class="pre">configure()</span></tt> call. <tt class="xref py py-attr docutils literal"><span class="pre">dictConfigClass</span></tt> would be bound to this new subclass, and then <a class="reference internal" href="#logging.dictConfig" title="logging.dictConfig"><tt class="xref py py-func docutils literal"><span class="pre">dictConfig()</span></tt></a> could be called exactly as in the default, uncustomized state.</p> </dd></dl> <dl class="function"> <dt id="logging.fileConfig"> <tt class="descclassname">logging.</tt><tt class="descname">fileConfig</tt><big>(</big><em>fname</em><span class="optional">[</span>, <em>defaults</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.fileConfig" title="Permalink to this definition">¶</a></dt> <dd><p>Reads the logging configuration from a <a class="reference internal" href="configparser.html#module-ConfigParser" title="Configuration file parser."><tt class="xref py py-mod docutils literal"><span class="pre">ConfigParser</span></tt></a>-format file named <em>fname</em>. This function can be called several times from an application, allowing an end user to select from various pre-canned configurations (if the developer provides a mechanism to present the choices and load the chosen configuration). Defaults to be passed to the ConfigParser can be specified in the <em>defaults</em> argument.</p> </dd></dl> <dl class="function"> <dt id="logging.listen"> <tt class="descclassname">logging.</tt><tt class="descname">listen</tt><big>(</big><span class="optional">[</span><em>port</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#logging.listen" title="Permalink to this definition">¶</a></dt> <dd><p>Starts up a socket server on the specified port, and listens for new configurations. If no port is specified, the module’s default <tt class="xref py py-const docutils literal"><span class="pre">DEFAULT_LOGGING_CONFIG_PORT</span></tt> is used. Logging configurations will be sent as a file suitable for processing by <a class="reference internal" href="#logging.fileConfig" title="logging.fileConfig"><tt class="xref py py-func docutils literal"><span class="pre">fileConfig()</span></tt></a>. Returns a <tt class="xref py py-class docutils literal"><span class="pre">Thread</span></tt> instance on which you can call <tt class="xref py py-meth docutils literal"><span class="pre">start()</span></tt> to start the server, and which you can <tt class="xref py py-meth docutils literal"><span class="pre">join()</span></tt> when appropriate. To stop the server, call <a class="reference internal" href="#logging.stopListening" title="logging.stopListening"><tt class="xref py py-func docutils literal"><span class="pre">stopListening()</span></tt></a>.</p> <p>To send a configuration to the socket, read in the configuration file and send it to the socket as a string of bytes preceded by a four-byte length string packed in binary using <tt class="docutils literal"><span class="pre">struct.pack('>L',</span> <span class="pre">n)</span></tt>.</p> </dd></dl> <dl class="function"> <dt id="logging.stopListening"> <tt class="descclassname">logging.</tt><tt class="descname">stopListening</tt><big>(</big><big>)</big><a class="headerlink" href="#logging.stopListening" title="Permalink to this definition">¶</a></dt> <dd><p>Stops the listening server which was created with a call to <a class="reference internal" href="#logging.listen" title="logging.listen"><tt class="xref py py-func docutils literal"><span class="pre">listen()</span></tt></a>. This is typically called before calling <tt class="xref py py-meth docutils literal"><span class="pre">join()</span></tt> on the return value from <a class="reference internal" href="#logging.listen" title="logging.listen"><tt class="xref py py-func docutils literal"><span class="pre">listen()</span></tt></a>.</p> </dd></dl> </div> <div class="section" id="configuration-dictionary-schema"> <span id="logging-config-dictschema"></span><h3>15.7.21.2. Configuration dictionary schema<a class="headerlink" href="#configuration-dictionary-schema" title="Permalink to this headline">¶</a></h3> <p>Describing a logging configuration requires listing the various objects to create and the connections between them; for example, you may create a handler named “console” and then say that the logger named “startup” will send its messages to the “console” handler. These objects aren’t limited to those provided by the <a class="reference internal" href="#module-logging" title="Flexible error logging system for applications."><tt class="xref py py-mod docutils literal"><span class="pre">logging</span></tt></a> module because you might write your own formatter or handler class. The parameters to these classes may also need to include external objects such as <tt class="docutils literal"><span class="pre">sys.stderr</span></tt>. The syntax for describing these objects and connections is defined in <a class="reference internal" href="#logging-config-dict-connections"><em>Object connections</em></a> below.</p> <div class="section" id="dictionary-schema-details"> <h4>15.7.21.2.1. Dictionary Schema Details<a class="headerlink" href="#dictionary-schema-details" title="Permalink to this headline">¶</a></h4> <p>The dictionary passed to <a class="reference internal" href="#logging.dictConfig" title="logging.dictConfig"><tt class="xref py py-func docutils literal"><span class="pre">dictConfig()</span></tt></a> must contain the following keys:</p> <ul class="simple"> <li><cite>version</cite> - to be set to an integer value representing the schema version. The only valid value at present is 1, but having this key allows the schema to evolve while still preserving backwards compatibility.</li> </ul> <p>All other keys are optional, but if present they will be interpreted as described below. In all cases below where a ‘configuring dict’ is mentioned, it will be checked for the special <tt class="docutils literal"><span class="pre">'()'</span></tt> key to see if a custom instantiation is required. If so, the mechanism described in <a class="reference internal" href="#logging-config-dict-userdef"><em>User-defined objects</em></a> below is used to create an instance; otherwise, the context is used to determine what to instantiate.</p> <ul> <li><p class="first"><cite>formatters</cite> - the corresponding value will be a dict in which each key is a formatter id and each value is a dict describing how to configure the corresponding Formatter instance.</p> <p>The configuring dict is searched for keys <tt class="docutils literal"><span class="pre">format</span></tt> and <tt class="docutils literal"><span class="pre">datefmt</span></tt> (with defaults of <tt class="xref docutils literal"><span class="pre">None</span></tt>) and these are used to construct a <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">logging.Formatter</span></tt></a> instance.</p> </li> <li><p class="first"><cite>filters</cite> - the corresponding value will be a dict in which each key is a filter id and each value is a dict describing how to configure the corresponding Filter instance.</p> <p>The configuring dict is searched for the key <tt class="docutils literal"><span class="pre">name</span></tt> (defaulting to the empty string) and this is used to construct a <a class="reference internal" href="#logging.Filter" title="logging.Filter"><tt class="xref py py-class docutils literal"><span class="pre">logging.Filter</span></tt></a> instance.</p> </li> <li><p class="first"><cite>handlers</cite> - the corresponding value will be a dict in which each key is a handler id and each value is a dict describing how to configure the corresponding Handler instance.</p> <p>The configuring dict is searched for the following keys:</p> <ul class="simple"> <li><tt class="docutils literal"><span class="pre">class</span></tt> (mandatory). This is the fully qualified name of the handler class.</li> <li><tt class="docutils literal"><span class="pre">level</span></tt> (optional). The level of the handler.</li> <li><tt class="docutils literal"><span class="pre">formatter</span></tt> (optional). The id of the formatter for this handler.</li> <li><tt class="docutils literal"><span class="pre">filters</span></tt> (optional). A list of ids of the filters for this handler.</li> </ul> <p>All <em>other</em> keys are passed through as keyword arguments to the handler’s constructor. For example, given the snippet:</p> <div class="highlight-python"><pre>handlers: console: class : logging.StreamHandler formatter: brief level : INFO filters: [allow_foo] stream : ext://sys.stdout file: class : logging.handlers.RotatingFileHandler formatter: precise filename: logconfig.log maxBytes: 1024 backupCount: 3</pre> </div> <p>the handler with id <tt class="docutils literal"><span class="pre">console</span></tt> is instantiated as a <a class="reference internal" href="#logging.StreamHandler" title="logging.StreamHandler"><tt class="xref py py-class docutils literal"><span class="pre">logging.StreamHandler</span></tt></a>, using <tt class="docutils literal"><span class="pre">sys.stdout</span></tt> as the underlying stream. The handler with id <tt class="docutils literal"><span class="pre">file</span></tt> is instantiated as a <a class="reference internal" href="#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><tt class="xref py py-class docutils literal"><span class="pre">logging.handlers.RotatingFileHandler</span></tt></a> with the keyword arguments <tt class="docutils literal"><span class="pre">filename='logconfig.log',</span> <span class="pre">maxBytes=1024,</span> <span class="pre">backupCount=3</span></tt>.</p> </li> <li><p class="first"><cite>loggers</cite> - the corresponding value will be a dict in which each key is a logger name and each value is a dict describing how to configure the corresponding Logger instance.</p> <p>The configuring dict is searched for the following keys:</p> <ul class="simple"> <li><tt class="docutils literal"><span class="pre">level</span></tt> (optional). The level of the logger.</li> <li><tt class="docutils literal"><span class="pre">propagate</span></tt> (optional). The propagation setting of the logger.</li> <li><tt class="docutils literal"><span class="pre">filters</span></tt> (optional). A list of ids of the filters for this logger.</li> <li><tt class="docutils literal"><span class="pre">handlers</span></tt> (optional). A list of ids of the handlers for this logger.</li> </ul> <p>The specified loggers will be configured according to the level, propagation, filters and handlers specified.</p> </li> <li><p class="first"><cite>root</cite> - this will be the configuration for the root logger. Processing of the configuration will be as for any logger, except that the <tt class="docutils literal"><span class="pre">propagate</span></tt> setting will not be applicable.</p> </li> <li><p class="first"><cite>incremental</cite> - whether the configuration is to be interpreted as incremental to the existing configuration. This value defaults to <tt class="xref docutils literal"><span class="pre">False</span></tt>, which means that the specified configuration replaces the existing configuration with the same semantics as used by the existing <a class="reference internal" href="#logging.fileConfig" title="logging.fileConfig"><tt class="xref py py-func docutils literal"><span class="pre">fileConfig()</span></tt></a> API.</p> <p>If the specified value is <tt class="xref docutils literal"><span class="pre">True</span></tt>, the configuration is processed as described in the section on <a class="reference internal" href="#logging-config-dict-incremental"><em>Incremental Configuration</em></a>.</p> </li> <li><p class="first"><cite>disable_existing_loggers</cite> - whether any existing loggers are to be disabled. This setting mirrors the parameter of the same name in <a class="reference internal" href="#logging.fileConfig" title="logging.fileConfig"><tt class="xref py py-func docutils literal"><span class="pre">fileConfig()</span></tt></a>. If absent, this parameter defaults to <tt class="xref docutils literal"><span class="pre">True</span></tt>. This value is ignored if <cite>incremental</cite> is <tt class="xref docutils literal"><span class="pre">True</span></tt>.</p> </li> </ul> </div> <div class="section" id="incremental-configuration"> <span id="logging-config-dict-incremental"></span><h4>15.7.21.2.2. Incremental Configuration<a class="headerlink" href="#incremental-configuration" title="Permalink to this headline">¶</a></h4> <p>It is difficult to provide complete flexibility for incremental configuration. For example, because objects such as filters and formatters are anonymous, once a configuration is set up, it is not possible to refer to such anonymous objects when augmenting a configuration.</p> <p>Furthermore, there is not a compelling case for arbitrarily altering the object graph of loggers, handlers, filters, formatters at run-time, once a configuration is set up; the verbosity of loggers and handlers can be controlled just by setting levels (and, in the case of loggers, propagation flags). Changing the object graph arbitrarily in a safe way is problematic in a multi-threaded environment; while not impossible, the benefits are not worth the complexity it adds to the implementation.</p> <p>Thus, when the <tt class="docutils literal"><span class="pre">incremental</span></tt> key of a configuration dict is present and is <tt class="xref docutils literal"><span class="pre">True</span></tt>, the system will completely ignore any <tt class="docutils literal"><span class="pre">formatters</span></tt> and <tt class="docutils literal"><span class="pre">filters</span></tt> entries, and process only the <tt class="docutils literal"><span class="pre">level</span></tt> settings in the <tt class="docutils literal"><span class="pre">handlers</span></tt> entries, and the <tt class="docutils literal"><span class="pre">level</span></tt> and <tt class="docutils literal"><span class="pre">propagate</span></tt> settings in the <tt class="docutils literal"><span class="pre">loggers</span></tt> and <tt class="docutils literal"><span class="pre">root</span></tt> entries.</p> <p>Using a value in the configuration dict lets configurations to be sent over the wire as pickled dicts to a socket listener. Thus, the logging verbosity of a long-running application can be altered over time with no need to stop and restart the application.</p> </div> <div class="section" id="object-connections"> <span id="logging-config-dict-connections"></span><h4>15.7.21.2.3. Object connections<a class="headerlink" href="#object-connections" title="Permalink to this headline">¶</a></h4> <p>The schema describes a set of logging objects - loggers, handlers, formatters, filters - which are connected to each other in an object graph. Thus, the schema needs to represent connections between the objects. For example, say that, once configured, a particular logger has attached to it a particular handler. For the purposes of this discussion, we can say that the logger represents the source, and the handler the destination, of a connection between the two. Of course in the configured objects this is represented by the logger holding a reference to the handler. In the configuration dict, this is done by giving each destination object an id which identifies it unambiguously, and then using the id in the source object’s configuration to indicate that a connection exists between the source and the destination object with that id.</p> <p>So, for example, consider the following YAML snippet:</p> <div class="highlight-python"><pre>formatters: brief: # configuration for formatter with id 'brief' goes here precise: # configuration for formatter with id 'precise' goes here handlers: h1: #This is an id # configuration of handler with id 'h1' goes here formatter: brief h2: #This is another id # configuration of handler with id 'h2' goes here formatter: precise loggers: foo.bar.baz: # other configuration for logger 'foo.bar.baz' handlers: [h1, h2]</pre> </div> <p>(Note: YAML used here because it’s a little more readable than the equivalent Python source form for the dictionary.)</p> <p>The ids for loggers are the logger names which would be used programmatically to obtain a reference to those loggers, e.g. <tt class="docutils literal"><span class="pre">foo.bar.baz</span></tt>. The ids for Formatters and Filters can be any string value (such as <tt class="docutils literal"><span class="pre">brief</span></tt>, <tt class="docutils literal"><span class="pre">precise</span></tt> above) and they are transient, in that they are only meaningful for processing the configuration dictionary and used to determine connections between objects, and are not persisted anywhere when the configuration call is complete.</p> <p>The above snippet indicates that logger named <tt class="docutils literal"><span class="pre">foo.bar.baz</span></tt> should have two handlers attached to it, which are described by the handler ids <tt class="docutils literal"><span class="pre">h1</span></tt> and <tt class="docutils literal"><span class="pre">h2</span></tt>. The formatter for <tt class="docutils literal"><span class="pre">h1</span></tt> is that described by id <tt class="docutils literal"><span class="pre">brief</span></tt>, and the formatter for <tt class="docutils literal"><span class="pre">h2</span></tt> is that described by id <tt class="docutils literal"><span class="pre">precise</span></tt>.</p> </div> <div class="section" id="user-defined-objects"> <span id="logging-config-dict-userdef"></span><h4>15.7.21.2.4. User-defined objects<a class="headerlink" href="#user-defined-objects" title="Permalink to this headline">¶</a></h4> <p>The schema supports user-defined objects for handlers, filters and formatters. (Loggers do not need to have different types for different instances, so there is no support in this configuration schema for user-defined logger classes.)</p> <p>Objects to be configured are described by dictionaries which detail their configuration. In some places, the logging system will be able to infer from the context how an object is to be instantiated, but when a user-defined object is to be instantiated, the system will not know how to do this. In order to provide complete flexibility for user-defined object instantiation, the user needs to provide a ‘factory’ - a callable which is called with a configuration dictionary and which returns the instantiated object. This is signalled by an absolute import path to the factory being made available under the special key <tt class="docutils literal"><span class="pre">'()'</span></tt>. Here’s a concrete example:</p> <div class="highlight-python"><pre>formatters: brief: format: '%(message)s' default: format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s' datefmt: '%Y-%m-%d %H:%M:%S' custom: (): my.package.customFormatterFactory bar: baz spam: 99.9 answer: 42</pre> </div> <p>The above YAML snippet defines three formatters. The first, with id <tt class="docutils literal"><span class="pre">brief</span></tt>, is a standard <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">logging.Formatter</span></tt></a> instance with the specified format string. The second, with id <tt class="docutils literal"><span class="pre">default</span></tt>, has a longer format and also defines the time format explicitly, and will result in a <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">logging.Formatter</span></tt></a> initialized with those two format strings. Shown in Python source form, the <tt class="docutils literal"><span class="pre">brief</span></tt> and <tt class="docutils literal"><span class="pre">default</span></tt> formatters have configuration sub-dictionaries:</p> <div class="highlight-python"><div class="highlight"><pre><span class="p">{</span> <span class="s">'format'</span> <span class="p">:</span> <span class="s">'</span><span class="si">%(message)s</span><span class="s">'</span> <span class="p">}</span> </pre></div> </div> <p>and:</p> <div class="highlight-python"><div class="highlight"><pre><span class="p">{</span> <span class="s">'format'</span> <span class="p">:</span> <span class="s">'</span><span class="si">%(asctime)s</span><span class="s"> </span><span class="si">%(levelname)-8s</span><span class="s"> </span><span class="si">%(name)-15s</span><span class="s"> </span><span class="si">%(message)s</span><span class="s">'</span><span class="p">,</span> <span class="s">'datefmt'</span> <span class="p">:</span> <span class="s">'%Y-%m-</span><span class="si">%d</span><span class="s"> %H:%M:%S'</span> <span class="p">}</span> </pre></div> </div> <p>respectively, and as these dictionaries do not contain the special key <tt class="docutils literal"><span class="pre">'()'</span></tt>, the instantiation is inferred from the context: as a result, standard <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">logging.Formatter</span></tt></a> instances are created. The configuration sub-dictionary for the third formatter, with id <tt class="docutils literal"><span class="pre">custom</span></tt>, is:</p> <div class="highlight-python"><div class="highlight"><pre><span class="p">{</span> <span class="s">'()'</span> <span class="p">:</span> <span class="s">'my.package.customFormatterFactory'</span><span class="p">,</span> <span class="s">'bar'</span> <span class="p">:</span> <span class="s">'baz'</span><span class="p">,</span> <span class="s">'spam'</span> <span class="p">:</span> <span class="mf">99.9</span><span class="p">,</span> <span class="s">'answer'</span> <span class="p">:</span> <span class="mi">42</span> <span class="p">}</span> </pre></div> </div> <p>and this contains the special key <tt class="docutils literal"><span class="pre">'()'</span></tt>, which means that user-defined instantiation is wanted. In this case, the specified factory callable will be used. If it is an actual callable it will be used directly - otherwise, if you specify a string (as in the example) the actual callable will be located using normal import mechanisms. The callable will be called with the <strong>remaining</strong> items in the configuration sub-dictionary as keyword arguments. In the above example, the formatter with id <tt class="docutils literal"><span class="pre">custom</span></tt> will be assumed to be returned by the call:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">my</span><span class="o">.</span><span class="n">package</span><span class="o">.</span><span class="n">customFormatterFactory</span><span class="p">(</span><span class="n">bar</span><span class="o">=</span><span class="s">'baz'</span><span class="p">,</span> <span class="n">spam</span><span class="o">=</span><span class="mf">99.9</span><span class="p">,</span> <span class="n">answer</span><span class="o">=</span><span class="mi">42</span><span class="p">)</span> </pre></div> </div> <p>The key <tt class="docutils literal"><span class="pre">'()'</span></tt> has been used as the special key because it is not a valid keyword parameter name, and so will not clash with the names of the keyword arguments used in the call. The <tt class="docutils literal"><span class="pre">'()'</span></tt> also serves as a mnemonic that the corresponding value is a callable.</p> </div> <div class="section" id="access-to-external-objects"> <span id="logging-config-dict-externalobj"></span><h4>15.7.21.2.5. Access to external objects<a class="headerlink" href="#access-to-external-objects" title="Permalink to this headline">¶</a></h4> <p>There are times where a configuration needs to refer to objects external to the configuration, for example <tt class="docutils literal"><span class="pre">sys.stderr</span></tt>. If the configuration dict is constructed using Python code, this is straightforward, but a problem arises when the configuration is provided via a text file (e.g. JSON, YAML). In a text file, there is no standard way to distinguish <tt class="docutils literal"><span class="pre">sys.stderr</span></tt> from the literal string <tt class="docutils literal"><span class="pre">'sys.stderr'</span></tt>. To facilitate this distinction, the configuration system looks for certain special prefixes in string values and treat them specially. For example, if the literal string <tt class="docutils literal"><span class="pre">'ext://sys.stderr'</span></tt> is provided as a value in the configuration, then the <tt class="docutils literal"><span class="pre">ext://</span></tt> will be stripped off and the remainder of the value processed using normal import mechanisms.</p> <p>The handling of such prefixes is done in a way analogous to protocol handling: there is a generic mechanism to look for prefixes which match the regular expression <tt class="docutils literal"><span class="pre">^(?P<prefix>[a-z]+)://(?P<suffix>.*)$</span></tt> whereby, if the <tt class="docutils literal"><span class="pre">prefix</span></tt> is recognised, the <tt class="docutils literal"><span class="pre">suffix</span></tt> is processed in a prefix-dependent manner and the result of the processing replaces the string value. If the prefix is not recognised, then the string value will be left as-is.</p> </div> <div class="section" id="access-to-internal-objects"> <span id="logging-config-dict-internalobj"></span><h4>15.7.21.2.6. Access to internal objects<a class="headerlink" href="#access-to-internal-objects" title="Permalink to this headline">¶</a></h4> <p>As well as external objects, there is sometimes also a need to refer to objects in the configuration. This will be done implicitly by the configuration system for things that it knows about. For example, the string value <tt class="docutils literal"><span class="pre">'DEBUG'</span></tt> for a <tt class="docutils literal"><span class="pre">level</span></tt> in a logger or handler will automatically be converted to the value <tt class="docutils literal"><span class="pre">logging.DEBUG</span></tt>, and the <tt class="docutils literal"><span class="pre">handlers</span></tt>, <tt class="docutils literal"><span class="pre">filters</span></tt> and <tt class="docutils literal"><span class="pre">formatter</span></tt> entries will take an object id and resolve to the appropriate destination object.</p> <p>However, a more generic mechanism is needed for user-defined objects which are not known to the <a class="reference internal" href="#module-logging" title="Flexible error logging system for applications."><tt class="xref py py-mod docutils literal"><span class="pre">logging</span></tt></a> module. For example, consider <a class="reference internal" href="#logging.handlers.MemoryHandler" title="logging.handlers.MemoryHandler"><tt class="xref py py-class docutils literal"><span class="pre">logging.handlers.MemoryHandler</span></tt></a>, which takes a <tt class="docutils literal"><span class="pre">target</span></tt> argument which is another handler to delegate to. Since the system already knows about this class, then in the configuration, the given <tt class="docutils literal"><span class="pre">target</span></tt> just needs to be the object id of the relevant target handler, and the system will resolve to the handler from the id. If, however, a user defines a <tt class="docutils literal"><span class="pre">my.package.MyHandler</span></tt> which has an <tt class="docutils literal"><span class="pre">alternate</span></tt> handler, the configuration system would not know that the <tt class="docutils literal"><span class="pre">alternate</span></tt> referred to a handler. To cater for this, a generic resolution system allows the user to specify:</p> <div class="highlight-python"><pre>handlers: file: # configuration of file handler goes here custom: (): my.package.MyHandler alternate: cfg://handlers.file</pre> </div> <p>The literal string <tt class="docutils literal"><span class="pre">'cfg://handlers.file'</span></tt> will be resolved in an analogous way to strings with the <tt class="docutils literal"><span class="pre">ext://</span></tt> prefix, but looking in the configuration itself rather than the import namespace. The mechanism allows access by dot or by index, in a similar way to that provided by <tt class="docutils literal"><span class="pre">str.format</span></tt>. Thus, given the following snippet:</p> <div class="highlight-python"><pre>handlers: email: class: logging.handlers.SMTPHandler mailhost: localhost fromaddr: my_app@domain.tld toaddrs: - support_team@domain.tld - dev_team@domain.tld subject: Houston, we have a problem.</pre> </div> <p>in the configuration, the string <tt class="docutils literal"><span class="pre">'cfg://handlers'</span></tt> would resolve to the dict with key <tt class="docutils literal"><span class="pre">handlers</span></tt>, the string <tt class="docutils literal"><span class="pre">'cfg://handlers.email</span></tt> would resolve to the dict with key <tt class="docutils literal"><span class="pre">email</span></tt> in the <tt class="docutils literal"><span class="pre">handlers</span></tt> dict, and so on. The string <tt class="docutils literal"><span class="pre">'cfg://handlers.email.toaddrs[1]</span></tt> would resolve to <tt class="docutils literal"><span class="pre">'dev_team.domain.tld'</span></tt> and the string <tt class="docutils literal"><span class="pre">'cfg://handlers.email.toaddrs[0]'</span></tt> would resolve to the value <tt class="docutils literal"><span class="pre">'support_team@domain.tld'</span></tt>. The <tt class="docutils literal"><span class="pre">subject</span></tt> value could be accessed using either <tt class="docutils literal"><span class="pre">'cfg://handlers.email.subject'</span></tt> or, equivalently, <tt class="docutils literal"><span class="pre">'cfg://handlers.email[subject]'</span></tt>. The latter form only needs to be used if the key contains spaces or non-alphanumeric characters. If an index value consists only of decimal digits, access will be attempted using the corresponding integer value, falling back to the string value if needed.</p> <p>Given a string <tt class="docutils literal"><span class="pre">cfg://handlers.myhandler.mykey.123</span></tt>, this will resolve to <tt class="docutils literal"><span class="pre">config_dict['handlers']['myhandler']['mykey']['123']</span></tt>. If the string is specified as <tt class="docutils literal"><span class="pre">cfg://handlers.myhandler.mykey[123]</span></tt>, the system will attempt to retrieve the value from <tt class="docutils literal"><span class="pre">config_dict['handlers']['myhandler']['mykey'][123]</span></tt>, and fall back to <tt class="docutils literal"><span class="pre">config_dict['handlers']['myhandler']['mykey']['123']</span></tt> if that fails.</p> </div> </div> <div class="section" id="configuration-file-format"> <span id="logging-config-fileformat"></span><h3>15.7.21.3. Configuration file format<a class="headerlink" href="#configuration-file-format" title="Permalink to this headline">¶</a></h3> <p>The configuration file format understood by <a class="reference internal" href="#logging.fileConfig" title="logging.fileConfig"><tt class="xref py py-func docutils literal"><span class="pre">fileConfig()</span></tt></a> is based on <a class="reference internal" href="configparser.html#module-ConfigParser" title="Configuration file parser."><tt class="xref py py-mod docutils literal"><span class="pre">ConfigParser</span></tt></a> functionality. The file must contain sections called <tt class="docutils literal"><span class="pre">[loggers]</span></tt>, <tt class="docutils literal"><span class="pre">[handlers]</span></tt> and <tt class="docutils literal"><span class="pre">[formatters]</span></tt> which identify by name the entities of each type which are defined in the file. For each such entity, there is a separate section which identifies how that entity is configured. Thus, for a logger named <tt class="docutils literal"><span class="pre">log01</span></tt> in the <tt class="docutils literal"><span class="pre">[loggers]</span></tt> section, the relevant configuration details are held in a section <tt class="docutils literal"><span class="pre">[logger_log01]</span></tt>. Similarly, a handler called <tt class="docutils literal"><span class="pre">hand01</span></tt> in the <tt class="docutils literal"><span class="pre">[handlers]</span></tt> section will have its configuration held in a section called <tt class="docutils literal"><span class="pre">[handler_hand01]</span></tt>, while a formatter called <tt class="docutils literal"><span class="pre">form01</span></tt> in the <tt class="docutils literal"><span class="pre">[formatters]</span></tt> section will have its configuration specified in a section called <tt class="docutils literal"><span class="pre">[formatter_form01]</span></tt>. The root logger configuration must be specified in a section called <tt class="docutils literal"><span class="pre">[logger_root]</span></tt>.</p> <p>Examples of these sections in the file are given below.</p> <div class="highlight-python"><div class="highlight"><pre><span class="p">[</span><span class="n">loggers</span><span class="p">]</span> <span class="n">keys</span><span class="o">=</span><span class="n">root</span><span class="p">,</span><span class="n">log02</span><span class="p">,</span><span class="n">log03</span><span class="p">,</span><span class="n">log04</span><span class="p">,</span><span class="n">log05</span><span class="p">,</span><span class="n">log06</span><span class="p">,</span><span class="n">log07</span> <span class="p">[</span><span class="n">handlers</span><span class="p">]</span> <span class="n">keys</span><span class="o">=</span><span class="n">hand01</span><span class="p">,</span><span class="n">hand02</span><span class="p">,</span><span class="n">hand03</span><span class="p">,</span><span class="n">hand04</span><span class="p">,</span><span class="n">hand05</span><span class="p">,</span><span class="n">hand06</span><span class="p">,</span><span class="n">hand07</span><span class="p">,</span><span class="n">hand08</span><span class="p">,</span><span class="n">hand09</span> <span class="p">[</span><span class="n">formatters</span><span class="p">]</span> <span class="n">keys</span><span class="o">=</span><span class="n">form01</span><span class="p">,</span><span class="n">form02</span><span class="p">,</span><span class="n">form03</span><span class="p">,</span><span class="n">form04</span><span class="p">,</span><span class="n">form05</span><span class="p">,</span><span class="n">form06</span><span class="p">,</span><span class="n">form07</span><span class="p">,</span><span class="n">form08</span><span class="p">,</span><span class="n">form09</span> </pre></div> </div> <p>The root logger must specify a level and a list of handlers. An example of a root logger section is given below.</p> <div class="highlight-python"><div class="highlight"><pre><span class="p">[</span><span class="n">logger_root</span><span class="p">]</span> <span class="n">level</span><span class="o">=</span><span class="n">NOTSET</span> <span class="n">handlers</span><span class="o">=</span><span class="n">hand01</span> </pre></div> </div> <p>The <tt class="docutils literal"><span class="pre">level</span></tt> entry can be one of <tt class="docutils literal"><span class="pre">DEBUG,</span> <span class="pre">INFO,</span> <span class="pre">WARNING,</span> <span class="pre">ERROR,</span> <span class="pre">CRITICAL</span></tt> or <tt class="docutils literal"><span class="pre">NOTSET</span></tt>. For the root logger only, <tt class="docutils literal"><span class="pre">NOTSET</span></tt> means that all messages will be logged. Level values are <a class="reference internal" href="functions.html#eval" title="eval"><tt class="xref py py-func docutils literal"><span class="pre">eval()</span></tt></a>uated in the context of the <tt class="docutils literal"><span class="pre">logging</span></tt> package’s namespace.</p> <p>The <tt class="docutils literal"><span class="pre">handlers</span></tt> entry is a comma-separated list of handler names, which must appear in the <tt class="docutils literal"><span class="pre">[handlers]</span></tt> section. These names must appear in the <tt class="docutils literal"><span class="pre">[handlers]</span></tt> section and have corresponding sections in the configuration file.</p> <p>For loggers other than the root logger, some additional information is required. This is illustrated by the following example.</p> <div class="highlight-python"><div class="highlight"><pre><span class="p">[</span><span class="n">logger_parser</span><span class="p">]</span> <span class="n">level</span><span class="o">=</span><span class="n">DEBUG</span> <span class="n">handlers</span><span class="o">=</span><span class="n">hand01</span> <span class="n">propagate</span><span class="o">=</span><span class="mi">1</span> <span class="n">qualname</span><span class="o">=</span><span class="n">compiler</span><span class="o">.</span><span class="n">parser</span> </pre></div> </div> <p>The <tt class="docutils literal"><span class="pre">level</span></tt> and <tt class="docutils literal"><span class="pre">handlers</span></tt> entries are interpreted as for the root logger, except that if a non-root logger’s level is specified as <tt class="docutils literal"><span class="pre">NOTSET</span></tt>, the system consults loggers higher up the hierarchy to determine the effective level of the logger. The <tt class="docutils literal"><span class="pre">propagate</span></tt> entry is set to 1 to indicate that messages must propagate to handlers higher up the logger hierarchy from this logger, or 0 to indicate that messages are <strong>not</strong> propagated to handlers up the hierarchy. The <tt class="docutils literal"><span class="pre">qualname</span></tt> entry is the hierarchical channel name of the logger, that is to say the name used by the application to get the logger.</p> <p>Sections which specify handler configuration are exemplified by the following.</p> <div class="highlight-python"><pre>[handler_hand01] class=StreamHandler level=NOTSET formatter=form01 args=(sys.stdout,)</pre> </div> <p>The <tt class="docutils literal"><span class="pre">class</span></tt> entry indicates the handler’s class (as determined by <a class="reference internal" href="functions.html#eval" title="eval"><tt class="xref py py-func docutils literal"><span class="pre">eval()</span></tt></a> in the <tt class="docutils literal"><span class="pre">logging</span></tt> package’s namespace). The <tt class="docutils literal"><span class="pre">level</span></tt> is interpreted as for loggers, and <tt class="docutils literal"><span class="pre">NOTSET</span></tt> is taken to mean “log everything”.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.6: </span>Added support for resolving the handler’s class as a dotted module and class name.</p> <p>The <tt class="docutils literal"><span class="pre">formatter</span></tt> entry indicates the key name of the formatter for this handler. If blank, a default formatter (<tt class="docutils literal"><span class="pre">logging._defaultFormatter</span></tt>) is used. If a name is specified, it must appear in the <tt class="docutils literal"><span class="pre">[formatters]</span></tt> section and have a corresponding section in the configuration file.</p> <p>The <tt class="docutils literal"><span class="pre">args</span></tt> entry, when <a class="reference internal" href="functions.html#eval" title="eval"><tt class="xref py py-func docutils literal"><span class="pre">eval()</span></tt></a>uated in the context of the <tt class="docutils literal"><span class="pre">logging</span></tt> package’s namespace, is the list of arguments to the constructor for the handler class. Refer to the constructors for the relevant handlers, or to the examples below, to see how typical entries are constructed.</p> <div class="highlight-python"><pre>[handler_hand02] class=FileHandler level=DEBUG formatter=form02 args=('python.log', 'w') [handler_hand03] class=handlers.SocketHandler level=INFO formatter=form03 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT) [handler_hand04] class=handlers.DatagramHandler level=WARN formatter=form04 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT) [handler_hand05] class=handlers.SysLogHandler level=ERROR formatter=form05 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER) [handler_hand06] class=handlers.NTEventLogHandler level=CRITICAL formatter=form06 args=('Python Application', '', 'Application') [handler_hand07] class=handlers.SMTPHandler level=WARN formatter=form07 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject') [handler_hand08] class=handlers.MemoryHandler level=NOTSET formatter=form08 target= args=(10, ERROR) [handler_hand09] class=handlers.HTTPHandler level=NOTSET formatter=form09 args=('localhost:9022', '/log', 'GET')</pre> </div> <p>Sections which specify formatter configuration are typified by the following.</p> <div class="highlight-python"><pre>[formatter_form01] format=F1 %(asctime)s %(levelname)s %(message)s datefmt= class=logging.Formatter</pre> </div> <p>The <tt class="docutils literal"><span class="pre">format</span></tt> entry is the overall format string, and the <tt class="docutils literal"><span class="pre">datefmt</span></tt> entry is the <tt class="xref py py-func docutils literal"><span class="pre">strftime()</span></tt>-compatible date/time format string. If empty, the package substitutes ISO8601 format date/times, which is almost equivalent to specifying the date format string <tt class="docutils literal"><span class="pre">"%Y-%m-%d</span> <span class="pre">%H:%M:%S"</span></tt>. The ISO8601 format also specifies milliseconds, which are appended to the result of using the above format string, with a comma separator. An example time in ISO8601 format is <tt class="docutils literal"><span class="pre">2003-01-23</span> <span class="pre">00:29:50,411</span></tt>.</p> <p>The <tt class="docutils literal"><span class="pre">class</span></tt> entry is optional. It indicates the name of the formatter’s class (as a dotted module and class name.) This option is useful for instantiating a <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> subclass. Subclasses of <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> can present exception tracebacks in an expanded or condensed format.</p> </div> <div class="section" id="configuration-server-example"> <h3>15.7.21.4. Configuration server example<a class="headerlink" href="#configuration-server-example" title="Permalink to this headline">¶</a></h3> <p>Here is an example of a module using the logging configuration server:</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="kn">import</span> <span class="nn">time</span> <span class="kn">import</span> <span class="nn">os</span> <span class="c"># read initial config file</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 and start listener on port 9999</span> <span class="n">t</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">listen</span><span class="p">(</span><span class="mi">9999</span><span class="p">)</span> <span class="n">t</span><span class="o">.</span><span class="n">start</span><span class="p">()</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="k">try</span><span class="p">:</span> <span class="c"># loop through logging calls to see the difference</span> <span class="c"># new configurations make, until Ctrl+C is pressed</span> <span class="k">while</span> <span class="bp">True</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">"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> <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span> <span class="k">except</span> <span class="ne">KeyboardInterrupt</span><span class="p">:</span> <span class="c"># cleanup</span> <span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">stopListening</span><span class="p">()</span> <span class="n">t</span><span class="o">.</span><span class="n">join</span><span class="p">()</span> </pre></div> </div> <p>And here is a script that takes a filename and sends that file to the server, properly preceded with the binary-encoded length, as the new logging configuration:</p> <div class="highlight-python"><div class="highlight"><pre><span class="c">#!/usr/bin/env python</span> <span class="kn">import</span> <span class="nn">socket</span><span class="o">,</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">struct</span> <span class="n">data_to_send</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="s">"r"</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">()</span> <span class="n">HOST</span> <span class="o">=</span> <span class="s">'localhost'</span> <span class="n">PORT</span> <span class="o">=</span> <span class="mi">9999</span> <span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span> <span class="k">print</span> <span class="s">"connecting..."</span> <span class="n">s</span><span class="o">.</span><span class="n">connect</span><span class="p">((</span><span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span><span class="p">))</span> <span class="k">print</span> <span class="s">"sending config..."</span> <span class="n">s</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="n">struct</span><span class="o">.</span><span class="n">pack</span><span class="p">(</span><span class="s">">L"</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">data_to_send</span><span class="p">)))</span> <span class="n">s</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="n">data_to_send</span><span class="p">)</span> <span class="n">s</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> <span class="k">print</span> <span class="s">"complete"</span> </pre></div> </div> </div> </div> <div class="section" id="more-examples"> <h2>15.7.22. More examples<a class="headerlink" href="#more-examples" title="Permalink to this headline">¶</a></h2> <div class="section" id="multiple-handlers-and-formatters"> <h3>15.7.22.1. Multiple handlers and formatters<a class="headerlink" href="#multiple-handlers-and-formatters" title="Permalink to this headline">¶</a></h3> <p>Loggers are plain Python objects. The <tt class="xref py py-func docutils literal"><span class="pre">addHandler()</span></tt> method has no minimum or maximum quota for the number of handlers you may add. Sometimes it will be beneficial for an application to log all messages of all severities to a text file while simultaneously logging errors or above to the console. To set this up, simply configure the appropriate handlers. The logging calls in the application code will remain unchanged. Here is a slight modification to the previous simple module-based configuration example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</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 file handler which logs even debug messages</span> <span class="n">fh</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">FileHandler</span><span class="p">(</span><span class="s">"spam.log"</span><span class="p">)</span> <span class="n">fh</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 with a higher log level</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">ERROR</span><span class="p">)</span> <span class="c"># create formatter and add it to the handlers</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="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="n">fh</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 the handlers 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="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">fh</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>Notice that the “application” code does not care about multiple handlers. All that changed was the addition and configuration of a new handler named <em>fh</em>.</p> <p>The ability to create new handlers with higher- or lower-severity filters can be very helpful when writing and testing an application. Instead of using many <tt class="docutils literal"><span class="pre">print</span></tt> statements for debugging, use <tt class="docutils literal"><span class="pre">logger.debug</span></tt>: Unlike the print statements, which you will have to delete or comment out later, the logger.debug statements can remain intact in the source code and remain dormant until you need them again. At that time, the only change that needs to happen is to modify the severity level of the logger and/or handler to debug.</p> </div> <div class="section" id="using-logging-in-multiple-modules"> <h3>15.7.22.2. Using logging in multiple modules<a class="headerlink" href="#using-logging-in-multiple-modules" title="Permalink to this headline">¶</a></h3> <p>It was mentioned above that multiple calls to <tt class="docutils literal"><span class="pre">logging.getLogger('someLogger')</span></tt> return a reference to the same logger object. This is true not only within the same module, but also across modules as long as it is in the same Python interpreter process. It is true for references to the same object; additionally, application code can define and configure a parent logger in one module and create (but not configure) a child logger in a separate module, and all logger calls to the child will pass up to the parent. Here is a main module:</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">auxiliary_module</span> <span class="c"># create logger with "spam_application"</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">"spam_application"</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 file handler which logs even debug messages</span> <span class="n">fh</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">FileHandler</span><span class="p">(</span><span class="s">"spam.log"</span><span class="p">)</span> <span class="n">fh</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 with a higher log level</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">ERROR</span><span class="p">)</span> <span class="c"># create formatter and add it to the handlers</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="n">fh</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="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 the handlers to the logger</span> <span class="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">fh</span><span class="p">)</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="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">"creating an instance of auxiliary_module.Auxiliary"</span><span class="p">)</span> <span class="n">a</span> <span class="o">=</span> <span class="n">auxiliary_module</span><span class="o">.</span><span class="n">Auxiliary</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">"created an instance of auxiliary_module.Auxiliary"</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">"calling auxiliary_module.Auxiliary.do_something"</span><span class="p">)</span> <span class="n">a</span><span class="o">.</span><span class="n">do_something</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">"finished auxiliary_module.Auxiliary.do_something"</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">"calling auxiliary_module.some_function()"</span><span class="p">)</span> <span class="n">auxiliary_module</span><span class="o">.</span><span class="n">some_function</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">"done with auxiliary_module.some_function()"</span><span class="p">)</span> </pre></div> </div> <p>Here is the auxiliary module:</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">module_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">"spam_application.auxiliary"</span><span class="p">)</span> <span class="k">class</span> <span class="nc">Auxiliary</span><span class="p">:</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</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">"spam_application.auxiliary.Auxiliary"</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">"creating an instance of Auxiliary"</span><span class="p">)</span> <span class="k">def</span> <span class="nf">do_something</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">"doing something"</span><span class="p">)</span> <span class="n">a</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">+</span> <span class="mi">1</span> <span class="bp">self</span><span class="o">.</span><span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">"done doing something"</span><span class="p">)</span> <span class="k">def</span> <span class="nf">some_function</span><span class="p">():</span> <span class="n">module_logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">"received a call to </span><span class="se">\"</span><span class="s">some_function</span><span class="se">\"</span><span class="s">"</span><span class="p">)</span> </pre></div> </div> <p>The output looks like this:</p> <div class="highlight-python"><pre>2005-03-23 23:47:11,663 - spam_application - INFO - creating an instance of auxiliary_module.Auxiliary 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO - creating an instance of Auxiliary 2005-03-23 23:47:11,665 - spam_application - INFO - created an instance of auxiliary_module.Auxiliary 2005-03-23 23:47:11,668 - spam_application - INFO - calling auxiliary_module.Auxiliary.do_something 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO - doing something 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO - done doing something 2005-03-23 23:47:11,670 - spam_application - INFO - finished auxiliary_module.Auxiliary.do_something 2005-03-23 23:47:11,671 - spam_application - INFO - calling auxiliary_module.some_function() 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO - received a call to "some_function" 2005-03-23 23:47:11,673 - spam_application - INFO - done with auxiliary_module.some_function()</pre> </div> </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="#">15.7. <tt class="docutils literal"><span class="pre">logging</span></tt> — Logging facility for Python</a><ul> <li><a class="reference internal" href="#logging-tutorial">15.7.1. Logging tutorial</a><ul> <li><a class="reference internal" href="#simple-examples">15.7.1.1. Simple examples</a></li> <li><a class="reference internal" href="#loggers">15.7.1.2. Loggers</a></li> <li><a class="reference internal" href="#handlers">15.7.1.3. Handlers</a></li> <li><a class="reference internal" href="#formatters">15.7.1.4. Formatters</a></li> <li><a class="reference internal" href="#configuring-logging">15.7.1.5. Configuring Logging</a></li> <li><a class="reference internal" href="#configuring-logging-for-a-library">15.7.1.6. Configuring Logging for a Library</a></li> </ul> </li> <li><a class="reference internal" href="#logging-levels">15.7.2. Logging Levels</a></li> <li><a class="reference internal" href="#useful-handlers">15.7.3. Useful Handlers</a></li> <li><a class="reference internal" href="#module-level-functions">15.7.4. Module-Level Functions</a></li> <li><a class="reference internal" href="#logger-objects">15.7.5. Logger Objects</a></li> <li><a class="reference internal" href="#basic-example">15.7.6. Basic example</a></li> <li><a class="reference internal" href="#logging-to-multiple-destinations">15.7.7. Logging to multiple destinations</a></li> <li><a class="reference internal" href="#exceptions-raised-during-logging">15.7.8. Exceptions raised during logging</a></li> <li><a class="reference internal" href="#adding-contextual-information-to-your-logging-output">15.7.9. Adding contextual information to your logging output</a></li> <li><a class="reference internal" href="#logging-to-a-single-file-from-multiple-processes">15.7.10. Logging to a single file from multiple processes</a></li> <li><a class="reference internal" href="#sending-and-receiving-logging-events-across-a-network">15.7.11. Sending and receiving logging events across a network</a></li> <li><a class="reference internal" href="#using-arbitrary-objects-as-messages">15.7.12. Using arbitrary objects as messages</a></li> <li><a class="reference internal" href="#optimization">15.7.13. Optimization</a></li> <li><a class="reference internal" href="#handler-objects">15.7.14. Handler Objects</a><ul> <li><a class="reference internal" href="#streamhandler">15.7.14.1. StreamHandler</a></li> <li><a class="reference internal" href="#filehandler">15.7.14.2. FileHandler</a></li> <li><a class="reference internal" href="#nullhandler">15.7.14.3. NullHandler</a></li> <li><a class="reference internal" href="#watchedfilehandler">15.7.14.4. WatchedFileHandler</a></li> <li><a class="reference internal" href="#rotatingfilehandler">15.7.14.5. RotatingFileHandler</a></li> <li><a class="reference internal" href="#timedrotatingfilehandler">15.7.14.6. TimedRotatingFileHandler</a></li> <li><a class="reference internal" href="#sockethandler">15.7.14.7. SocketHandler</a></li> <li><a class="reference internal" href="#datagramhandler">15.7.14.8. DatagramHandler</a></li> <li><a class="reference internal" href="#sysloghandler">15.7.14.9. SysLogHandler</a></li> <li><a class="reference internal" href="#nteventloghandler">15.7.14.10. NTEventLogHandler</a></li> <li><a class="reference internal" href="#smtphandler">15.7.14.11. SMTPHandler</a></li> <li><a class="reference internal" href="#memoryhandler">15.7.14.12. MemoryHandler</a></li> <li><a class="reference internal" href="#httphandler">15.7.14.13. HTTPHandler</a></li> </ul> </li> <li><a class="reference internal" href="#formatter-objects">15.7.15. Formatter Objects</a></li> <li><a class="reference internal" href="#filter-objects">15.7.16. Filter Objects</a></li> <li><a class="reference internal" href="#logrecord-objects">15.7.17. LogRecord Objects</a></li> <li><a class="reference internal" href="#loggeradapter-objects">15.7.18. LoggerAdapter Objects</a></li> <li><a class="reference internal" href="#thread-safety">15.7.19. Thread Safety</a></li> <li><a class="reference internal" href="#integration-with-the-warnings-module">15.7.20. Integration with the warnings module</a></li> <li><a class="reference internal" href="#configuration">15.7.21. Configuration</a><ul> <li><a class="reference internal" href="#configuration-functions">15.7.21.1. Configuration functions</a></li> <li><a class="reference internal" href="#configuration-dictionary-schema">15.7.21.2. Configuration dictionary schema</a><ul> <li><a class="reference internal" href="#dictionary-schema-details">15.7.21.2.1. Dictionary Schema Details</a></li> <li><a class="reference internal" href="#incremental-configuration">15.7.21.2.2. Incremental Configuration</a></li> <li><a class="reference internal" href="#object-connections">15.7.21.2.3. Object connections</a></li> <li><a class="reference internal" href="#user-defined-objects">15.7.21.2.4. User-defined objects</a></li> <li><a class="reference internal" href="#access-to-external-objects">15.7.21.2.5. Access to external objects</a></li> <li><a class="reference internal" href="#access-to-internal-objects">15.7.21.2.6. Access to internal objects</a></li> </ul> </li> <li><a class="reference internal" href="#configuration-file-format">15.7.21.3. Configuration file format</a></li> <li><a class="reference internal" href="#configuration-server-example">15.7.21.4. Configuration server example</a></li> </ul> </li> <li><a class="reference internal" href="#more-examples">15.7.22. More examples</a><ul> <li><a class="reference internal" href="#multiple-handlers-and-formatters">15.7.22.1. Multiple handlers and formatters</a></li> <li><a class="reference internal" href="#using-logging-in-multiple-modules">15.7.22.2. Using logging in multiple modules</a></li> </ul> </li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="getopt.html" title="previous chapter">15.6. <tt class="docutils literal docutils literal"><span class="pre">getopt</span></tt> — C-style parser for command line options</a></p> <h4>Next topic</h4> <p class="topless"><a href="getpass.html" title="next chapter">15.8. <tt class="docutils literal docutils literal docutils literal"><span class="pre">getpass</span></tt> — Portable password input</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/library/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" size="18" /> <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="getpass.html" title="15.8. getpass — Portable password input" >next</a> |</li> <li class="right" > <a href="getopt.html" title="15.6. getopt — C-style parser for command line options" >previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="../index.html">Python v2.7 documentation</a> »</li> <li><a href="index.html" >The Python Standard Library</a> »</li> <li><a href="allos.html" >15. Generic Operating System Services</a> »</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 1990-2010, 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 Aug 09, 2010. <a href="../bugs.html">Found a bug</a>? <br /> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.0b2. </div> </body> </html>