File size: 69,753 Bytes
9273228
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
# Logging HOWTO

Author
:   Vinay Sajip \<vinay_sajip at red-dove dot com\>

:::: {#logging-basic-tutorial}
::: currentmodule
logging
:::
::::

This page contains tutorial information. For links to reference information and a logging cookbook, please see `tutorial-ref-links`{.interpreted-text role="ref"}.

## Basic Logging Tutorial

Logging is a means of tracking events that happen when some software runs. The software\'s developer adds logging calls to their code to indicate that certain events have occurred. An event is described by a descriptive message which can optionally contain variable data (i.e. data that is potentially different for each occurrence of the event). Events also have an importance which the developer ascribes to the event; the importance can also be called the *level* or *severity*.

### When to use logging

You can access logging functionality by creating a logger via `logger = getLogger(__name__)`, and then calling the logger\'s `~Logger.debug`{.interpreted-text role="meth"}, `~Logger.info`{.interpreted-text role="meth"}, `~Logger.warning`{.interpreted-text role="meth"}, `~Logger.error`{.interpreted-text role="meth"} and `~Logger.critical`{.interpreted-text role="meth"} methods. To determine when to use logging, and to see which logger methods to use when, see the table below. It states, for each of a set of common tasks, the best tool to use for that task.

+-------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Task you want to perform                                                                                          | The best tool for the task                                                                                                                                                                                                              |
+===================================================================================================================+=========================================================================================================================================================================================================================================+
| Display console output for ordinary usage of a command line script or program                                     | `print`{.interpreted-text role="func"}                                                                                                                                                                                                  |
+-------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Report events that occur during normal operation of a program (e.g. for status monitoring or fault investigation) | A logger\'s `~Logger.info`{.interpreted-text role="meth"} (or `~Logger.debug`{.interpreted-text role="meth"} method for very detailed output for diagnostic purposes)                                                                   |
+-------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Issue a warning regarding a particular runtime event                                                              | `warnings.warn`{.interpreted-text role="func"} in library code if the issue is avoidable and the client application should be modified to eliminate the warning                                                                         |
|                                                                                                                   |                                                                                                                                                                                                                                         |
|                                                                                                                   | A logger\'s `~Logger.warning`{.interpreted-text role="meth"} method if there is nothing the client application can do about the situation, but the event should still be noted                                                          |
+-------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Report an error regarding a particular runtime event                                                              | Raise an exception                                                                                                                                                                                                                      |
+-------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Report suppression of an error without raising an exception (e.g. error handler in a long-running server process) | A logger\'s `~Logger.error`{.interpreted-text role="meth"}, `~Logger.exception`{.interpreted-text role="meth"} or `~Logger.critical`{.interpreted-text role="meth"} method as appropriate for the specific error and application domain |
+-------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

The logger methods 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):

::: tabularcolumns
[\|l\|](##SUBST##|l|)L\|
:::

  -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  Level          When it\'s used
  -------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  `DEBUG`        Detailed information, typically of interest only when diagnosing problems.

  `INFO`         Confirmation that things are working as expected.

  `WARNING`      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.

  `ERROR`        Due to a more serious problem, the software has not been able to perform some function.

  `CRITICAL`     A serious error, indicating that the program itself may be unable to continue running.
  -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

The default level is `WARNING`, which means that only events of this severity and higher will be tracked, unless the logging package is configured to do otherwise.

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.

### A simple example {#howto-minimal-example}

A very simple example is:

    import logging
    logging.warning('Watch out!')  # will print a message to the console
    logging.info('I told you so')  # will not print anything

If you type these lines into a script and run it, you\'ll see:

``` none
WARNING:root:Watch out!
```

printed out on the console. The `INFO` message doesn\'t appear because the default level is `WARNING`. The printed message includes the indication of the level and the description of the event provided in the logging call, i.e. \'Watch out!\'. The actual output can be formatted quite flexibly if you need that; formatting options will also be explained later.

Notice that in this example, we use functions directly on the `logging` module, like `logging.debug`, rather than creating a logger and calling functions on it. These functions operate on the root logger, but can be useful as they will call `~logging.basicConfig`{.interpreted-text role="func"} for you if it has not been called yet, like in this example. In larger programs you\'ll usually want to control the logging configuration explicitly however - so for that reason as well as others, it\'s better to create loggers and call their methods.

### Logging to a file

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:

    import logging
    logger = logging.getLogger(__name__)
    logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
    logger.debug('This message should go to the log file')
    logger.info('So should this')
    logger.warning('And this, too')
    logger.error('And non-ASCII stuff, too, like Øresund and Malmö')

::: versionchanged
3.9 The *encoding* argument was added. In earlier Python versions, or if not specified, the encoding used is the default value used by `open`{.interpreted-text role="func"}. While not shown in the above example, an *errors* argument can also now be passed, which determines how encoding errors are handled. For available values and the default, see the documentation for `open`{.interpreted-text role="func"}.
:::

And now if we open the file and look at what we have, we should find the log messages:

``` none
DEBUG:__main__:This message should go to the log file
INFO:__main__:So should this
WARNING:__main__:And this, too
ERROR:__main__:And non-ASCII stuff, too, like Øresund and Malmö
```

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 `DEBUG`, all of the messages were printed.

If you want to set the logging level from a command-line option such as:

``` none
--log=INFO
```

and you have the value of the parameter passed for `--log` in some variable *loglevel*, you can use:

    getattr(logging, loglevel.upper())

to get the value which you\'ll pass to `basicConfig`{.interpreted-text role="func"} via the *level* argument. You may want to error check any user input value, perhaps as in the following example:

    # assuming loglevel is bound to the string value obtained from the
    # command line argument. Convert to upper case to allow the user to
    # specify --log=DEBUG or --log=debug
    numeric_level = getattr(logging, loglevel.upper(), None)
    if not isinstance(numeric_level, int):
        raise ValueError('Invalid log level: %s' % loglevel)
    logging.basicConfig(level=numeric_level, ...)

The call to `basicConfig`{.interpreted-text role="func"} should come *before* any calls to a logger\'s methods such as `~Logger.debug`{.interpreted-text role="meth"}, `~Logger.info`{.interpreted-text role="meth"}, etc. Otherwise, that logging event may not be handled in the desired manner.

If you run the above script several times, the messages from successive runs are appended to the file *example.log*. If you want each run to start afresh, not remembering the messages from earlier runs, you can specify the *filemode* argument, by changing the call in the above example to:

    logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)

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.

### Logging variable data

To log variable data, use a format string for the event description message and append the variable data as arguments. For example:

    import logging
    logging.warning('%s before you %s', 'Look', 'leap!')

will display:

``` none
WARNING:root:Look before you leap!
```

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 `str.format`{.interpreted-text role="meth"} and `string.Template`{.interpreted-text role="class"}. These newer formatting options *are* supported, but exploring them is outside the scope of this tutorial: see `formatting-styles`{.interpreted-text role="ref"} for more information.

### Changing the format of displayed messages

To change the format which is used to display messages, you need to specify the format you want to use:

    import logging
    logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
    logging.debug('This message should appear on the console')
    logging.info('So should this')
    logging.warning('And this, too')

which would print:

``` none
DEBUG:This message should appear on the console
INFO:So should this
WARNING:And this, too
```

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 `logrecord-attributes`{.interpreted-text role="ref"}, but for simple usage, you just need the *levelname* (severity), *message* (event description, including variable data) and perhaps to display when the event occurred. This is described in the next section.

### Displaying the date/time in messages

To display the date and time of an event, you would place \'%(asctime)s\' in your format string:

    import logging
    logging.basicConfig(format='%(asctime)s %(message)s')
    logging.warning('is when this event was logged.')

which should print something like this:

``` none
2010-12-12 11:41:42,612 is when this event was logged.
```

The default format for date/time display (shown above) is like ISO8601 or `3339`{.interpreted-text role="rfc"}. If you need more control over the formatting of the date/time, provide a *datefmt* argument to `basicConfig`, as in this example:

    import logging
    logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
    logging.warning('is when this event was logged.')

which would display something like this:

``` none
12/12/2010 11:46:36 AM is when this event was logged.
```

The format of the *datefmt* argument is the same as supported by `time.strftime`{.interpreted-text role="func"}.

### Next Steps

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.

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 in the Help category of the [Python discussion forum](https://discuss.python.org/c/help/7) and you should receive help before too long.

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 `logging-cookbook`{.interpreted-text role="ref"}.

## Advanced Logging Tutorial {#logging-advanced-tutorial}

The logging library takes a modular approach and offers several categories of components: loggers, handlers, filters, and formatters.

- Loggers expose the interface that application code directly uses.
- Handlers send the log records (created by loggers) to the appropriate destination.
- Filters provide a finer grained facility for determining which log records to output.
- Formatters specify the layout of log records in the final output.

Log event information is passed between loggers, handlers, filters and formatters in a `LogRecord`{.interpreted-text role="class"} instance.

Logging is performed by calling methods on instances of the `Logger`{.interpreted-text role="class"} class (hereafter called `loggers`{.interpreted-text role="dfn"}). 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.

A good convention to use when naming loggers is to use a module-level logger, in each module which uses logging, named as follows:

    logger = logging.getLogger(__name__)

This means that logger names track the package/module hierarchy, and it\'s intuitively obvious where events are logged just from the logger name.

The root of the hierarchy of loggers is called the root logger. That\'s the logger used by the functions `debug`{.interpreted-text role="func"}, `info`{.interpreted-text role="func"}, `warning`{.interpreted-text role="func"}, `error`{.interpreted-text role="func"} and `critical`{.interpreted-text role="func"}, 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.

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 `handler`{.interpreted-text role="dfn"} classes. You can create your own log destination class if you have special requirements not met by any of the built-in handler classes.

By default, no destination is set for any logging messages. You can specify a destination (such as console or file) by using `basicConfig`{.interpreted-text role="func"} as in the tutorial examples. If you call the functions `debug`{.interpreted-text role="func"}, `info`{.interpreted-text role="func"}, `warning`{.interpreted-text role="func"}, `error`{.interpreted-text role="func"} and `critical`{.interpreted-text role="func"}, they will check to see if no destination is set; and if one is not set, they will set a destination of the console (`sys.stderr`) and a default format for the displayed message before delegating to the root logger to do the actual message output.

The default format set by `basicConfig`{.interpreted-text role="func"} for messages is:

``` none
severity:logger name:message
```

You can change this by passing a format string to `basicConfig`{.interpreted-text role="func"} with the *format* keyword argument. For all options regarding how a format string is constructed, see `formatter-objects`{.interpreted-text role="ref"}.

### Logging Flow

The flow of log event information in loggers and handlers is illustrated in the following diagram.

::: only
not html

![image](logging_flow.*)
:::

<svg width="22cm" height="23cm" viewBox="1 1 439 446" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <!-- Invert color in dark mode -->
  <style type="text/css">
    svg {
      background-color: transparent !important;
    }
    line {
      stroke: #000000;
      fill: none;
      stroke-opacity: 1;
    }
    polygon, rect {
      fill: none;
      stroke: #000000;
      fill-opacity: 1;
      stroke-opacity: 1;
    }
    polygon.filled {
      fill: #000000;
    }
    polyline {
      fill: none;
      stroke-opacity: 1;
      stroke: #000000;
    }
    text {
      fill: #000000;
      fill-opacity: 1;
      stroke: none;
      font-family: sans-serif;
      font-style: normal;
      font-weight: normal;
      text-anchor: start;
    }
    @media (prefers-color-scheme: dark) {
      polygon, rect, polyline, line {
        stroke: #ffffff;
      }
      polygon.filled {
        fill: #ffffff;
      }
      text {
        fill: #ffffff;
      }
      image {
        filter: invert(100%) hue-rotate(180deg) saturate(1.25);
      }
    }
    /* These rules are for when the theme selector is used, perhaps in contrast to the browser theme. */
    body.dark-theme polygon, body.dark-theme rect, body.dark-theme polyline, body.dark-theme line {
      stroke: #ffffff;
    }
    body.dark-theme polygon.filled {
      fill: #ffffff;
    }
    body.dark-theme text {
      fill: #ffffff;
    }
    body.light-theme polygon, body.light-theme rect, body.light-theme polyline, body.light-theme line {
      stroke: #000000;
    }
    body.light-theme polygon.filled {
      fill: #000000;
    }
    body.light-theme text {
      fill: #000000;
    }
  </style>

  <defs />
  <g id="Background">
    <rect style="stroke-width: 1.8; stroke-dasharray: 3;" x="227.504" y="1.91011" width="211.607" height="207.375" rx="0" ry="0" />
    <rect style="stroke-width: 1.2;" x="230.966" y="5.62454" width="68.4216" height="21.9166" rx="0" ry="0" />
    <rect style="stroke-width: 1.2;" x="5.27912" y="5.70399" width="68.4216" height="21.9166" rx="0" ry="0" />
    <text font-size="6.77333" style="font-weight: 700;" x="17.0649" y="19.0071">
      <tspan x="17.0649" y="19.0071">Logger flow</tspan>
    </text>
    <g>
      <rect x="81.5533" y="106.469" width="44.45" height="25.9333" rx="0" ry="0" />
      <text font-size="6.77333" style="text-anchor: middle;" x="103.778" y="117.256">
        <tspan x="103.778" y="117.256">Create</tspan>
        <tspan x="103.778" y="125.723" style="font-family: monospace">LogRecord</tspan>
      </text>
    </g>
    <g>
      <line x1="103.778" y1="82.8734" x2="103.778" y2="102.351" />
      <polygon fill-rule="evenodd" points="103.778,105.351 101.778,101.351 103.778,102.351 105.778,101.351 " />
    </g>
    <g>
      <line x1="103.774" y1="3.65583" x2="103.778" y2="30.3755" />
      <polygon fill-rule="evenodd" points="103.778,33.3755 101.778,29.3758 103.778,30.3755 105.778,29.3752 " />
    </g>
    <text font-size="6.77333" style="text-anchor: middle;" x="144.365" y="10.4604">
      <tspan x="143.798" y="10.4604">Logging call in user</tspan>
      <tspan x="143.798" y="18.927">code, e.g.</tspan>
    </text>
    <text font-size="6.77333" style="font-family: monospace;" x="110.837" y="27.4696">
      <tspan x="111.893" y="27.4696">logger.info(...)</tspan>
    </text>
    <g>
      <line x1="155.62" y1="58.6834" x2="183.943" y2="58.6924" />
      <polygon fill-rule="evenodd" points="186.943,58.6933 182.942,60.6921 183.943,58.6924 182.943,56.6921 " />
    </g>
    <g>
      <rect x="188.061" y="49.9604" width="24.4" height="17.4667" rx="6" ry="6" />
      <text font-size="6.77333" style="text-anchor: middle;" x="200.261" y="60.7475">
        <tspan x="200.261" y="60.7475">Stop</tspan>
      </text>
    </g>
    <g>
      <polygon fill-rule="evenodd" points="103.778,162.482 169.307,193.042 103.778,223.603 38.2493,193.042 " />
      <text font-size="6.77333" style="text-anchor: middle;" x="103.778" y="186.629">
        <tspan x="103.778" y="188.741">Does a filter attached</tspan>
        <tspan x="103.778" y="197.208">to logger reject the</tspan>
        <tspan x="103.778" y="205.675">record?</tspan>
      </text>
    </g>
    <g>
      <line x1="103.778" y1="132.402" x2="103.778" y2="158.364" />
      <polygon class="filled" fill-rule="evenodd" points="103.778,161.364 101.778,157.364 103.778,158.364 105.778,157.364 " />
    </g>
    <g>
      <rect x="75.2033" y="249.478" width="57.15" height="34.4" rx="0" ry="0" />
      <text font-size="6.77333" style="text-anchor: middle;" x="103.778" y="260.265">
        <tspan x="103.778" y="260.265">Pass record to</tspan>
        <tspan x="103.778" y="268.732">handlers of</tspan>
        <tspan x="103.778" y="277.198">current logger</tspan>
      </text>
    </g>
    <g>
      <polygon fill-rule="evenodd" points="103.778,326.569 158.193,352.399 103.778,378.229 49.3637,352.399 " />
      <text font-size="6.77333" style="text-anchor: middle;" x="103.778" y="350.22">
        <tspan x="103.778" y="351.276">Is propagate true for</tspan>
        <tspan x="103.778" y="359.742">current logger?</tspan>
      </text>
    </g>
    <g>
      <polygon fill-rule="evenodd" points="103.778,399.9 150.573,422.994 103.778,446.087 56.984,422.994 " />
      <text font-size="6.77333" style="text-anchor: middle;" x="103.778" y="420.814">
        <tspan x="103.778" y="422.926">Is there a parent</tspan>
        <tspan x="103.778" y="431.393">logger?</tspan>
      </text>
    </g>
    <g>
      <rect x="2.43852" y="295.984" width="63.9" height="26.5909" rx="0" ry="0" />
      <text font-size="6.77333" style="text-anchor: middle;" x="34.3885" y="307.1">
        <tspan x="34.3885" y="307.1">Set current</tspan>
        <tspan x="34.3885" y="315.566">logger to parent</tspan>
      </text>
    </g>
    <g>
      <polygon fill-rule="evenodd" points="278.422,240.202 330.96,266.686 278.422,293.169 225.885,266.686 " />
      <text font-size="6.77333" style="text-anchor: middle;" x="278.422" y="264.506">
        <tspan x="278.422" y="266.618">At least one handler</tspan>
        <tspan x="278.422" y="275.085">in hierarchy?</tspan>
      </text>
    </g>
    <g>
      <rect x="298.963" y="312.257" width="57.75" height="25.9333" rx="0" ry="0" />
      <text font-size="6.77333" x="327.838" y="323.044">
        <tspan x="301" y="324.100">Use</tspan>
        <tspan x="315" y="324.100" style="font-family: monospace">lastResort</tspan>
        <tspan x="316" y="332.567">handler</tspan>
      </text>
    </g>
    <g>
      <polygon fill-rule="evenodd" points="320.041,35.7307 373.377,60.8536 320.041,85.9765 266.704,60.8536 " />
      <text font-size="6.77333" style="text-anchor: middle;" x="320.041" y="58.6741">
        <tspan x="320.041" y="58.6741">Handler enabled for</tspan>
        <tspan x="320.041" y="67.1407">level of record?</tspan>
      </text>
    </g>
    <g>
      <polygon fill-rule="evenodd" points="320.041,105.448 386.002,135.748 320.041,166.047 254.08,135.748 " />
      <text font-size="6.77333" style="text-anchor: middle;" x="320.041" y="129.335">
        <tspan x="320.041" y="132.508">Does a filter attached</tspan>
        <tspan x="320.041" y="140.970">to handler reject the</tspan>
        <tspan x="320.041" y="149.436">record?</tspan>
      </text>
    </g>
    <g>
      <rect x="409.532" y="52.4436" width="24.4" height="17.4667" rx="6" ry="6" />
      <text font-size="6.77333" style="text-anchor: middle;" x="421.732" y="63.2307">
        <tspan x="421.732" y="63.2307">Stop</tspan>
      </text>
    </g>
    <g>
      <rect x="271.091" y="185.519" width="97.9" height="17.4667" rx="6" ry="6" />
      <text font-size="6.77333" style="text-anchor: middle;" x="320.041" y="196.306">
        <tspan x="320.041" y="196.306">Emit (includes formatting)</tspan>
      </text>
    </g>
    <text font-size="6.77333" style="font-weight: 700;" x="241.002" y="18.9277">
      <tspan x="241.002" y="18.9277">Handler flow</tspan>
    </text>
    <g>
      <polygon fill-rule="evenodd" points="103.778,34.4935 155.62,58.6834 103.778,82.8734 51.9368,58.6834 " />
      <text font-size="6.77333" style="text-anchor: middle;" x="103.778" y="56.5039">
        <tspan x="103.778" y="57.560">Logger enabled for</tspan>
        <tspan x="103.778" y="66.026">level of call?</tspan>
      </text>
    </g>
    <g>
      <line x1="103.778" y1="223.603" x2="103.778" y2="245.36" />
      <polygon class="filled" fill-rule="evenodd" points="103.778,248.36 101.778,244.36 103.778,245.36 105.778,244.36 " />
    </g>
    <g>
      <line x1="103.778" y1="283.878" x2="103.778" y2="322.451" />
      <polygon class="filled" fill-rule="evenodd" points="103.778,325.451 101.778,321.451 103.778,322.451 105.778,321.451 " />
    </g>
    <g>
      <line x1="103.778" y1="378.229" x2="103.778" y2="395.782" />
      <polygon class="filled" fill-rule="evenodd" points="103.778,398.782 101.778,394.782 103.778,395.782 105.778,394.782 " />
    </g>
    <g>
      <polyline points="56.984,422.994 34.3885,422.994 34.3885,326.693 " />
      <polygon class="filled" fill-rule="evenodd" points="34.3885,323.693 36.3885,327.693 34.3885,326.693 32.3885,327.693 " />
    </g>
    <g>
      <polyline points="34.3885,295.984 34.3885,266.678 71.0853,266.678 " />
      <polygon class="filled" fill-rule="evenodd" points="74.0853,266.678 70.0853,268.678 71.0853,266.678 70.0853,264.678 " />
    </g>
    <g>
      <polyline points="150.573,422.994 200.261,422.994 200.261,71.5451 " />
      <polygon class="filled" fill-rule="evenodd" points="200.261,68.5451 202.261,72.5451 200.261,71.5451 198.261,72.5451 " />
    </g>
    <g>
      <line style="stroke-dasharray: 5" x1="132.353" y1="266.678" x2="221.767" y2="266.685" />
      <polygon class="filled" fill-rule="evenodd" points="224.767,266.686 220.766,268.685 221.767,266.685 220.767,264.685 " />
    </g>
    <g>
      <polyline style="stroke-dasharray: 5" points="278.422,293.169 278.422,325.224 294.845,325.224 " />
      <polygon class="filled" fill-rule="evenodd" points="297.845,325.224 293.845,327.224 294.845,325.224 293.845,323.224 " />
    </g>
    <g>
      <polyline points="169.307,193.042 200.261,193.042 200.261,71.5451 " />
      <polygon class="filled" fill-rule="evenodd" points="200.261,68.5451 202.261,72.5451 200.261,71.5451 198.261,72.5451 " />
    </g>
    <g>
      <polyline points="158.193,352.399 200.261,352.399 200.261,71.5451 " />
      <polygon class="filled" fill-rule="evenodd" points="200.261,68.5451 202.261,72.5451 200.261,71.5451 198.261,72.5451 " />
    </g>
    <g>
      <line x1="319.981" y1="4.27261" x2="320.033" y2="31.6127" />
      <polygon class="filled" fill-rule="evenodd" points="320.039,34.6127 318.031,30.6165 320.033,31.6127 322.031,30.6089 " />
    </g>
    <g>
      <line x1="320.041" y1="85.9765" x2="320.041" y2="101.33" />
      <polygon class="filled" fill-rule="evenodd" points="320.041,104.33 318.041,100.33 320.041,101.33 322.041,100.33 " />
    </g>
    <g>
      <line x1="320.041" y1="166.047" x2="320.041" y2="181.401" />
      <polygon class="filled" fill-rule="evenodd" points="320.041,184.401 318.041,180.401 320.041,181.401 322.041,180.401 " />
    </g>
    <g>
      <polyline points="386.002,135.748 421.732,135.748 421.732,74.0283 " />
      <polygon class="filled" fill-rule="evenodd" points="421.732,71.0283 423.732,75.0283 421.732,74.0283 419.732,75.0283 " />
    </g>
    <g>
      <line x1="373.377" y1="60.8536" x2="405.415" y2="61.1401" />
      <polygon class="filled" fill-rule="evenodd" points="408.414,61.1669 404.397,63.1311 405.415,61.1401 404.433,59.1312 " />
    </g>
    <text font-size="6.77333" x="164.96" y="55.5649">
      <tspan x="164.96" y="55.5649">No</tspan>
    </text>
    <text font-size="6.77333" x="106.571" y="97.8453">
      <tspan x="106.571" y="97.8453">Yes</tspan>
    </text>
    <text font-size="6.77333" x="173.856" y="188.452">
      <tspan x="173.856" y="188.452">Yes</tspan>
    </text>
    <text font-size="6.77333" x="107.446" y="239.221">
      <tspan x="107.446" y="239.221">No</tspan>
    </text>
    <text font-size="6.77333" x="174.731" y="349.418">
      <tspan x="174.731" y="349.418">No</tspan>
    </text>
    <text font-size="6.77333" x="106.571" y="390.507">
      <tspan x="106.571" y="390.507">Yes</tspan>
    </text>
    <text font-size="6.77333" x="39.4722" y="417.667">
      <tspan x="39.4722" y="417.667">Yes</tspan>
    </text>
    <text font-size="6.77333" x="174.731" y="417.667">
      <tspan x="174.731" y="417.667">No</tspan>
    </text>
    <text font-size="6.77333" x="281.451" y="313.406">
      <tspan x="281.451" y="313.406">No</tspan>
    </text>
    <text font-size="6.77333" x="333.909" y="263.96">
      <tspan x="333.909" y="263.96">Yes</tspan>
    </text>
    <text font-size="6.77333" x="333.307" y="105.598">
      <tspan x="333.307" y="105.598"></tspan>
    </text>
    <text font-size="6.77333" x="385.766" y="56.9098">
      <tspan x="385.766" y="56.9098">No</tspan>
    </text>
    <text font-size="6.77333" x="333.307" y="105.598">
      <tspan x="333.307" y="105.598"></tspan>
    </text>
    <text font-size="6.77333" x="333.307" y="105.598">
      <tspan x="333.307" y="105.598"></tspan>
    </text>
    <text font-size="6.77333" x="397.102" y="130.471">
      <tspan x="397.102" y="130.471">Yes</tspan>
    </text>
    <text font-size="6.77333" x="323.563" y="178.785">
      <tspan x="323.563" y="178.785">No</tspan>
    </text>
    <text font-size="6.77333" x="333.307" y="105.598">
      <tspan x="333.307" y="105.598"></tspan>
    </text>
    <text font-size="6.77333" x="323.75" y="99.0042">
      <tspan x="323.75" y="99.0042">Yes</tspan>
    </text>
    <text font-size="6.77323" style="text-anchor: middle;" x="355.762" y="18.2449">
      <tspan x="355.762" y="18.2449">Record passed</tspan>
      <tspan x="355.762" y="26.7116">to handler</tspan>
    </text>
    <line style="stroke-dasharray: 5" x1="330.96" y1="266.686" x2="377.733" y2="267.908" />
    <g>
      <polyline style="fill: none; stroke-opacity: 1; stroke-dasharray: 5" points="356.713,325.224 377.733,325.224 377.733,214.711 " />
      <polygon class="filled" fill-rule="evenodd" points="377.733,211.711 379.733,215.711 377.733,214.711 375.733,215.711 " />
    </g>
  </g>
</svg>
<script>
/*
 * This snippet is needed to handle the case where a light or dark theme is
 * chosen via the theme is selected in the page. We call the existing handler
 * and then add a dark-theme class to the body when the dark theme is selected.
 * The SVG styling (above) then does the rest.
 *
 * If the pydoc theme is updated to set the dark-theme class, this snippet
 * won't be needed any more.
 */
(function() {
  var oldActivateTheme = activateTheme;

  function updateBody(theme) {
     let elem = document.body;

     elem.classList.remove('dark-theme');
     elem.classList.remove('light-theme');
     if (theme === 'dark') {
         elem.classList.add('dark-theme');
     }
     else if (theme === 'light') {
         elem.classList.add('light-theme');
     }
  }

  activateTheme = function(theme) {
     oldActivateTheme(theme);
     updateBody(theme);
  };
  /*
   * If the page is refreshed, make sure we update the body - the overriding
   * of activateTheme won't have taken effect yet.
   */
   updateBody(localStorage.getItem('currentTheme') || 'auto');
})();
</script>

### Loggers

`Logger`{.interpreted-text role="class"} 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.

The most widely used methods on logger objects fall into two categories: configuration and message sending.

These are the most common configuration methods:

- `Logger.setLevel`{.interpreted-text role="meth"} 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.
- `Logger.addHandler`{.interpreted-text role="meth"} and `Logger.removeHandler`{.interpreted-text role="meth"} add and remove handler objects from the logger object. Handlers are covered in more detail in `handler-basic`{.interpreted-text role="ref"}.
- `Logger.addFilter`{.interpreted-text role="meth"} and `Logger.removeFilter`{.interpreted-text role="meth"} add and remove filter objects from the logger object. Filters are covered in more detail in `filter`{.interpreted-text role="ref"}.

You don\'t need to always call these methods on every logger you create. See the last two paragraphs in this section.

With the logger object configured, the following methods create log messages:

- `Logger.debug`{.interpreted-text role="meth"}, `Logger.info`{.interpreted-text role="meth"}, `Logger.warning`{.interpreted-text role="meth"}, `Logger.error`{.interpreted-text role="meth"}, and `Logger.critical`{.interpreted-text role="meth"} 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 `%s`, `%d`, `%f`, 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 `**kwargs`, the logging methods care only about a keyword of `exc_info` and use it to determine whether to log exception information.
- `Logger.exception`{.interpreted-text role="meth"} creates a log message similar to `Logger.error`{.interpreted-text role="meth"}. The difference is that `Logger.exception`{.interpreted-text role="meth"} dumps a stack trace along with it. Call this method only from an exception handler.
- `Logger.log`{.interpreted-text role="meth"} 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.

`getLogger`{.interpreted-text role="func"} returns a reference to a logger instance with the specified name if it is provided, or `root` if not. The names are period-separated hierarchical structures. Multiple calls to `getLogger`{.interpreted-text role="func"} 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 `foo`, loggers with names of `foo.bar`, `foo.bar.baz`, and `foo.bam` are all descendants of `foo`.

Loggers have a concept of *effective level*. 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, *its* 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 (`WARNING` 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.

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 *propagate* attribute of a logger to `False`.)

### Handlers {#handler-basic}

`~logging.Handler`{.interpreted-text role="class"} objects are responsible for dispatching the appropriate log messages (based on the log messages\' severity) to the handler\'s specified destination. `Logger`{.interpreted-text role="class"} objects can add zero or more handler objects to themselves with an `~Logger.addHandler`{.interpreted-text role="meth"} 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.

The standard library includes quite a few handler types (see `useful-handlers`{.interpreted-text role="ref"}); the tutorials use mainly `StreamHandler`{.interpreted-text role="class"} and `FileHandler`{.interpreted-text role="class"} in its examples.

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:

- The `~Handler.setLevel`{.interpreted-text role="meth"} method, just as in logger objects, specifies the lowest severity that will be dispatched to the appropriate destination. Why are there two `~Handler.setLevel`{.interpreted-text role="meth"} 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.
- `~Handler.setFormatter`{.interpreted-text role="meth"} selects a Formatter object for this handler to use.
- `~Handler.addFilter`{.interpreted-text role="meth"} and `~Handler.removeFilter`{.interpreted-text role="meth"} respectively configure and deconfigure filter objects on handlers.

Application code should not directly instantiate and use instances of `Handler`{.interpreted-text role="class"}. Instead, the `Handler`{.interpreted-text role="class"} 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).

### Formatters

Formatter objects configure the final order, structure, and contents of the log message. Unlike the base `logging.Handler`{.interpreted-text role="class"} 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.

::: method
logging.Formatter.\_\_init\_\_(fmt=None, datefmt=None, style=\'%\')
:::

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:

``` none
%Y-%m-%d %H:%M:%S
```

with the milliseconds tacked on at the end. The `style` is one of `'%'`, `'{'`, or `'$'`. If one of these is not specified, then `'%'` will be used.

If the `style` is `'%'`, the message format string uses `%(<dictionary key>)s` styled string substitution; the possible keys are documented in `logrecord-attributes`{.interpreted-text role="ref"}. If the style is `'{'`, the message format string is assumed to be compatible with `str.format`{.interpreted-text role="meth"} (using keyword arguments), while if the style is `'$'` then the message format string should conform to what is expected by `string.Template.substitute`{.interpreted-text role="meth"}.

::: versionchanged
3.2 Added the `style` parameter.
:::

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:

    '%(asctime)s - %(levelname)s - %(message)s'

Formatters use a user-configurable function to convert the creation time of a record to a tuple. By default, `time.localtime`{.interpreted-text role="func"} is used; to change this for a particular formatter instance, set the `converter` attribute of the instance to a function with the same signature as `time.localtime`{.interpreted-text role="func"} or `time.gmtime`{.interpreted-text role="func"}. To change it for all formatters, for example if you want all logging times to be shown in GMT, set the `converter` attribute in the Formatter class (to `time.gmtime` for GMT display).

### Configuring Logging

::: currentmodule
logging.config
:::

Programmers can configure logging in three ways:

1.  Creating loggers, handlers, and formatters explicitly using Python code that calls the configuration methods listed above.
2.  Creating a logging config file and reading it using the `fileConfig`{.interpreted-text role="func"} function.
3.  Creating a dictionary of configuration information and passing it to the `dictConfig`{.interpreted-text role="func"} function.

For the reference documentation on the last two options, see `logging-config-api`{.interpreted-text role="ref"}. The following example configures a very simple logger, a console handler, and a simple formatter using Python code:

    import logging

    # create logger
    logger = logging.getLogger('simple_example')
    logger.setLevel(logging.DEBUG)

    # create console handler and set level to debug
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)

    # create formatter
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    # add formatter to ch
    ch.setFormatter(formatter)

    # add ch to logger
    logger.addHandler(ch)

    # 'application' code
    logger.debug('debug message')
    logger.info('info message')
    logger.warning('warn message')
    logger.error('error message')
    logger.critical('critical message')

Running this module from the command line produces the following output:

``` shell-session
$ python simple_logging_module.py
2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
2005-03-19 15:10:26,620 - simple_example - INFO - info message
2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
2005-03-19 15:10:26,697 - simple_example - ERROR - error message
2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
```

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:

    import logging
    import logging.config

    logging.config.fileConfig('logging.conf')

    # create logger
    logger = logging.getLogger('simpleExample')

    # 'application' code
    logger.debug('debug message')
    logger.info('info message')
    logger.warning('warn message')
    logger.error('error message')
    logger.critical('critical message')

Here is the logging.conf file:

``` ini
[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
```

The output is nearly identical to that of the non-config-file-based example:

``` shell-session
$ python simple_logging_config.py
2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
2005-03-19 15:38:55,979 - simpleExample - INFO - info message
2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
```

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.

:::: warning
::: title
Warning
:::

The `fileConfig`{.interpreted-text role="func"} function takes a default parameter, `disable_existing_loggers`, which defaults to `True` for reasons of backward compatibility. This may or may not be what you want, since it will cause any non-root loggers existing before the `fileConfig`{.interpreted-text role="func"} 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 `False` for this parameter if you wish.

The dictionary passed to `dictConfig`{.interpreted-text role="func"} can also specify a Boolean value with key `disable_existing_loggers`, which if not specified explicitly in the dictionary also defaults to being interpreted as `True`. 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 `False`.
::::

::: currentmodule
logging
:::

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 `~logging.handlers.WatchedFileHandler`{.interpreted-text role="class"} (relative to the logging module) or `mypackage.mymodule.MyHandler` (for a class defined in package `mypackage` and module `mymodule`, where `mypackage` is available on the Python import path).

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.

Here\'s an example of the same configuration as above, in YAML format for the new dictionary-based approach:

``` yaml
version: 1
formatters:
  simple:
    format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
  console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: simple
    stream: ext://sys.stdout
loggers:
  simpleExample:
    level: DEBUG
    handlers: [console]
    propagate: no
root:
  level: DEBUG
  handlers: [console]
```

For more information about logging using a dictionary, see `logging-config-api`{.interpreted-text role="ref"}.

### What happens if no configuration is provided

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 event is output using a \'handler of last resort\', stored in `lastResort`{.interpreted-text role="data"}. This internal handler is not associated with any logger, and acts like a `~logging.StreamHandler`{.interpreted-text role="class"} which writes the event description message to the current value of `sys.stderr` (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 `WARNING`, so all events at this and greater severities will be output.

::: versionchanged
3.2

For versions of Python prior to 3.2, the behaviour is as follows:

- If `raiseExceptions`{.interpreted-text role="data"} is `False` (production mode), the event is silently dropped.
- If `raiseExceptions`{.interpreted-text role="data"} is `True` (development mode), a message \'No handlers could be found for logger X.Y.Z\' is printed once.

To obtain the pre-3.2 behaviour, `lastResort`{.interpreted-text role="data"} can be set to `None`.
:::

### Configuring Logging for a Library {#library-config}

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 `WARNING` and greater will be printed to `sys.stderr`. This is regarded as the best default behaviour.

If for some reason you *don\'t* 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 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.

A do-nothing handler is included in the logging package: `~logging.NullHandler`{.interpreted-text role="class"} (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 (*if* you want to prevent your library\'s logged events being output to `sys.stderr` in the absence of logging configuration). If all logging by a library *foo* is done using loggers with names matching \'foo.x\', \'foo.x.y\', etc. then the code:

    import logging
    logging.getLogger('foo').addHandler(logging.NullHandler())

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\'.

:::: note
::: title
Note
:::

It is strongly advised that you *do not log to the root logger* in your library. Instead, use a logger with a unique and easily identifiable name, such as the `__name__` for your library\'s top-level package or module. Logging to the root logger will make it difficult or impossible for the application developer to configure the logging verbosity or handlers of your library as they wish.
::::

:::: note
::: title
Note
:::

It is strongly advised that you *do not add any handlers other than* `~logging.NullHandler`{.interpreted-text role="class"} *to your library\'s loggers*. 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.
::::

## Logging Levels

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.

  ------------------------------
  Level          Numeric value
  -------------- ---------------
  `CRITICAL`     50

  `ERROR`        40

  `WARNING`      30

  `INFO`         20

  `DEBUG`        10

  `NOTSET`       0
  ------------------------------

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.

Logging messages are encoded as instances of the `~logging.LogRecord`{.interpreted-text role="class"} class. When a logger decides to actually log an event, a `~logging.LogRecord`{.interpreted-text role="class"} instance is created from the logging message.

Logging messages are subjected to a dispatch mechanism through the use of `handlers`{.interpreted-text role="dfn"}, which are instances of subclasses of the `Handler`{.interpreted-text role="class"} class. Handlers are responsible for ensuring that a logged message (in the form of a `LogRecord`{.interpreted-text role="class"}) 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 `LogRecord`{.interpreted-text role="class"} instances intended for particular destinations. Each logger can have zero, one or more handlers associated with it (via the `~Logger.addHandler`{.interpreted-text role="meth"} method of `Logger`{.interpreted-text role="class"}). In addition to any handlers directly associated with a logger, *all handlers associated with all ancestors of the logger* are called to dispatch the message (unless the *propagate* flag for a logger is set to a false value, at which point the passing to ancestor handlers stops).

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 `~Handler.emit`{.interpreted-text role="meth"} method is used to send the message to its destination. Most user-defined subclasses of `Handler`{.interpreted-text role="class"} will need to override this `~Handler.emit`{.interpreted-text role="meth"}.

### Custom Levels

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 *a very bad idea to define custom levels if you are developing a library*. 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.

## Useful Handlers

In addition to the base `Handler`{.interpreted-text role="class"} class, many useful subclasses are provided:

1.  `StreamHandler`{.interpreted-text role="class"} instances send messages to streams (file-like objects).
2.  `FileHandler`{.interpreted-text role="class"} instances send messages to disk files.
3.  `~handlers.BaseRotatingHandler`{.interpreted-text role="class"} is the base class for handlers that rotate log files at a certain point. It is not meant to be instantiated directly. Instead, use `~handlers.RotatingFileHandler`{.interpreted-text role="class"} or `~handlers.TimedRotatingFileHandler`{.interpreted-text role="class"}.
4.  `~handlers.RotatingFileHandler`{.interpreted-text role="class"} instances send messages to disk files, with support for maximum log file sizes and log file rotation.
5.  `~handlers.TimedRotatingFileHandler`{.interpreted-text role="class"} instances send messages to disk files, rotating the log file at certain timed intervals.
6.  `~handlers.SocketHandler`{.interpreted-text role="class"} instances send messages to TCP/IP sockets. Since 3.4, Unix domain sockets are also supported.
7.  `~handlers.DatagramHandler`{.interpreted-text role="class"} instances send messages to UDP sockets. Since 3.4, Unix domain sockets are also supported.
8.  `~handlers.SMTPHandler`{.interpreted-text role="class"} instances send messages to a designated email address.
9.  `~handlers.SysLogHandler`{.interpreted-text role="class"} instances send messages to a Unix syslog daemon, possibly on a remote machine.
10. `~handlers.NTEventLogHandler`{.interpreted-text role="class"} instances send messages to a Windows NT/2000/XP event log.
11. `~handlers.MemoryHandler`{.interpreted-text role="class"} instances send messages to a buffer in memory, which is flushed whenever specific criteria are met.
12. `~handlers.HTTPHandler`{.interpreted-text role="class"} instances send messages to an HTTP server using either `GET` or `POST` semantics.
13. `~handlers.WatchedFileHandler`{.interpreted-text role="class"} 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.
14. `~handlers.QueueHandler`{.interpreted-text role="class"} instances send messages to a queue, such as those implemented in the `queue`{.interpreted-text role="mod"} or `multiprocessing`{.interpreted-text role="mod"} modules.
15. `NullHandler`{.interpreted-text role="class"} 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 `library-config`{.interpreted-text role="ref"} for more information.

::: versionadded
3.1 The `NullHandler`{.interpreted-text role="class"} class.
:::

::: versionadded
3.2 The `~handlers.QueueHandler`{.interpreted-text role="class"} class.
:::

The `NullHandler`{.interpreted-text role="class"}, `StreamHandler`{.interpreted-text role="class"} and `FileHandler`{.interpreted-text role="class"} classes are defined in the core logging package. The other handlers are defined in a sub-module, `logging.handlers`{.interpreted-text role="mod"}. (There is also another sub-module, `logging.config`{.interpreted-text role="mod"}, for configuration functionality.)

Logged messages are formatted for presentation through instances of the `Formatter`{.interpreted-text role="class"} class. They are initialized with a format string suitable for use with the % operator and a dictionary.

For formatting multiple messages in a batch, instances of `BufferingFormatter`{.interpreted-text role="class"} 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.

When filtering based on logger level and/or handler level is not enough, instances of `Filter`{.interpreted-text role="class"} can be added to both `Logger`{.interpreted-text role="class"} and `Handler`{.interpreted-text role="class"} instances (through their `~Handler.addFilter`{.interpreted-text role="meth"} 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.

The basic `Filter`{.interpreted-text role="class"} 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.

## Exceptions raised during logging {#logging-exceptions}

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.

`SystemExit`{.interpreted-text role="class"} and `KeyboardInterrupt`{.interpreted-text role="class"} exceptions are never swallowed. Other exceptions which occur during the `~Handler.emit`{.interpreted-text role="meth"} method of a `Handler`{.interpreted-text role="class"} subclass are passed to its `~Handler.handleError`{.interpreted-text role="meth"} method.

The default implementation of `~Handler.handleError`{.interpreted-text role="meth"} in `Handler`{.interpreted-text role="class"} checks to see if a module-level variable, `raiseExceptions`{.interpreted-text role="data"}, is set. If set, a traceback is printed to `sys.stderr`{.interpreted-text role="data"}. If not set, the exception is swallowed.

:::: note
::: title
Note
:::

The default value of `raiseExceptions`{.interpreted-text role="data"} is `True`. This is because during development, you typically want to be notified of any exceptions that occur. It\'s advised that you set `raiseExceptions`{.interpreted-text role="data"} to `False` for production usage.
::::

::: currentmodule
logging
:::

## Using arbitrary objects as messages {#arbitrary-object-messages}

In the preceding sections and examples, it has been assumed that the message passed when logging the event is a string. However, this is not the only possibility. You can pass an arbitrary object as a message, and its `~object.__str__`{.interpreted-text role="meth"} method will be called when the logging system needs to convert it to a string representation. In fact, if you want to, you can avoid computing a string representation altogether - for example, the `~handlers.SocketHandler`{.interpreted-text role="class"} emits an event by pickling it and sending it over the wire.

## Optimization

Formatting of message arguments is deferred until it cannot be avoided. However, computing the arguments passed to the logging method can also be expensive, and you may want to avoid doing it if the logger will just throw away your event. To decide what to do, you can call the `~Logger.isEnabledFor`{.interpreted-text role="meth"} method which takes a level argument and returns true if the event would be created by the Logger for that level of call. You can write code like this:

    if logger.isEnabledFor(logging.DEBUG):
        logger.debug('Message with %s, %s', expensive_func1(),
                                            expensive_func2())

so that if the logger\'s threshold is set above `DEBUG`, the calls to `expensive_func1` and `expensive_func2` are never made.

:::: note
::: title
Note
:::

In some cases, `~Logger.isEnabledFor`{.interpreted-text role="meth"} can itself be more expensive than you\'d like (e.g. for deeply nested loggers where an explicit level is only set high up in the logger hierarchy). In such cases (or if you want to avoid calling a method in tight loops), you can cache the result of a call to `~Logger.isEnabledFor`{.interpreted-text role="meth"} in a local or instance variable, and use that instead of calling the method each time. Such a cached value would only need to be recomputed when the logging configuration changes dynamically while the application is running (which is not all that common).
::::

There are other optimizations which can be made for specific applications which need more precise control over what logging information is collected. Here\'s a list of things you can do to avoid processing during logging which you don\'t need:

  -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  What you don\'t want to collect                                                     How to avoid collecting it
  ----------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  Information about where calls were made from.                                       Set `logging._srcfile` to `None`. This avoids calling `sys._getframe`{.interpreted-text role="func"}, which may help to speed up your code in environments like PyPy (which can\'t speed up code that uses `sys._getframe`{.interpreted-text role="func"}).

  Threading information.                                                              Set `logging.logThreads` to `False`.

  Current process ID (`os.getpid`{.interpreted-text role="func"})                     Set `logging.logProcesses` to `False`.

  Current process name when using `multiprocessing` to manage multiple processes.     Set `logging.logMultiprocessing` to `False`.

  Current `asyncio.Task`{.interpreted-text role="class"} name when using `asyncio`.   Set `logging.logAsyncioTasks` to `False`.
  -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Also note that the core logging module only includes the basic handlers. If you don\'t import `logging.handlers`{.interpreted-text role="mod"} and `logging.config`{.interpreted-text role="mod"}, they won\'t take up any memory.

## Other resources {#tutorial-ref-links}

::: seealso

Module `logging`{.interpreted-text role="mod"}

:   API reference for the logging module.

Module `logging.config`{.interpreted-text role="mod"}

:   Configuration API for the logging module.

Module `logging.handlers`{.interpreted-text role="mod"}

:   Useful handlers included with the logging module.

`A logging cookbook <logging-cookbook>`{.interpreted-text role="ref"}
:::