-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging.html
More file actions
1220 lines (1180 loc) · 111 KB
/
logging.html
File metadata and controls
1220 lines (1180 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_TW">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>如何使用 Logging 模組 — Python 3.7.0 說明文件</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/translations.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="在 Python 3.7.0 說明文件 中搜尋"
href="../_static/opensearch.xml"/>
<link rel="author" title="關於這些文件" href="../about.html" />
<link rel="index" title="索引" href="../genindex.html" />
<link rel="search" title="搜尋" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="Logging Cookbook" href="logging-cookbook.html" />
<link rel="prev" title="函式編程 HOWTO" href="functional.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/howto/logging.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<h3>瀏覽</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">索引</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python 模組索引"
>模組</a> |</li>
<li class="right" >
<a href="logging-cookbook.html" title="Logging Cookbook"
accesskey="N">下一頁</a> |</li>
<li class="right" >
<a href="functional.html" title="函式編程 HOWTO"
accesskey="P">上一頁</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> »</li>
<li>
<span class="language_switcher_placeholder">zh_TW</span>
<span class="version_switcher_placeholder">3.7.0</span>
<a href="../index.html">Documentation </a> »
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> »</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="logging-howto">
<h1>如何使用 Logging 模組<a class="headerlink" href="#logging-howto" title="本標題的永久連結">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">原文作者 Vinay Sajip <vinay_sajip at red-dove dot com></td>
</tr>
</tbody>
</table>
<div class="section" id="basic-logging-tutorial">
<span id="logging-basic-tutorial"></span><h2>基礎 Logging 指南<a class="headerlink" href="#basic-logging-tutorial" title="本標題的永久連結">¶</a></h2>
<p>軟體執行時,追蹤有什麼事件發生的動作稱為 Logging。軟體開發者會使用 Logging 這樣的機制是因為想知道在運行過程中是否有特定的事件發生。事件會被一段訊息所描述。這段訊息可能包含一些因為此事件發生而改變的資料。開發者也可以指派事件的重要程度,重要程度有時候也會被稱作 <em>程度</em> 或是 <em>嚴重性</em> 。</p>
<div class="section" id="when-to-use-logging">
<h3>什麼時候使用 logging<a class="headerlink" href="#when-to-use-logging" title="本標題的永久連結">¶</a></h3>
<p>Logging provides a set of convenience functions for simple logging usage. These
are <a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><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>, <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>. To determine when to use logging, see the table below, which
states, for each of a set of common tasks, the best tool to use for it.</p>
<table border="1" class="docutils">
<colgroup>
<col width="49%" />
<col width="51%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Task you want to perform</th>
<th class="head">The best tool for the task</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>Display console output for ordinary
usage of a command line script or
program</td>
<td><a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a></td>
</tr>
<tr class="row-odd"><td>Report events that occur during
normal operation of a program (e.g.
for status monitoring or fault
investigation)</td>
<td><a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><code class="xref py py-func docutils literal notranslate"><span class="pre">logging.info()</span></code></a> (or
<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">logging.debug()</span></code></a> for very
detailed output for diagnostic
purposes)</td>
</tr>
<tr class="row-even"><td>Issue a warning regarding a
particular runtime event</td>
<td><p class="first"><a class="reference internal" href="../library/warnings.html#warnings.warn" title="warnings.warn"><code class="xref py py-func docutils literal notranslate"><span class="pre">warnings.warn()</span></code></a> in library
code if the issue is avoidable and
the client application should be
modified to eliminate the warning</p>
<p class="last"><a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><code class="xref py py-func docutils literal notranslate"><span class="pre">logging.warning()</span></code></a> if there is
nothing the client application can do
about the situation, but the event
should still be noted</p>
</td>
</tr>
<tr class="row-odd"><td>Report an error regarding a
particular runtime event</td>
<td>Raise an exception</td>
</tr>
<tr class="row-even"><td>Report suppression of an error
without raising an exception (e.g.
error handler in a long-running
server process)</td>
<td><a class="reference internal" href="../library/logging.html#logging.error" title="logging.error"><code class="xref py py-func docutils literal notranslate"><span class="pre">logging.error()</span></code></a>,
<a class="reference internal" href="../library/logging.html#logging.exception" title="logging.exception"><code class="xref py py-func docutils literal notranslate"><span class="pre">logging.exception()</span></code></a> or
<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">logging.critical()</span></code></a> as
appropriate for the specific error
and application domain</td>
</tr>
</tbody>
</table>
<p>The logging functions are named after the level or severity of the events
they are used to track. The standard levels and their applicability are
described below (in increasing order of severity):</p>
<table border="1" class="docutils">
<colgroup>
<col width="24%" />
<col width="76%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Level</th>
<th class="head">When it’s used</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">DEBUG</span></code></td>
<td>Detailed information, typically of interest
only when diagnosing problems.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">INFO</span></code></td>
<td>Confirmation that things are working as
expected.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">WARNING</span></code></td>
<td>An indication that something unexpected
happened, or indicative of some problem in
the near future (e.g. 『disk space low』).
The software is still working as expected.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ERROR</span></code></td>
<td>Due to a more serious problem, the software
has not been able to perform some function.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">CRITICAL</span></code></td>
<td>A serious error, indicating that the program
itself may be unable to continue running.</td>
</tr>
</tbody>
</table>
<p>The default level is <code class="docutils literal notranslate"><span class="pre">WARNING</span></code>, which means that only events of this level
and above will be tracked, unless the logging package is configured to do
otherwise.</p>
<p>Events that are tracked can be handled in different ways. The simplest way of
handling tracked events is to print them to the console. Another common way
is to write them to a disk file.</p>
</div>
<div class="section" id="a-simple-example">
<span id="howto-minimal-example"></span><h3>A simple example<a class="headerlink" href="#a-simple-example" title="本標題的永久連結">¶</a></h3>
<p>A very simple example is:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">'Watch out!'</span><span class="p">)</span> <span class="c1"># will print a message to the console</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">'I told you so'</span><span class="p">)</span> <span class="c1"># will not print anything</span>
</pre></div>
</div>
<p>If you type these lines into a script and run it, you’ll see:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>WARNING:root:Watch out!
</pre></div>
</div>
<p>printed out on the console. The <code class="docutils literal notranslate"><span class="pre">INFO</span></code> message doesn’t appear because the
default level is <code class="docutils literal notranslate"><span class="pre">WARNING</span></code>. The printed message includes the indication of
the level and the description of the event provided in the logging call, i.e.
『Watch out!』. Don’t worry about the 『root』 part for now: it will be explained
later. The actual output can be formatted quite flexibly if you need that;
formatting options will also be explained later.</p>
</div>
<div class="section" id="logging-to-a-file">
<h3>Logging to a file<a class="headerlink" href="#logging-to-a-file" title="本標題的永久連結">¶</a></h3>
<p>A very common situation is that of recording logging events in a file, so let’s
look at that next. Be sure to try the following in a newly-started Python
interpreter, and don’t just continue from the session described above:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="s1">'example.log'</span><span class="p">,</span><span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">'This message should go to the log file'</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">'So should this'</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">'And this, too'</span><span class="p">)</span>
</pre></div>
</div>
<p>And now if we open the file and look at what we have, we should find the log
messages:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too
</pre></div>
</div>
<p>This example also shows how you can set the logging level which acts as the
threshold for tracking. In this case, because we set the threshold to
<code class="docutils literal notranslate"><span class="pre">DEBUG</span></code>, all of the messages were printed.</p>
<p>If you want to set the logging level from a command-line option such as:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>--log=INFO
</pre></div>
</div>
<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
<em>loglevel</em>, you can use:</p>
<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>
</pre></div>
</div>
<p>to get the value which you’ll pass to <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">basicConfig()</span></code></a> via the <em>level</em>
argument. You may want to error check any user input value, perhaps as in the
following example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># assuming loglevel is bound to the string value obtained from the</span>
<span class="c1"># command line argument. Convert to upper case to allow the user to</span>
<span class="c1"># specify --log=DEBUG or --log=debug</span>
<span class="n">numeric_level</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">logging</span><span class="p">,</span> <span class="n">loglevel</span><span class="o">.</span><span class="n">upper</span><span class="p">(),</span> <span class="kc">None</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">numeric_level</span><span class="p">,</span> <span class="nb">int</span><span class="p">):</span>
<span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s1">'Invalid log level: </span><span class="si">%s</span><span class="s1">'</span> <span class="o">%</span> <span class="n">loglevel</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">level</span><span class="o">=</span><span class="n">numeric_level</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span>
</pre></div>
</div>
<p>The call to <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><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 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> etc. As it’s intended as a one-off simple configuration facility,
only the first call will actually do anything: subsequent calls are effectively
no-ops.</p>
<p>If you run the above script several times, the messages from successive runs
are appended to the file <em>example.log</em>. If you want each run to start afresh,
not remembering the messages from earlier runs, you can specify the <em>filemode</em>
argument, by changing the call in the above example to:</p>
<div class="highlight-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">'example.log'</span><span class="p">,</span> <span class="n">filemode</span><span class="o">=</span><span class="s1">'w'</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
</pre></div>
</div>
<p>The output will be the same as before, but the log file is no longer appended
to, so the messages from earlier runs are lost.</p>
</div>
<div class="section" id="logging-from-multiple-modules">
<h3>Logging from multiple modules<a class="headerlink" href="#logging-from-multiple-modules" title="本標題的永久連結">¶</a></h3>
<p>If your program consists of multiple modules, here’s an example of how you
could organize logging in it:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># myapp.py</span>
<span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">mylib</span>
<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="s1">'myapp.log'</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">'Started'</span><span class="p">)</span>
<span class="n">mylib</span><span class="o">.</span><span class="n">do_something</span><span class="p">()</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">'Finished'</span><span class="p">)</span>
<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">'__main__'</span><span class="p">:</span>
<span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># mylib.py</span>
<span class="kn">import</span> <span class="nn">logging</span>
<span class="k">def</span> <span class="nf">do_something</span><span class="p">():</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">'Doing something'</span><span class="p">)</span>
</pre></div>
</div>
<p>If you run <em>myapp.py</em>, you should see this in <em>myapp.log</em>:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>INFO:root:Started
INFO:root:Doing something
INFO:root:Finished
</pre></div>
</div>
<p>which is hopefully what you were expecting to see. You can generalize this to
multiple modules, using the pattern in <em>mylib.py</em>. Note that for this simple
usage pattern, you won’t know, by looking in the log file, <em>where</em> in your
application your messages came from, apart from looking at the event
description. If you want to track the location of your messages, you’ll need
to refer to the documentation beyond the tutorial level – see
<a class="reference internal" href="#logging-advanced-tutorial"><span class="std std-ref">Advanced Logging Tutorial</span></a>.</p>
</div>
<div class="section" id="logging-variable-data">
<h3>Logging variable data<a class="headerlink" href="#logging-variable-data" title="本標題的永久連結">¶</a></h3>
<p>To log variable data, use a format string for the event description message and
append the variable data as arguments. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">'</span><span class="si">%s</span><span class="s1"> before you </span><span class="si">%s</span><span class="s1">'</span><span class="p">,</span> <span class="s1">'Look'</span><span class="p">,</span> <span class="s1">'leap!'</span><span class="p">)</span>
</pre></div>
</div>
<p>will display:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>WARNING:root:Look before you leap!
</pre></div>
</div>
<p>As you can see, merging of variable data into the event description message
uses the old, %-style of string formatting. This is for backwards
compatibility: the logging package pre-dates newer formatting options such as
<a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><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
options <em>are</em> supported, but exploring them is outside the scope of this
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>
</div>
<div class="section" id="changing-the-format-of-displayed-messages">
<h3>Changing the format of displayed messages<a class="headerlink" href="#changing-the-format-of-displayed-messages" title="本標題的永久連結">¶</a></h3>
<p>To change the format which is used to display messages, you need to
specify the format you want to use:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="nb">format</span><span class="o">=</span><span class="s1">'</span><span class="si">%(levelname)s</span><span class="s1">:</span><span class="si">%(message)s</span><span class="s1">'</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">'This message should appear on the console'</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">'So should this'</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">'And this, too'</span><span class="p">)</span>
</pre></div>
</div>
<p>which would print:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>DEBUG:This message should appear on the console
INFO:So should this
WARNING:And this, too
</pre></div>
</div>
<p>Notice that the 『root』 which appeared in earlier examples has disappeared. For
a full set of things that can appear in format strings, you can refer to the
documentation for <a class="reference internal" href="../library/logging.html#logrecord-attributes"><span class="std std-ref">LogRecord attributes</span></a>, but for simple usage, you just
need the <em>levelname</em> (severity), <em>message</em> (event description, including
variable data) and perhaps to display when the event occurred. This is
described in the next section.</p>
</div>
<div class="section" id="displaying-the-date-time-in-messages">
<h3>Displaying the date/time in messages<a class="headerlink" href="#displaying-the-date-time-in-messages" title="本標題的永久連結">¶</a></h3>
<p>To display the date and time of an event, you would place 『%(asctime)s』 in
your format string:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="nb">format</span><span class="o">=</span><span class="s1">'</span><span class="si">%(asctime)s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">'</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">'is when this event was logged.'</span><span class="p">)</span>
</pre></div>
</div>
<p>which should print something like this:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>2010-12-12 11:41:42,612 is when this event was logged.
</pre></div>
</div>
<p>The default format for date/time display (shown above) is like ISO8601 or
<span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3339.html"><strong>RFC 3339</strong></a>. If you need more control over the formatting of the date/time, provide
a <em>datefmt</em> argument to <code class="docutils literal notranslate"><span class="pre">basicConfig</span></code>, as in this example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="nb">format</span><span class="o">=</span><span class="s1">'</span><span class="si">%(asctime)s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">'</span><span class="p">,</span> <span class="n">datefmt</span><span class="o">=</span><span class="s1">'%m/</span><span class="si">%d</span><span class="s1">/%Y %I:%M:%S %p'</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">'is when this event was logged.'</span><span class="p">)</span>
</pre></div>
</div>
<p>which would display something like this:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>12/12/2010 11:46:36 AM is when this event was logged.
</pre></div>
</div>
<p>The format of the <em>datefmt</em> argument is the same as supported by
<a class="reference internal" href="../library/time.html#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.strftime()</span></code></a>.</p>
</div>
<div class="section" id="next-steps">
<h3>Next Steps<a class="headerlink" href="#next-steps" title="本標題的永久連結">¶</a></h3>
<p>That concludes the basic tutorial. It should be enough to get you up and
running with logging. There’s a lot more that the logging package offers, but
to get the best out of it, you’ll need to invest a little more of your time in
reading the following sections. If you’re ready for that, grab some of your
favourite beverage and carry on.</p>
<p>If your logging needs are simple, then use the above examples to incorporate
logging into your own scripts, and if you run into problems or don’t
understand something, please post a question on the comp.lang.python Usenet
group (available at <a class="reference external" href="https://groups.google.com/forum/#!forum/comp.lang.python">https://groups.google.com/forum/#!forum/comp.lang.python</a>) and you
should receive help before too long.</p>
<p>Still here? You can carry on reading the next few sections, which provide a
slightly more advanced/in-depth tutorial than the basic one above. After that,
you can take a look at the <a class="reference internal" href="logging-cookbook.html#logging-cookbook"><span class="std std-ref">Logging Cookbook</span></a>.</p>
</div>
</div>
<div class="section" id="advanced-logging-tutorial">
<span id="logging-advanced-tutorial"></span><h2>Advanced Logging Tutorial<a class="headerlink" href="#advanced-logging-tutorial" title="本標題的永久連結">¶</a></h2>
<p>The logging library takes a modular approach and offers several categories
of components: loggers, handlers, filters, and formatters.</p>
<ul class="simple">
<li>Loggers expose the interface that application code directly uses.</li>
<li>Handlers send the log records (created by loggers) to the appropriate
destination.</li>
<li>Filters provide a finer grained facility for determining which log records
to output.</li>
<li>Formatters specify the layout of log records in the final output.</li>
</ul>
<p>Log event information is passed between loggers, handlers, filters and
formatters in a <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> instance.</p>
<p>Logging is performed by calling methods on instances of the <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a>
class (hereafter called <em class="dfn">loggers</em>). Each instance has a name, and they are
conceptually arranged in a namespace hierarchy using dots (periods) as
separators. For example, a logger named 『scan』 is the parent of loggers
『scan.text』, 『scan.html』 and 『scan.pdf』. Logger names can be anything you want,
and indicate the area of an application in which a logged message originates.</p>
<p>A good convention to use when naming loggers is to use a module-level logger,
in each module which uses logging, named as follows:</p>
<div class="highlight-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>
</pre></div>
</div>
<p>This means that logger names track the package/module hierarchy, and it’s
intuitively obvious where events are logged just from the logger name.</p>
<p>The root of the hierarchy of loggers is called the root logger. That’s the
logger used by the functions <a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><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>,
<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
the root logger. The functions and the methods have the same signatures. The
root logger’s name is printed as 『root』 in the logged output.</p>
<p>It is, of course, possible to log messages to different destinations. Support
is included in the package for writing log messages to files, HTTP GET/POST
locations, email via SMTP, generic sockets, queues, or OS-specific logging
mechanisms such as syslog or the Windows NT event log. Destinations are served
by <em class="dfn">handler</em> classes. You can create your own log destination class if
you have special requirements not met by any of the built-in handler classes.</p>
<p>By default, no destination is set for any logging messages. You can specify
a destination (such as console or file) by using <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">basicConfig()</span></code></a> as in the
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>,
<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
if no destination is set; and if one is not set, they will set a destination
of the console (<code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>) and a default format for the displayed
message before delegating to the root logger to do the actual message output.</p>
<p>The default format set by <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">basicConfig()</span></code></a> for messages is:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>severity:logger name:message
</pre></div>
</div>
<p>You can change this by passing a format string to <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">basicConfig()</span></code></a> with the
<em>format</em> keyword argument. For all options regarding how a format string is
constructed, see <a class="reference internal" href="../library/logging.html#formatter-objects"><span class="std std-ref">Formatter Objects</span></a>.</p>
<div class="section" id="logging-flow">
<h3>Logging Flow<a class="headerlink" href="#logging-flow" title="本標題的永久連結">¶</a></h3>
<p>The flow of log event information in loggers and handlers is illustrated in the
following diagram.</p>
<img alt="../_images/logging_flow.png" src="../_images/logging_flow.png" />
</div>
<div class="section" id="loggers">
<h3>Loggers<a class="headerlink" href="#loggers" title="本標題的永久連結">¶</a></h3>
<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
methods to application code so that applications can log messages at runtime.
Second, logger objects determine which log messages to act upon based upon
severity (the default filtering facility) or filter objects. Third, logger
objects pass along relevant log messages to all interested log handlers.</p>
<p>The most widely used methods on logger objects fall into two categories:
configuration and message sending.</p>
<p>These are the most common configuration methods:</p>
<ul class="simple">
<li><a class="reference internal" href="../library/logging.html#logging.Logger.setLevel" title="logging.Logger.setLevel"><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
will handle, where debug is the lowest built-in severity level and critical
is the highest built-in severity. For example, if the severity level is
INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL messages
and will ignore DEBUG messages.</li>
<li><a class="reference internal" href="../library/logging.html#logging.Logger.addHandler" title="logging.Logger.addHandler"><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
handler objects from the logger object. Handlers are covered in more detail
in <a class="reference internal" href="#handler-basic"><span class="std std-ref">Handlers</span></a>.</li>
<li><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
objects from the logger object. Filters are covered in more detail in
<a class="reference internal" href="../library/logging.html#filter"><span class="std std-ref">Filter Objects</span></a>.</li>
</ul>
<p>You don’t need to always call these methods on every logger you create. See the
last two paragraphs in this section.</p>
<p>With the logger object configured, the following methods create log messages:</p>
<ul class="simple">
<li><a class="reference internal" href="../library/logging.html#logging.Logger.debug" title="logging.Logger.debug"><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>,
<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
a message and a level that corresponds to their respective method names. The
message is actually a format string, which may contain the standard string
substitution syntax of <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
rest of their arguments is a list of objects that correspond with the
substitution fields in the message. With regard to <code class="docutils literal notranslate"><span class="pre">**kwargs</span></code>, the
logging methods care only about a keyword of <code class="docutils literal notranslate"><span class="pre">exc_info</span></code> and use it to
determine whether to log exception information.</li>
<li><a class="reference internal" href="../library/logging.html#logging.Logger.exception" title="logging.Logger.exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Logger.exception()</span></code></a> creates a log message similar to
<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
stack trace along with it. Call this method only from an exception handler.</li>
<li><a class="reference internal" href="../library/logging.html#logging.Logger.log" title="logging.Logger.log"><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
little more verbose for logging messages than using the log level convenience
methods listed above, but this is how to log at custom log levels.</li>
</ul>
<p><a class="reference internal" href="../library/logging.html#logging.getLogger" title="logging.getLogger"><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
name if it is provided, or <code class="docutils literal notranslate"><span class="pre">root</span></code> if not. The names are period-separated
hierarchical structures. Multiple calls to <a class="reference internal" href="../library/logging.html#logging.getLogger" title="logging.getLogger"><code class="xref py py-func docutils literal notranslate"><span class="pre">getLogger()</span></code></a> with the same name
will return a reference to the same logger object. Loggers that are further
down in the hierarchical list are children of loggers higher up in the list.
For example, given a logger with a name of <code class="docutils literal notranslate"><span class="pre">foo</span></code>, loggers with names of
<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>
<p>Loggers have a concept of <em>effective level</em>. If a level is not explicitly set
on a logger, the level of its parent is used instead as its effective level.
If the parent has no explicit level set, <em>its</em> parent is examined, and so on -
all ancestors are searched until an explicitly set level is found. The root
logger always has an explicit level set (<code class="docutils literal notranslate"><span class="pre">WARNING</span></code> by default). When deciding
whether to process an event, the effective level of the logger is used to
determine whether the event is passed to the logger’s handlers.</p>
<p>Child loggers propagate messages up to the handlers associated with their
ancestor loggers. Because of this, it is unnecessary to define and configure
handlers for all the loggers an application uses. It is sufficient to
configure handlers for a top-level logger and create child loggers as needed.
(You can, however, turn off propagation by setting the <em>propagate</em>
attribute of a logger to <code class="docutils literal notranslate"><span class="pre">False</span></code>.)</p>
</div>
<div class="section" id="handlers">
<span id="handler-basic"></span><h3>Handlers<a class="headerlink" href="#handlers" title="本標題的永久連結">¶</a></h3>
<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
appropriate log messages (based on the log messages』 severity) to the handler’s
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
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
scenario, an application may want to send all log messages to a log file, all
log messages of error or higher to stdout, and all messages of critical to an
email address. This scenario requires three individual handlers where each
handler is responsible for sending messages of a specific severity to a specific
location.</p>
<p>The standard library includes quite a few handler types (see
<a class="reference internal" href="#useful-handlers"><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
<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>
<p>There are very few methods in a handler for application developers to concern
themselves with. The only handler methods that seem relevant for application
developers who are using the built-in handler objects (that is, not creating
custom handlers) are the following configuration methods:</p>
<ul class="simple">
<li>The <a class="reference internal" href="../library/logging.html#logging.Handler.setLevel" title="logging.Handler.setLevel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setLevel()</span></code></a> method, just as in logger objects, specifies the
lowest severity that will be dispatched to the appropriate destination. Why
are there two <code class="xref py py-func docutils literal notranslate"><span class="pre">setLevel()</span></code> methods? The level set in the logger
determines which severity of messages it will pass to its handlers. The level
set in each handler determines which messages that handler will send on.</li>
<li><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
use.</li>
<li><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
configure and deconfigure filter objects on handlers.</li>
</ul>
<p>Application code should not directly instantiate and use instances of
<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
defines the interface that all handlers should have and establishes some
default behavior that child classes can use (or override).</p>
</div>
<div class="section" id="formatters">
<h3>Formatters<a class="headerlink" href="#formatters" title="本標題的永久連結">¶</a></h3>
<p>Formatter objects configure the final order, structure, and contents of the log
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
instantiate formatter classes, although you could likely subclass the formatter
if your application needs special behavior. The constructor takes three
optional arguments – a message format string, a date format string and a style
indicator.</p>
<dl class="method">
<dt id="logging.logging.Formatter.__init__">
<code class="descclassname">logging.Formatter.</code><code class="descname">__init__</code><span class="sig-paren">(</span><em>fmt=None</em>, <em>datefmt=None</em>, <em>style='%'</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.logging.Formatter.__init__" title="本定義的永久連結">¶</a></dt>
<dd></dd></dl>
<p>If there is no message format string, the default is to use the
raw message. If there is no date format string, the default date format is:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>%Y-%m-%d %H:%M:%S
</pre></div>
</div>
<p>with the milliseconds tacked on at the end. The <code class="docutils literal notranslate"><span class="pre">style</span></code> is one of <cite>%</cite>, 『{『
or 『$』. If one of these is not specified, then 『%』 will be used.</p>
<p>If the <code class="docutils literal notranslate"><span class="pre">style</span></code> is 『%』, the message format string uses
<code class="docutils literal notranslate"><span class="pre">%(<dictionary</span> <span class="pre">key>)s</span></code> styled string substitution; the possible keys are
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 『{『, the message
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
keyword arguments), while if the style is 『$』 then the message format string
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>
<div class="versionchanged">
<p><span class="versionmodified">3.2 版更變: </span>Added the <code class="docutils literal notranslate"><span class="pre">style</span></code> parameter.</p>
</div>
<p>The following message format string will log the time in a human-readable
format, the severity of the message, and the contents of the message, in that
order:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="s1">'</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">'</span>
</pre></div>
</div>
<p>Formatters use a user-configurable function to convert the creation time of a
record to a tuple. By default, <a class="reference internal" href="../library/time.html#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.localtime()</span></code></a> is used; to change this
for a particular formatter instance, set the <code class="docutils literal notranslate"><span class="pre">converter</span></code> attribute of the
instance to a function with the same signature as <a class="reference internal" href="../library/time.html#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.localtime()</span></code></a> or
<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
all logging times to be shown in GMT, set the <code class="docutils literal notranslate"><span class="pre">converter</span></code> attribute in the
Formatter class (to <code class="docutils literal notranslate"><span class="pre">time.gmtime</span></code> for GMT display).</p>
</div>
<div class="section" id="configuring-logging">
<h3>Configuring Logging<a class="headerlink" href="#configuring-logging" title="本標題的永久連結">¶</a></h3>
<p>Programmers can configure logging in three ways:</p>
<ol class="arabic simple">
<li>Creating loggers, handlers, and formatters explicitly using Python
code that calls the configuration methods listed above.</li>
<li>Creating a logging config file and reading it using the <a class="reference internal" href="../library/logging.config.html#logging.config.fileConfig" title="logging.config.fileConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">fileConfig()</span></code></a>
function.</li>
<li>Creating a dictionary of configuration information and passing it
to the <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code></a> function.</li>
</ol>
<p>For the reference documentation on the last two options, see
<a class="reference internal" href="../library/logging.config.html#logging-config-api"><span class="std std-ref">Configuration functions</span></a>. The following example configures a very simple
logger, a console handler, and a simple formatter using Python code:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="c1"># create logger</span>
<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">'simple_example'</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
<span class="c1"># create console handler and set level to debug</span>
<span class="n">ch</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">StreamHandler</span><span class="p">()</span>
<span class="n">ch</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
<span class="c1"># create formatter</span>
<span class="n">formatter</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">Formatter</span><span class="p">(</span><span class="s1">'</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">'</span><span class="p">)</span>
<span class="c1"># add formatter to ch</span>
<span class="n">ch</span><span class="o">.</span><span class="n">setFormatter</span><span class="p">(</span><span class="n">formatter</span><span class="p">)</span>
<span class="c1"># add ch to logger</span>
<span class="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">ch</span><span class="p">)</span>
<span class="c1"># 'application' code</span>
<span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">'debug message'</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">'info message'</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s1">'warn message'</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">'error message'</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s1">'critical message'</span><span class="p">)</span>
</pre></div>
</div>
<p>Running this module from the command line produces the following output:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python simple_logging_module.py
<span class="go">2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message</span>
<span class="go">2005-03-19 15:10:26,620 - simple_example - INFO - info message</span>
<span class="go">2005-03-19 15:10:26,695 - simple_example - WARNING - warn message</span>
<span class="go">2005-03-19 15:10:26,697 - simple_example - ERROR - error message</span>
<span class="go">2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message</span>
</pre></div>
</div>
<p>The following Python module creates a logger, handler, and formatter nearly
identical to those in the example listed above, with the only difference being
the names of the objects:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">logging.config</span>
<span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">fileConfig</span><span class="p">(</span><span class="s1">'logging.conf'</span><span class="p">)</span>
<span class="c1"># create logger</span>
<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">'simpleExample'</span><span class="p">)</span>
<span class="c1"># 'application' code</span>
<span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">'debug message'</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">'info message'</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s1">'warn message'</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">'error message'</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s1">'critical message'</span><span class="p">)</span>
</pre></div>
</div>
<p>Here is the logging.conf file:</p>
<div class="highlight-ini notranslate"><div class="highlight"><pre><span></span><span class="k">[loggers]</span>
<span class="na">keys</span><span class="o">=</span><span class="s">root,simpleExample</span>
<span class="k">[handlers]</span>
<span class="na">keys</span><span class="o">=</span><span class="s">consoleHandler</span>
<span class="k">[formatters]</span>
<span class="na">keys</span><span class="o">=</span><span class="s">simpleFormatter</span>
<span class="k">[logger_root]</span>
<span class="na">level</span><span class="o">=</span><span class="s">DEBUG</span>
<span class="na">handlers</span><span class="o">=</span><span class="s">consoleHandler</span>
<span class="k">[logger_simpleExample]</span>
<span class="na">level</span><span class="o">=</span><span class="s">DEBUG</span>
<span class="na">handlers</span><span class="o">=</span><span class="s">consoleHandler</span>
<span class="na">qualname</span><span class="o">=</span><span class="s">simpleExample</span>
<span class="na">propagate</span><span class="o">=</span><span class="s">0</span>
<span class="k">[handler_consoleHandler]</span>
<span class="na">class</span><span class="o">=</span><span class="s">StreamHandler</span>
<span class="na">level</span><span class="o">=</span><span class="s">DEBUG</span>
<span class="na">formatter</span><span class="o">=</span><span class="s">simpleFormatter</span>
<span class="na">args</span><span class="o">=</span><span class="s">(sys.stdout,)</span>
<span class="k">[formatter_simpleFormatter]</span>
<span class="na">format</span><span class="o">=</span><span class="s">%(asctime)s - %(name)s - %(levelname)s - %(message)s</span>
<span class="na">datefmt</span><span class="o">=</span>
</pre></div>
</div>
<p>The output is nearly identical to that of the non-config-file-based example:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python simple_logging_config.py
<span class="go">2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message</span>
<span class="go">2005-03-19 15:38:55,979 - simpleExample - INFO - info message</span>
<span class="go">2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message</span>
<span class="go">2005-03-19 15:38:56,055 - simpleExample - ERROR - error message</span>
<span class="go">2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message</span>
</pre></div>
</div>
<p>You can see that the config file approach has a few advantages over the Python
code approach, mainly separation of configuration and code and the ability of
noncoders to easily modify the logging properties.</p>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<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,
<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
backward compatibility. This may or may not be what you want, since it
will cause any loggers existing before the <a class="reference internal" href="../library/logging.config.html#logging.config.fileConfig" title="logging.config.fileConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">fileConfig()</span></code></a> call to
be disabled unless they (or an ancestor) are explicitly named in the
configuration. Please refer to the reference documentation for more
information, and specify <code class="docutils literal notranslate"><span class="pre">False</span></code> for this parameter if you wish.</p>
<p class="last">The dictionary passed to <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code></a> can also specify a Boolean
value with key <code class="docutils literal notranslate"><span class="pre">disable_existing_loggers</span></code>, which if not specified
explicitly in the dictionary also defaults to being interpreted as
<code class="docutils literal notranslate"><span class="pre">True</span></code>. This leads to the logger-disabling behaviour described above,
which may not be what you want - in which case, provide the key
explicitly with a value of <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</div>
<p>Note that the class names referenced in config files need to be either relative
to the logging module, or absolute values which can be resolved using normal
import mechanisms. Thus, you could use either
<a class="reference internal" href="../library/logging.handlers.html#logging.handlers.WatchedFileHandler" title="logging.handlers.WatchedFileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">WatchedFileHandler</span></code></a> (relative to the logging module) or
<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>
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
path).</p>
<p>In Python 3.2, a new means of configuring logging has been introduced, using
dictionaries to hold configuration information. This provides a superset of the
functionality of the config-file-based approach outlined above, and is the
recommended configuration method for new applications and deployments. Because
a Python dictionary is used to hold configuration information, and since you
can populate that dictionary using different means, you have more options for
configuration. For example, you can use a configuration file in JSON format,
or, if you have access to YAML processing functionality, a file in YAML
format, to populate the configuration dictionary. Or, of course, you can
construct the dictionary in Python code, receive it in pickled form over a
socket, or use whatever approach makes sense for your application.</p>
<p>Here’s an example of the same configuration as above, in YAML format for
the new dictionary-based approach:</p>
<div class="highlight-yaml notranslate"><div class="highlight"><pre><span></span><span class="l l-Scalar l-Scalar-Plain">version</span><span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">1</span>
<span class="l l-Scalar l-Scalar-Plain">formatters</span><span class="p p-Indicator">:</span>
<span class="l l-Scalar l-Scalar-Plain">simple</span><span class="p p-Indicator">:</span>
<span class="l l-Scalar l-Scalar-Plain">format</span><span class="p p-Indicator">:</span> <span class="s">'%(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'</span>
<span class="l l-Scalar l-Scalar-Plain">handlers</span><span class="p p-Indicator">:</span>
<span class="l l-Scalar l-Scalar-Plain">console</span><span class="p p-Indicator">:</span>
<span class="l l-Scalar l-Scalar-Plain">class</span><span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">logging.StreamHandler</span>
<span class="l l-Scalar l-Scalar-Plain">level</span><span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">DEBUG</span>
<span class="l l-Scalar l-Scalar-Plain">formatter</span><span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">simple</span>
<span class="l l-Scalar l-Scalar-Plain">stream</span><span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">ext://sys.stdout</span>
<span class="l l-Scalar l-Scalar-Plain">loggers</span><span class="p p-Indicator">:</span>
<span class="l l-Scalar l-Scalar-Plain">simpleExample</span><span class="p p-Indicator">:</span>
<span class="l l-Scalar l-Scalar-Plain">level</span><span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">DEBUG</span>
<span class="l l-Scalar l-Scalar-Plain">handlers</span><span class="p p-Indicator">:</span> <span class="p p-Indicator">[</span><span class="nv">console</span><span class="p p-Indicator">]</span>
<span class="l l-Scalar l-Scalar-Plain">propagate</span><span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">no</span>
<span class="l l-Scalar l-Scalar-Plain">root</span><span class="p p-Indicator">:</span>
<span class="l l-Scalar l-Scalar-Plain">level</span><span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">DEBUG</span>
<span class="l l-Scalar l-Scalar-Plain">handlers</span><span class="p p-Indicator">:</span> <span class="p p-Indicator">[</span><span class="nv">console</span><span class="p p-Indicator">]</span>
</pre></div>
</div>
<p>For more information about logging using a dictionary, see
<a class="reference internal" href="../library/logging.config.html#logging-config-api"><span class="std std-ref">Configuration functions</span></a>.</p>
</div>
<div class="section" id="what-happens-if-no-configuration-is-provided">
<h3>What happens if no configuration is provided<a class="headerlink" href="#what-happens-if-no-configuration-is-provided" title="本標題的永久連結">¶</a></h3>
<p>If no logging configuration is provided, it is possible to have a situation
where a logging event needs to be output, but no handlers can be found to
output the event. The behaviour of the logging package in these
circumstances is dependent on the Python version.</p>
<p>For versions of Python prior to 3.2, the behaviour is as follows:</p>
<ul class="simple">
<li>If <em>logging.raiseExceptions</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code> (production mode), the event is
silently dropped.</li>
<li>If <em>logging.raiseExceptions</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code> (development mode), a message
『No handlers could be found for logger X.Y.Z』 is printed once.</li>
</ul>
<p>In Python 3.2 and later, the behaviour is as follows:</p>
<ul class="simple">
<li>The event is output using a 『handler of last resort』, stored in
<code class="docutils literal notranslate"><span class="pre">logging.lastResort</span></code>. This internal handler is not associated with any
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
event description message to the current value of <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> (therefore
respecting any redirections which may be in effect). No formatting is
done on the message - just the bare event description message is printed.
The handler’s level is set to <code class="docutils literal notranslate"><span class="pre">WARNING</span></code>, so all events at this and
greater severities will be output.</li>
</ul>
<p>To obtain the pre-3.2 behaviour, <code class="docutils literal notranslate"><span class="pre">logging.lastResort</span></code> can be set to <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</div>
<div class="section" id="configuring-logging-for-a-library">
<span id="library-config"></span><h3>Configuring Logging for a Library<a class="headerlink" href="#configuring-logging-for-a-library" title="本標題的永久連結">¶</a></h3>
<p>When developing a library which uses logging, you should take care to
document how the library uses logging - for example, the names of loggers
used. Some consideration also needs to be given to its logging configuration.
If the using application does not use logging, and library code makes logging
calls, then (as described in the previous section) events of severity
<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
the best default behaviour.</p>
<p>If for some reason you <em>don’t</em> want these messages printed in the absence of
any logging configuration, you can attach a do-nothing handler to the top-level
logger for your library. This avoids the message being printed, since a handler
will be always be found for the library’s events: it just doesn’t produce any
output. If the library user configures logging for application use, presumably
that configuration will add some handlers, and if levels are suitably
configured then logging calls made in library code will send output to those
handlers, as normal.</p>
<p>A do-nothing handler is included in the logging package:
<a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><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
could be added to the top-level logger of the logging namespace used by the
library (<em>if</em> you want to prevent your library’s logged events being output to
<code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> in the absence of logging configuration). If all logging by a
library <em>foo</em> is done using loggers with names matching 『foo.x』, 『foo.x.y』,
etc. then the code:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">'foo'</span><span class="p">)</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">NullHandler</span><span class="p">())</span>
</pre></div>
</div>
<p>should have the desired effect. If an organisation produces a number of
libraries, then the logger name specified can be 『orgname.foo』 rather than
just 『foo』.</p>
<div class="admonition note">
<p class="first admonition-title">備註</p>
<p class="last">It is strongly advised that you <em>do not add any handlers other
than</em> <a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><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
because the configuration of handlers is the prerogative of the application
developer who uses your library. The application developer knows their
target audience and what handlers are most appropriate for their
application: if you add handlers 『under the hood』, you might well interfere
with their ability to carry out unit tests and deliver logs which suit their
requirements.</p>
</div>
</div>
</div>
<div class="section" id="logging-levels">
<h2>Logging Levels<a class="headerlink" href="#logging-levels" title="本標題的永久連結">¶</a></h2>
<p>The numeric values of logging levels are given in the following table. These are
primarily of interest if you want to define your own levels, and need them to
have specific values relative to the predefined levels. If you define a level
with the same numeric value, it overwrites the predefined value; the predefined
name is lost.</p>
<table border="1" class="docutils">
<colgroup>
<col width="48%" />
<col width="52%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Level</th>
<th class="head">Numeric value</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">CRITICAL</span></code></td>
<td>50</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ERROR</span></code></td>
<td>40</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">WARNING</span></code></td>
<td>30</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">INFO</span></code></td>
<td>20</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">DEBUG</span></code></td>
<td>10</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">NOTSET</span></code></td>
<td>0</td>
</tr>
</tbody>
</table>
<p>Levels can also be associated with loggers, being set either by the developer or
through loading a saved logging configuration. When a logging method is called
on a logger, the logger compares its own level with the level associated with
the method call. If the logger’s level is higher than the method call’s, no
logging message is actually generated. This is the basic mechanism controlling
the verbosity of logging output.</p>
<p>Logging messages are encoded as instances of the <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a>
class. When a logger decides to actually log an event, a
<a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> instance is created from the logging message.</p>
<p>Logging messages are subjected to a dispatch mechanism through the use of
<em class="dfn">handlers</em>, which are instances of subclasses of the <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. Handlers are responsible for ensuring that a logged message (in the form
of a <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><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)
which is useful for the target audience for that message (such as end users,
support desk staff, system administrators, developers). Handlers are passed
<a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> instances intended for particular destinations. Each logger
can have zero, one or more handlers associated with it (via the
<a class="reference internal" href="../library/logging.html#logging.Logger.addHandler" title="logging.Logger.addHandler"><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
handlers directly associated with a logger, <em>all handlers associated with all
ancestors of the logger</em> are called to dispatch the message (unless the
<em>propagate</em> flag for a logger is set to a false value, at which point the
passing to ancestor handlers stops).</p>
<p>Just as for loggers, handlers can have levels associated with them. A handler’s
level acts as a filter in the same way as a logger’s level does. If a handler
decides to actually dispatch an event, the <a class="reference internal" href="../library/logging.html#logging.Handler.emit" title="logging.Handler.emit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">emit()</span></code></a> method is used
to send the message to its destination. Most user-defined subclasses of
<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>
<div class="section" id="custom-levels">
<span id="id1"></span><h3>Custom Levels<a class="headerlink" href="#custom-levels" title="本標題的永久連結">¶</a></h3>
<p>Defining your own levels is possible, but should not be necessary, as the
existing levels have been chosen on the basis of practical experience.
However, if you are convinced that you need custom levels, great care should
be exercised when doing this, and it is possibly <em>a very bad idea to define
custom levels if you are developing a library</em>. That’s because if multiple
library authors all define their own custom levels, there is a chance that
the logging output from such multiple libraries used together will be
difficult for the using developer to control and/or interpret, because a
given numeric value might mean different things for different libraries.</p>
</div>
</div>
<div class="section" id="useful-handlers">
<span id="id2"></span><h2>Useful Handlers<a class="headerlink" href="#useful-handlers" title="本標題的永久連結">¶</a></h2>
<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
provided:</p>
<ol class="arabic simple">
<li><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
objects).</li>
<li><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.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.BaseRotatingHandler" title="logging.handlers.BaseRotatingHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseRotatingHandler</span></code></a> is the base class for handlers that
rotate log files at a certain point. It is not meant to be instantiated
directly. Instead, use <a class="reference internal" href="../library/logging.handlers.html#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">RotatingFileHandler</span></code></a> or
<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>.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">RotatingFileHandler</span></code></a> instances send messages to disk
files, with support for maximum log file sizes and log file rotation.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler" title="logging.handlers.TimedRotatingFileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">TimedRotatingFileHandler</span></code></a> instances send messages to
disk files, rotating the log file at certain timed intervals.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SocketHandler</span></code></a> instances send messages to TCP/IP
sockets. Since 3.4, Unix domain sockets are also supported.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.DatagramHandler" title="logging.handlers.DatagramHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">DatagramHandler</span></code></a> instances send messages to UDP
sockets. Since 3.4, Unix domain sockets are also supported.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SMTPHandler" title="logging.handlers.SMTPHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SMTPHandler</span></code></a> instances send messages to a designated
email address.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SysLogHandler</span></code></a> instances send messages to a Unix
syslog daemon, possibly on a remote machine.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.NTEventLogHandler" title="logging.handlers.NTEventLogHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">NTEventLogHandler</span></code></a> instances send messages to a
Windows NT/2000/XP event log.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.MemoryHandler" title="logging.handlers.MemoryHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">MemoryHandler</span></code></a> instances send messages to a buffer
in memory, which is flushed whenever specific criteria are met.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.HTTPHandler" title="logging.handlers.HTTPHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPHandler</span></code></a> instances send messages to an HTTP
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.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.WatchedFileHandler" title="logging.handlers.WatchedFileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">WatchedFileHandler</span></code></a> instances watch the file they are
logging to. If the file changes, it is closed and reopened using the file
name. This handler is only useful on Unix-like systems; Windows does not
support the underlying mechanism used.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.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
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.</li>
<li><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
by library developers who want to use logging, but want to avoid the 『No
handlers could be found for logger XXX』 message which can be displayed if
the library user has not configured logging. See <a class="reference internal" href="#library-config"><span class="std std-ref">Configuring Logging for a Library</span></a> for
more information.</li>
</ol>
<div class="versionadded">
<p><span class="versionmodified">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>
</div>
<div class="versionadded">
<p><span class="versionmodified">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>
</div>
<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>
classes are defined in the core logging package. The other handlers are
defined in a sub- module, <a class="reference internal" href="../library/logging.handlers.html#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a>. (There is also another
sub-module, <a class="reference internal" href="../library/logging.config.html#module-logging.config" title="logging.config: Configuration of the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.config</span></code></a>, for configuration functionality.)</p>
<p>Logged messages are formatted for presentation through instances of the
<a class="reference internal" href="../library/logging.html#logging.Formatter" title="logging.Formatter"><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
use with the % operator and a dictionary.</p>
<p>For formatting multiple messages in a batch, instances of
<code class="xref py py-class docutils literal notranslate"><span class="pre">BufferingFormatter</span></code> can be used. In addition to the format
string (which is applied to each message in the batch), there is provision for
header and trailer format strings.</p>
<p>When filtering based on logger level and/or handler level is not enough,
instances of <a class="reference internal" href="../library/logging.html#logging.Filter" title="logging.Filter"><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
<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).
Before deciding to process a message further, both loggers and handlers consult
all their filters for permission. If any filter returns a false value, the
message is not processed further.</p>
<p>The basic <a class="reference internal" href="../library/logging.html#logging.Filter" title="logging.Filter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Filter</span></code></a> functionality allows filtering by specific logger
name. If this feature is used, messages sent to the named logger and its
children are allowed through the filter, and all others dropped.</p>
</div>
<div class="section" id="exceptions-raised-during-logging">
<span id="logging-exceptions"></span><h2>Exceptions raised during logging<a class="headerlink" href="#exceptions-raised-during-logging" title="本標題的永久連結">¶</a></h2>
<p>The logging package is designed to swallow exceptions which occur while logging
in production. This is so that errors which occur while handling logging events
- such as logging misconfiguration, network or other similar errors - do not
cause the application using logging to terminate prematurely.</p>
<p><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
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
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>