Linux server.nvwebsoft.co.in 3.10.0-1160.114.2.el7.x86_64 #1 SMP Wed Mar 20 15:54:52 UTC 2024 x86_64
Apache
: 162.240.12.249 | : 3.143.7.53
202 Domain
8.1.31
nbspublicschool
www.github.com/MadExploits
Terminal
AUTO ROOT
Adminer
Backdoor Destroyer
Linux Exploit
Lock Shell
Lock File
Create User
CREATE RDP
PHP Mailer
BACKCONNECT
UNLOCK SHELL
HASH IDENTIFIER
CPANEL RESET
CREATE WP USER
README
+ Create Folder
+ Create File
/
usr /
share /
doc /
python-docs-2.7.5 /
html /
howto /
[ HOME SHELL ]
Name
Size
Permission
Action
argparse.html
72.39
KB
-rw-r--r--
cporting.html
39.22
KB
-rw-r--r--
curses.html
42.8
KB
-rw-r--r--
descriptor.html
50.15
KB
-rw-r--r--
doanddont.html
38.69
KB
-rw-r--r--
functional.html
109
KB
-rw-r--r--
index.html
7.51
KB
-rw-r--r--
logging-cookbook.html
103.51
KB
-rw-r--r--
logging.html
93.47
KB
-rw-r--r--
pyporting.html
60.8
KB
-rw-r--r--
regex.html
133.84
KB
-rw-r--r--
sockets.html
39.93
KB
-rw-r--r--
sorting.html
44.25
KB
-rw-r--r--
unicode.html
64.29
KB
-rw-r--r--
urllib2.html
58.48
KB
-rw-r--r--
webservers.html
55.66
KB
-rw-r--r--
Delete
Unzip
Zip
${this.title}
Close
Code Editor : logging-cookbook.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Logging Cookbook — Python 2.7.5 documentation</title> <link rel="stylesheet" href="../_static/default.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '2.7.5', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 2.7.5 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="top" title="Python 2.7.5 documentation" href="../index.html" /> <link rel="up" title="Python HOWTOs" href="index.html" /> <link rel="next" title="Regular Expression HOWTO" href="regex.html" /> <link rel="prev" title="Logging HOWTO" href="logging.html" /> <link rel="shortcut icon" type="image/png" href="../_static/py.png" /> <script type="text/javascript" src="../_static/copybutton.js"></script> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="regex.html" title="Regular Expression HOWTO" accesskey="N">next</a> |</li> <li class="right" > <a href="logging.html" title="Logging HOWTO" accesskey="P">previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="http://www.python.org/">Python</a> »</li> <li> <a href="../index.html">Python 2.7.5 documentation</a> » </li> <li><a href="index.html" accesskey="U">Python HOWTOs</a> »</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <div class="section" id="logging-cookbook"> <span id="id1"></span><h1>Logging Cookbook<a class="headerlink" href="#logging-cookbook" title="Permalink to this headline">¶</a></h1> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">Vinay Sajip <vinay_sajip at red-dove dot com></td> </tr> </tbody> </table> <p>This page contains a number of recipes related to logging, which have been found useful in the past.</p> <div class="section" id="using-logging-in-multiple-modules"> <h2>Using logging in multiple modules<a class="headerlink" href="#using-logging-in-multiple-modules" title="Permalink to this headline">¶</a></h2> <p>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 "some_function"'</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 class="section" id="multiple-handlers-and-formatters"> <h2>Multiple handlers and formatters<a class="headerlink" href="#multiple-handlers-and-formatters" title="Permalink to this headline">¶</a></h2> <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="logging-to-multiple-destinations"> <span id="multiple-destinations"></span><h2>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="configuration-server-example"> <h2>Configuration server example<a class="headerlink" href="#configuration-server-example" title="Permalink to this headline">¶</a></h2> <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="k">with</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">'rb'</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span> <span class="n">data_to_send</span> <span class="o">=</span> <span class="n">f</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="p">(</span><span class="s">'connecting...'</span><span class="p">)</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="p">(</span><span class="s">'sending config...'</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">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="p">(</span><span class="s">'complete'</span><span class="p">)</span> </pre></div> </div> </div> <div class="section" id="sending-and-receiving-logging-events-across-a-network"> <span id="network-logging"></span><h2>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="../library/socketserver.html#module-SocketServer" title="SocketServer: 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">pickle</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="bp">True</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">pickle</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">"""</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="p">(</span><span class="s">'About to start TCP server...'</span><span class="p">)</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> <p>Note that there are some security issues with pickle in some scenarios. If these affect you, you can use an alternative serialization scheme by overriding the <tt class="xref py py-meth docutils literal"><span class="pre">makePickle()</span></tt> method and implementing your alternative there, as well as adapting the above script to use your alternative serialization.</p> </div> <div class="section" id="adding-contextual-information-to-your-logging-output"> <span id="context-info"></span><h2>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 <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt></a> 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 <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt></a> 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 <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt></a> instances becomes effectively unbounded.</p> <div class="section" id="using-loggeradapters-to-impart-contextual-information"> <h3>Using LoggerAdapters to impart contextual information<a class="headerlink" href="#using-loggeradapters-to-impart-contextual-information" title="Permalink to this headline">¶</a></h3> <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="../library/logging.html#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 <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt></a>, so that you can call <a class="reference internal" href="../library/logging.html#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="../library/logging.html#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="../library/logging.html#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="../library/logging.html#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="../library/logging.html#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="../library/logging.html#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="../library/logging.html#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 <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt></a>, so you can use the two types of instances interchangeably.</p> <p>When you create an instance of <a class="reference internal" href="../library/logging.html#logging.LoggerAdapter" title="logging.LoggerAdapter"><tt class="xref py py-class docutils literal"><span class="pre">LoggerAdapter</span></tt></a>, you pass it a <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt></a> 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="../library/logging.html#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 <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt></a> 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="../library/logging.html#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="../library/logging.html#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="../library/logging.html#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="../library/logging.html#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="../library/logging.html#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> </div> <div class="section" id="using-filters-to-impart-contextual-information"> <span id="filters-contextual"></span><h3>Using Filters to impart contextual information<a class="headerlink" href="#using-filters-to-impart-contextual-information" title="Permalink to this headline">¶</a></h3> <p>You can also add contextual information to log output using a user-defined <a class="reference internal" href="../library/logging.html#logging.Filter" title="logging.Filter"><tt class="xref py py-class docutils literal"><span class="pre">Filter</span></tt></a>. <tt class="docutils literal"><span class="pre">Filter</span></tt> instances are allowed to modify the <tt class="docutils literal"><span class="pre">LogRecords</span></tt> passed to them, including adding additional attributes which can then be output using a suitable format string, or if needed a custom <a class="reference internal" href="../library/logging.html#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a>.</p> <p>For example in a web application, the request being processed (or at least, the interesting parts of it) can be stored in a threadlocal (<a class="reference internal" href="../library/threading.html#threading.local" title="threading.local"><tt class="xref py py-class docutils literal"><span class="pre">threading.local</span></tt></a>) variable, and then accessed from a <tt class="docutils literal"><span class="pre">Filter</span></tt> to add, say, information from the request - say, the remote IP address and remote user’s username - to the <tt class="docutils literal"><span class="pre">LogRecord</span></tt>, using the attribute names ‘ip’ and ‘user’ as in the <tt class="docutils literal"><span class="pre">LoggerAdapter</span></tt> example above. In that case, the same format string can be used to get similar output to that shown above. Here’s an example script:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span> <span class="kn">from</span> <span class="nn">random</span> <span class="kn">import</span> <span class="n">choice</span> <span class="k">class</span> <span class="nc">ContextFilter</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">Filter</span><span class="p">):</span> <span class="sd">"""</span> <span class="sd"> This is a filter which injects contextual information into the log.</span> <span class="sd"> Rather than use actual contextual information, we just use random</span> <span class="sd"> data in this demo.</span> <span class="sd"> """</span> <span class="n">USERS</span> <span class="o">=</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="n">IPS</span> <span class="o">=</span> <span class="p">[</span><span class="s">'123.231.231.123'</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">def</span> <span class="nf">filter</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="n">record</span><span class="o">.</span><span class="n">ip</span> <span class="o">=</span> <span class="n">choice</span><span class="p">(</span><span class="n">ContextFilter</span><span class="o">.</span><span class="n">IPS</span><span class="p">)</span> <span class="n">record</span><span class="o">.</span><span class="n">user</span> <span class="o">=</span> <span class="n">choice</span><span class="p">(</span><span class="n">ContextFilter</span><span class="o">.</span><span class="n">USERS</span><span class="p">)</span> <span class="k">return</span> <span class="bp">True</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">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">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">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="n">a2</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">'d.e.f'</span><span class="p">)</span> <span class="n">f</span> <span class="o">=</span> <span class="n">ContextFilter</span><span class="p">()</span> <span class="n">a1</span><span class="o">.</span><span class="n">addFilter</span><span class="p">(</span><span class="n">f</span><span class="p">)</span> <span class="n">a2</span><span class="o">.</span><span class="n">addFilter</span><span class="p">(</span><span class="n">f</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="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>which, when run, produces something like:</p> <div class="highlight-python"><pre>2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A message at CRITICAL level with 2 parameters 2010-09-06 22:38:15,300 d.e.f ERROR IP: 127.0.0.1 User: jim A message at ERROR level with 2 parameters 2010-09-06 22:38:15,300 d.e.f DEBUG IP: 127.0.0.1 User: sheila A message at DEBUG level with 2 parameters 2010-09-06 22:38:15,300 d.e.f ERROR IP: 123.231.231.123 User: fred A message at ERROR level with 2 parameters 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1 User: jim A message at CRITICAL level with 2 parameters 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A message at CRITICAL level with 2 parameters 2010-09-06 22:38:15,300 d.e.f DEBUG IP: 192.168.0.1 User: jim A message at DEBUG level with 2 parameters 2010-09-06 22:38:15,301 d.e.f ERROR IP: 127.0.0.1 User: sheila A message at ERROR level with 2 parameters 2010-09-06 22:38:15,301 d.e.f DEBUG IP: 123.231.231.123 User: fred A message at DEBUG level with 2 parameters 2010-09-06 22:38:15,301 d.e.f INFO IP: 123.231.231.123 User: fred A message at INFO level with 2 parameters</pre> </div> </div> </div> <div class="section" id="logging-to-a-single-file-from-multiple-processes"> <span id="multiple-processes"></span><h2>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, one 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.) <a class="reference internal" href="#network-logging"><em>This section</em></a> 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="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based "threading" interface."><tt class="xref py py-mod docutils literal"><span class="pre">multiprocessing</span></tt></a> module, you could 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="../library/logging.handlers.html#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="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: 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="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: 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="using-file-rotation"> <h2>Using file rotation<a class="headerlink" href="#using-file-rotation" title="Permalink to this headline">¶</a></h2> <p>Sometimes you want to let a log file grow to a certain size, then open a new file and log to that. You may want to keep a certain number of these files, and when that many files have been created, rotate the files so that the number of files and the size of the files both remain bounded. For this usage pattern, the logging package provides a <a class="reference internal" href="../library/logging.handlers.html#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><tt class="xref py py-class docutils literal"><span class="pre">RotatingFileHandler</span></tt></a>:</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="p">(</span><span class="n">filename</span><span class="p">)</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 too small as an extreme example. You would want to set <em>maxBytes</em> to an appropriate value.</p> </div> <div class="section" id="an-example-dictionary-based-configuration"> <h2>An example dictionary-based configuration<a class="headerlink" href="#an-example-dictionary-based-configuration" title="Permalink to this headline">¶</a></h2> <p>Below is an example of a logging configuration dictionary - it’s taken from the <a class="reference external" href="https://docs.djangoproject.com/en/1.3/topics/logging/#configuring-logging">documentation on the Django project</a>. This dictionary is passed to <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><tt class="xref py py-func docutils literal"><span class="pre">dictConfig()</span></tt></a> to put the configuration into effect:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">LOGGING</span> <span class="o">=</span> <span class="p">{</span> <span class="s">'version'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s">'disable_existing_loggers'</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span> <span class="s">'formatters'</span><span class="p">:</span> <span class="p">{</span> <span class="s">'verbose'</span><span class="p">:</span> <span class="p">{</span> <span class="s">'format'</span><span class="p">:</span> <span class="s">'</span><span class="si">%(levelname)s</span><span class="s"> </span><span class="si">%(asctime)s</span><span class="s"> </span><span class="si">%(module)s</span><span class="s"> </span><span class="si">%(process)d</span><span class="s"> </span><span class="si">%(thread)d</span><span class="s"> </span><span class="si">%(message)s</span><span class="s">'</span> <span class="p">},</span> <span class="s">'simple'</span><span class="p">:</span> <span class="p">{</span> <span class="s">'format'</span><span class="p">:</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="p">},</span> <span class="s">'filters'</span><span class="p">:</span> <span class="p">{</span> <span class="s">'special'</span><span class="p">:</span> <span class="p">{</span> <span class="s">'()'</span><span class="p">:</span> <span class="s">'project.logging.SpecialFilter'</span><span class="p">,</span> <span class="s">'foo'</span><span class="p">:</span> <span class="s">'bar'</span><span class="p">,</span> <span class="p">}</span> <span class="p">},</span> <span class="s">'handlers'</span><span class="p">:</span> <span class="p">{</span> <span class="s">'null'</span><span class="p">:</span> <span class="p">{</span> <span class="s">'level'</span><span class="p">:</span><span class="s">'DEBUG'</span><span class="p">,</span> <span class="s">'class'</span><span class="p">:</span><span class="s">'django.utils.log.NullHandler'</span><span class="p">,</span> <span class="p">},</span> <span class="s">'console'</span><span class="p">:{</span> <span class="s">'level'</span><span class="p">:</span><span class="s">'DEBUG'</span><span class="p">,</span> <span class="s">'class'</span><span class="p">:</span><span class="s">'logging.StreamHandler'</span><span class="p">,</span> <span class="s">'formatter'</span><span class="p">:</span> <span class="s">'simple'</span> <span class="p">},</span> <span class="s">'mail_admins'</span><span class="p">:</span> <span class="p">{</span> <span class="s">'level'</span><span class="p">:</span> <span class="s">'ERROR'</span><span class="p">,</span> <span class="s">'class'</span><span class="p">:</span> <span class="s">'django.utils.log.AdminEmailHandler'</span><span class="p">,</span> <span class="s">'filters'</span><span class="p">:</span> <span class="p">[</span><span class="s">'special'</span><span class="p">]</span> <span class="p">}</span> <span class="p">},</span> <span class="s">'loggers'</span><span class="p">:</span> <span class="p">{</span> <span class="s">'django'</span><span class="p">:</span> <span class="p">{</span> <span class="s">'handlers'</span><span class="p">:[</span><span class="s">'null'</span><span class="p">],</span> <span class="s">'propagate'</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span> <span class="s">'level'</span><span class="p">:</span><span class="s">'INFO'</span><span class="p">,</span> <span class="p">},</span> <span class="s">'django.request'</span><span class="p">:</span> <span class="p">{</span> <span class="s">'handlers'</span><span class="p">:</span> <span class="p">[</span><span class="s">'mail_admins'</span><span class="p">],</span> <span class="s">'level'</span><span class="p">:</span> <span class="s">'ERROR'</span><span class="p">,</span> <span class="s">'propagate'</span><span class="p">:</span> <span class="bp">False</span><span class="p">,</span> <span class="p">},</span> <span class="s">'myproject.custom'</span><span class="p">:</span> <span class="p">{</span> <span class="s">'handlers'</span><span class="p">:</span> <span class="p">[</span><span class="s">'console'</span><span class="p">,</span> <span class="s">'mail_admins'</span><span class="p">],</span> <span class="s">'level'</span><span class="p">:</span> <span class="s">'INFO'</span><span class="p">,</span> <span class="s">'filters'</span><span class="p">:</span> <span class="p">[</span><span class="s">'special'</span><span class="p">]</span> <span class="p">}</span> <span class="p">}</span> <span class="p">}</span> </pre></div> </div> <p>For more information about this configuration, you can see the <a class="reference external" href="https://docs.djangoproject.com/en/1.3/topics/logging/#configuring-logging">relevant section</a> of the Django documentation.</p> </div> <div class="section" id="inserting-a-bom-into-messages-sent-to-a-sysloghandler"> <h2>Inserting a BOM into messages sent to a SysLogHandler<a class="headerlink" href="#inserting-a-bom-into-messages-sent-to-a-sysloghandler" title="Permalink to this headline">¶</a></h2> <p><a class="reference external" href="http://tools.ietf.org/html/rfc5424">RFC 5424</a> requires that a Unicode message be sent to a syslog daemon as a set of bytes which have the following structure: an optional pure-ASCII component, followed by a UTF-8 Byte Order Mark (BOM), followed by Unicode encoded using UTF-8. (See the <a class="reference external" href="http://tools.ietf.org/html/rfc5424#section-6">relevant section of the specification</a>.)</p> <p>In Python 2.6 and 2.7, code was added to <a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><tt class="xref py py-class docutils literal"><span class="pre">SysLogHandler</span></tt></a> to insert a BOM into the message, but unfortunately, it was implemented incorrectly, with the BOM appearing at the beginning of the message and hence not allowing any pure-ASCII component to appear before it.</p> <p>As this behaviour is broken, the incorrect BOM insertion code is being removed from Python 2.7.4 and later. However, it is not being replaced, and if you want to produce RFC 5424-compliant messages which include a BOM, an optional pure-ASCII sequence before it and arbitrary Unicode after it, encoded using UTF-8, then you need to do the following:</p> <ol class="arabic"> <li><p class="first">Attach a <a class="reference internal" href="../library/logging.html#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> instance to your <a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><tt class="xref py py-class docutils literal"><span class="pre">SysLogHandler</span></tt></a> instance, with a format string such as:</p> <div class="highlight-python"><div class="highlight"><pre><span class="s">u'ASCII section</span><span class="se">\ufeff</span><span class="s">Unicode section'</span> </pre></div> </div> <p>The Unicode code point <tt class="docutils literal"><span class="pre">u'\ufeff'</span></tt>, when encoded using UTF-8, will be encoded as a UTF-8 BOM – the byte-string <tt class="docutils literal"><span class="pre">'\xef\xbb\xbf'</span></tt>.</p> </li> <li><p class="first">Replace the ASCII section with whatever placeholders you like, but make sure that the data that appears in there after substitution is always ASCII (that way, it will remain unchanged after UTF-8 encoding).</p> </li> <li><p class="first">Replace the Unicode section with whatever placeholders you like; if the data which appears there after substitution contains characters outside the ASCII range, that’s fine – it will be encoded using UTF-8.</p> </li> </ol> <p>If the formatted message is Unicode, it <em>will</em> be encoded using UTF-8 encoding by <tt class="docutils literal"><span class="pre">SysLogHandler</span></tt>. If you follow the above rules, you should be able to produce RFC 5424-compliant messages. If you don’t, logging may not complain, but your messages will not be RFC 5424-compliant, and your syslog daemon may complain.</p> </div> <div class="section" id="implementing-structured-logging"> <h2>Implementing structured logging<a class="headerlink" href="#implementing-structured-logging" title="Permalink to this headline">¶</a></h2> <p>Although most logging messages are intended for reading by humans, and thus not readily machine-parseable, there might be cirumstances where you want to output messages in a structured format which <em>is</em> capable of being parsed by a program (without needing complex regular expressions to parse the log message). This is straightforward to achieve using the logging package. There are a number of ways in which this could be achieved, but the following is a simple approach which uses JSON to serialise the event in a machine-parseable manner:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">json</span> <span class="kn">import</span> <span class="nn">logging</span> <span class="k">class</span> <span class="nc">StructuredMessage</span><span class="p">(</span><span class="nb">object</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="n">message</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">message</span> <span class="o">=</span> <span class="n">message</span> <span class="bp">self</span><span class="o">.</span><span class="n">kwargs</span> <span class="o">=</span> <span class="n">kwargs</span> <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="s">'</span><span class="si">%s</span><span class="s"> >>> </span><span class="si">%s</span><span class="s">'</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">message</span><span class="p">,</span> <span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">kwargs</span><span class="p">))</span> <span class="n">_</span> <span class="o">=</span> <span class="n">StructuredMessage</span> <span class="c"># optional, to improve readability</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">INFO</span><span class="p">,</span> <span class="n">format</span><span class="o">=</span><span class="s">'</span><span class="si">%(message)s</span><span class="s">'</span><span class="p">)</span> <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="n">_</span><span class="p">(</span><span class="s">'message 1'</span><span class="p">,</span> <span class="n">foo</span><span class="o">=</span><span class="s">'bar'</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">num</span><span class="o">=</span><span class="mi">123</span><span class="p">,</span> <span class="n">fnum</span><span class="o">=</span><span class="mf">123.456</span><span class="p">))</span> </pre></div> </div> <p>If the above script is run, it prints:</p> <div class="highlight-python"><pre>message 1 >>> {"fnum": 123.456, "num": 123, "bar": "baz", "foo": "bar"}</pre> </div> <p>Note that the order of items might be different according to the version of Python used.</p> <p>If you need more specialised processing, you can use a custom JSON encoder, as in the following complete example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">__future__</span> <span class="kn">import</span> <span class="n">unicode_literals</span> <span class="kn">import</span> <span class="nn">json</span> <span class="kn">import</span> <span class="nn">logging</span> <span class="c"># This next bit is to ensure the script runs unchanged on 2.x and 3.x</span> <span class="k">try</span><span class="p">:</span> <span class="nb">unicode</span> <span class="k">except</span> <span class="ne">NameError</span><span class="p">:</span> <span class="nb">unicode</span> <span class="o">=</span> <span class="nb">str</span> <span class="k">class</span> <span class="nc">Encoder</span><span class="p">(</span><span class="n">json</span><span class="o">.</span><span class="n">JSONEncoder</span><span class="p">):</span> <span class="k">def</span> <span class="nf">default</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">o</span><span class="p">):</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">o</span><span class="p">,</span> <span class="nb">set</span><span class="p">):</span> <span class="k">return</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">o</span><span class="p">)</span> <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">o</span><span class="p">,</span> <span class="nb">unicode</span><span class="p">):</span> <span class="k">return</span> <span class="n">o</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s">'unicode_escape'</span><span class="p">)</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="s">'ascii'</span><span class="p">)</span> <span class="k">return</span> <span class="nb">super</span><span class="p">(</span><span class="n">Encoder</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">default</span><span class="p">(</span><span class="n">o</span><span class="p">)</span> <span class="k">class</span> <span class="nc">StructuredMessage</span><span class="p">(</span><span class="nb">object</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="n">message</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">message</span> <span class="o">=</span> <span class="n">message</span> <span class="bp">self</span><span class="o">.</span><span class="n">kwargs</span> <span class="o">=</span> <span class="n">kwargs</span> <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">s</span> <span class="o">=</span> <span class="n">Encoder</span><span class="p">()</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">kwargs</span><span class="p">)</span> <span class="k">return</span> <span class="s">'</span><span class="si">%s</span><span class="s"> >>> </span><span class="si">%s</span><span class="s">'</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">message</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span> <span class="n">_</span> <span class="o">=</span> <span class="n">StructuredMessage</span> <span class="c"># optional, to improve readability</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">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">,</span> <span class="n">format</span><span class="o">=</span><span class="s">'</span><span class="si">%(message)s</span><span class="s">'</span><span class="p">)</span> <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="n">_</span><span class="p">(</span><span class="s">'message 1'</span><span class="p">,</span> <span class="n">set_value</span><span class="o">=</span><span class="nb">set</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]),</span> <span class="n">snowman</span><span class="o">=</span><span class="s">'</span><span class="se">\u2603</span><span class="s">'</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>When the above script is run, it prints:</p> <div class="highlight-python"><pre>message 1 >>> {"snowman": "\u2603", "set_value": [1, 2, 3]}</pre> </div> <p>Note that the order of items might be different according to the version of Python used.</p> </div> </div> </div> </div> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <h3><a href="../contents.html">Table Of Contents</a></h3> <ul> <li><a class="reference internal" href="#">Logging Cookbook</a><ul> <li><a class="reference internal" href="#using-logging-in-multiple-modules">Using logging in multiple modules</a></li> <li><a class="reference internal" href="#multiple-handlers-and-formatters">Multiple handlers and formatters</a></li> <li><a class="reference internal" href="#logging-to-multiple-destinations">Logging to multiple destinations</a></li> <li><a class="reference internal" href="#configuration-server-example">Configuration server example</a></li> <li><a class="reference internal" href="#sending-and-receiving-logging-events-across-a-network">Sending and receiving logging events across a network</a></li> <li><a class="reference internal" href="#adding-contextual-information-to-your-logging-output">Adding contextual information to your logging output</a><ul> <li><a class="reference internal" href="#using-loggeradapters-to-impart-contextual-information">Using LoggerAdapters to impart contextual information</a></li> <li><a class="reference internal" href="#using-filters-to-impart-contextual-information">Using Filters to impart contextual information</a></li> </ul> </li> <li><a class="reference internal" href="#logging-to-a-single-file-from-multiple-processes">Logging to a single file from multiple processes</a></li> <li><a class="reference internal" href="#using-file-rotation">Using file rotation</a></li> <li><a class="reference internal" href="#an-example-dictionary-based-configuration">An example dictionary-based configuration</a></li> <li><a class="reference internal" href="#inserting-a-bom-into-messages-sent-to-a-sysloghandler">Inserting a BOM into messages sent to a SysLogHandler</a></li> <li><a class="reference internal" href="#implementing-structured-logging">Implementing structured logging</a></li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="logging.html" title="previous chapter">Logging HOWTO</a></p> <h4>Next topic</h4> <p class="topless"><a href="regex.html" title="next chapter">Regular Expression HOWTO</a></p> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a Bug</a></li> <li><a href="../_sources/howto/logging-cookbook.txt" rel="nofollow">Show Source</a></li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="regex.html" title="Regular Expression HOWTO" >next</a> |</li> <li class="right" > <a href="logging.html" title="Logging HOWTO" >previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="http://www.python.org/">Python</a> »</li> <li> <a href="../index.html">Python 2.7.5 documentation</a> » </li> <li><a href="index.html" >Python HOWTOs</a> »</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 1990-2020, Python Software Foundation. <br /> The Python Software Foundation is a non-profit corporation. <a href="http://www.python.org/psf/donations/">Please donate.</a> <br /> Last updated on Oct 13, 2020. <a href="../bugs.html">Found a bug</a>? <br /> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3. </div> </body> </html>
Close