gooderp18绿色标准版
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1381 lines
122KB

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