summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/howto%2Flogging-cookbook.html
blob: 2b5b0130875eba7dd6ffe1030b6f2ef3730d0c46 (plain)
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
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
 <span id="id1"></span><h1>Logging Cookbook</h1> <dl class="field-list simple"> <dt class="field-odd">Author</dt> <dd class="field-odd">
<p>Vinay Sajip &lt;vinay_sajip at red-dove dot com&gt;</p> </dd> </dl> <p>This page contains a number of recipes related to logging, which have been found useful in the past. For links to tutorial and reference information, please see <a class="reference internal" href="#cookbook-ref-links"><span class="std std-ref">Other resources</span></a>.</p> <section id="using-logging-in-multiple-modules"> <h2>Using logging in multiple modules</h2> <p>Multiple calls to <code>logging.getLogger('someLogger')</code> return a reference to the same logger object. This is true not only within the same module, but also across modules as long as it is in the same Python interpreter process. It is true for references to the same object; additionally, application code can define and configure a parent logger in one module and create (but not configure) a child logger in a separate module, and all logger calls to the child will pass up to the parent. Here is a main module:</p> <pre data-language="python">import logging
import auxiliary_module

# create logger with 'spam_application'
logger = logging.getLogger('spam_application')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)

logger.info('creating an instance of auxiliary_module.Auxiliary')
a = auxiliary_module.Auxiliary()
logger.info('created an instance of auxiliary_module.Auxiliary')
logger.info('calling auxiliary_module.Auxiliary.do_something')
a.do_something()
logger.info('finished auxiliary_module.Auxiliary.do_something')
logger.info('calling auxiliary_module.some_function()')
auxiliary_module.some_function()
logger.info('done with auxiliary_module.some_function()')
</pre> <p>Here is the auxiliary module:</p> <pre data-language="python">import logging

# create logger
module_logger = logging.getLogger('spam_application.auxiliary')

class Auxiliary:
    def __init__(self):
        self.logger = logging.getLogger('spam_application.auxiliary.Auxiliary')
        self.logger.info('creating an instance of Auxiliary')

    def do_something(self):
        self.logger.info('doing something')
        a = 1 + 1
        self.logger.info('done doing something')

def some_function():
    module_logger.info('received a call to "some_function"')
</pre> <p>The output looks like this:</p> <pre data-language="none">2005-03-23 23:47:11,663 - spam_application - INFO -
   creating an instance of auxiliary_module.Auxiliary
2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
   creating an instance of Auxiliary
2005-03-23 23:47:11,665 - spam_application - INFO -
   created an instance of auxiliary_module.Auxiliary
2005-03-23 23:47:11,668 - spam_application - INFO -
   calling auxiliary_module.Auxiliary.do_something
2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
   doing something
2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
   done doing something
2005-03-23 23:47:11,670 - spam_application - INFO -
   finished auxiliary_module.Auxiliary.do_something
2005-03-23 23:47:11,671 - spam_application - INFO -
   calling auxiliary_module.some_function()
2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
   received a call to 'some_function'
2005-03-23 23:47:11,673 - spam_application - INFO -
   done with auxiliary_module.some_function()
</pre> </section> <section id="logging-from-multiple-threads"> <h2>Logging from multiple threads</h2> <p>Logging from multiple threads requires no special effort. The following example shows logging from the main (initial) thread and another thread:</p> <pre data-language="python">import logging
import threading
import time

def worker(arg):
    while not arg['stop']:
        logging.debug('Hi from myfunc')
        time.sleep(0.5)

def main():
    logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s')
    info = {'stop': False}
    thread = threading.Thread(target=worker, args=(info,))
    thread.start()
    while True:
        try:
            logging.debug('Hello from main')
            time.sleep(0.75)
        except KeyboardInterrupt:
            info['stop'] = True
            break
    thread.join()

if __name__ == '__main__':
    main()
</pre> <p>When run, the script should print something like the following:</p> <pre data-language="none">   0 Thread-1 Hi from myfunc
   3 MainThread Hello from main
 505 Thread-1 Hi from myfunc
 755 MainThread Hello from main
1007 Thread-1 Hi from myfunc
1507 MainThread Hello from main
1508 Thread-1 Hi from myfunc
2010 Thread-1 Hi from myfunc
2258 MainThread Hello from main
2512 Thread-1 Hi from myfunc
3009 MainThread Hello from main
3013 Thread-1 Hi from myfunc
3515 Thread-1 Hi from myfunc
3761 MainThread Hello from main
4017 Thread-1 Hi from myfunc
4513 MainThread Hello from main
4518 Thread-1 Hi from myfunc
</pre> <p>This shows the logging output interspersed as one might expect. This approach works for more threads than shown here, of course.</p> </section> <section id="multiple-handlers-and-formatters"> <h2>Multiple handlers and formatters</h2> <p>Loggers are plain Python objects. The <a class="reference internal" href="../library/logging#logging.Logger.addHandler" title="logging.Logger.addHandler"><code>addHandler()</code></a> method has no minimum or maximum quota for the number of handlers you may add. Sometimes it will be beneficial for an application to log all messages of all severities to a text file while simultaneously logging errors or above to the console. To set this up, simply configure the appropriate handlers. The logging calls in the application code will remain unchanged. Here is a slight modification to the previous simple module-based configuration example:</p> <pre data-language="python">import logging

logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')
</pre> <p>Notice that the ‘application’ code does not care about multiple handlers. All that changed was the addition and configuration of a new handler named <em>fh</em>.</p> <p>The ability to create new handlers with higher- or lower-severity filters can be very helpful when writing and testing an application. Instead of using many <code>print</code> statements for debugging, use <code>logger.debug</code>: Unlike the print statements, which you will have to delete or comment out later, the logger.debug statements can remain intact in the source code and remain dormant until you need them again. At that time, the only change that needs to happen is to modify the severity level of the logger and/or handler to debug.</p> </section> <section id="logging-to-multiple-destinations"> <span id="multiple-destinations"></span><h2>Logging to multiple destinations</h2> <p>Let’s say you want to log to console and file with different message formats and in differing circumstances. Say you want to log messages with levels of DEBUG and higher to file, and those messages at level INFO and higher to the console. Let’s also assume that the file should contain timestamps, but the console messages should not. Here’s how you can achieve this:</p> <pre data-language="python">import logging

# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    filename='/tmp/myapp.log',
                    filemode='w')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)

# Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.')

# Now, define a couple of other loggers which might represent areas in your
# application:

logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')

logger1.debug('Quick zephyrs blow, vexing daft Jim.')
logger1.info('How quickly daft jumping zebras vex.')
logger2.warning('Jail zesty vixen who grabbed pay from quack.')
logger2.error('The five boxing wizards jump quickly.')
</pre> <p>When you run this, on the console you will see</p> <pre data-language="none">root        : INFO     Jackdaws love my big sphinx of quartz.
myapp.area1 : INFO     How quickly daft jumping zebras vex.
myapp.area2 : WARNING  Jail zesty vixen who grabbed pay from quack.
myapp.area2 : ERROR    The five boxing wizards jump quickly.
</pre> <p>and in the file you will see something like</p> <pre data-language="none">10-22 22:19 root         INFO     Jackdaws love my big sphinx of quartz.
10-22 22:19 myapp.area1  DEBUG    Quick zephyrs blow, vexing daft Jim.
10-22 22:19 myapp.area1  INFO     How quickly daft jumping zebras vex.
10-22 22:19 myapp.area2  WARNING  Jail zesty vixen who grabbed pay from quack.
10-22 22:19 myapp.area2  ERROR    The five boxing wizards jump quickly.
</pre> <p>As you can see, the DEBUG message only shows up in the file. The other messages are sent to both destinations.</p> <p>This example uses console and file handlers, but you can use any number and combination of handlers you choose.</p> <p>Note that the above choice of log filename <code>/tmp/myapp.log</code> implies use of a standard location for temporary files on POSIX systems. On Windows, you may need to choose a different directory name for the log - just ensure that the directory exists and that you have the permissions to create and update files in it.</p> </section> <section id="custom-handling-of-levels"> <span id="custom-level-handling"></span><h2>Custom handling of levels</h2> <p>Sometimes, you might want to do something slightly different from the standard handling of levels in handlers, where all levels above a threshold get processed by a handler. To do this, you need to use filters. Let’s look at a scenario where you want to arrange things as follows:</p> <ul class="simple"> <li>Send messages of severity <code>INFO</code> and <code>WARNING</code> to <code>sys.stdout</code>
</li> <li>Send messages of severity <code>ERROR</code> and above to <code>sys.stderr</code>
</li> <li>Send messages of severity <code>DEBUG</code> and above to file <code>app.log</code>
</li> </ul> <p>Suppose you configure logging with the following JSON:</p> <pre data-language="json">{
    "version": 1,
    "disable_existing_loggers": false,
    "formatters": {
        "simple": {
            "format": "%(levelname)-8s - %(message)s"
        }
    },
    "handlers": {
        "stdout": {
            "class": "logging.StreamHandler",
            "level": "INFO",
            "formatter": "simple",
            "stream": "ext://sys.stdout"
        },
        "stderr": {
            "class": "logging.StreamHandler",
            "level": "ERROR",
            "formatter": "simple",
            "stream": "ext://sys.stderr"
        },
        "file": {
            "class": "logging.FileHandler",
            "formatter": "simple",
            "filename": "app.log",
            "mode": "w"
        }
    },
    "root": {
        "level": "DEBUG",
        "handlers": [
            "stderr",
            "stdout",
            "file"
        ]
    }
}
</pre> <p>This configuration does <em>almost</em> what we want, except that <code>sys.stdout</code> would show messages of severity <code>ERROR</code> and above as well as <code>INFO</code> and <code>WARNING</code> messages. To prevent this, we can set up a filter which excludes those messages and add it to the relevant handler. This can be configured by adding a <code>filters</code> section parallel to <code>formatters</code> and <code>handlers</code>:</p> <pre data-language="json">{
    "filters": {
        "warnings_and_below": {
            "()" : "__main__.filter_maker",
            "level": "WARNING"
        }
    }
}
</pre> <p>and changing the section on the <code>stdout</code> handler to add it:</p> <pre data-language="json">{
    "stdout": {
        "class": "logging.StreamHandler",
        "level": "INFO",
        "formatter": "simple",
        "stream": "ext://sys.stdout",
        "filters": ["warnings_and_below"]
    }
}
</pre> <p>A filter is just a function, so we can define the <code>filter_maker</code> (a factory function) as follows:</p> <pre data-language="python">def filter_maker(level):
    level = getattr(logging, level)

    def filter(record):
        return record.levelno &lt;= level

    return filter
</pre> <p>This converts the string argument passed in to a numeric level, and returns a function which only returns <code>True</code> if the level of the passed in record is at or below the specified level. Note that in this example I have defined the <code>filter_maker</code> in a test script <code>main.py</code> that I run from the command line, so its module will be <code>__main__</code> - hence the <code>__main__.filter_maker</code> in the filter configuration. You will need to change that if you define it in a different module.</p> <p>With the filter added, we can run <code>main.py</code>, which in full is:</p> <pre data-language="python">import json
import logging
import logging.config

CONFIG = '''
{
    "version": 1,
    "disable_existing_loggers": false,
    "formatters": {
        "simple": {
            "format": "%(levelname)-8s - %(message)s"
        }
    },
    "filters": {
        "warnings_and_below": {
            "()" : "__main__.filter_maker",
            "level": "WARNING"
        }
    },
    "handlers": {
        "stdout": {
            "class": "logging.StreamHandler",
            "level": "INFO",
            "formatter": "simple",
            "stream": "ext://sys.stdout",
            "filters": ["warnings_and_below"]
        },
        "stderr": {
            "class": "logging.StreamHandler",
            "level": "ERROR",
            "formatter": "simple",
            "stream": "ext://sys.stderr"
        },
        "file": {
            "class": "logging.FileHandler",
            "formatter": "simple",
            "filename": "app.log",
            "mode": "w"
        }
    },
    "root": {
        "level": "DEBUG",
        "handlers": [
            "stderr",
            "stdout",
            "file"
        ]
    }
}
'''

def filter_maker(level):
    level = getattr(logging, level)

    def filter(record):
        return record.levelno &lt;= level

    return filter

logging.config.dictConfig(json.loads(CONFIG))
logging.debug('A DEBUG message')
logging.info('An INFO message')
logging.warning('A WARNING message')
logging.error('An ERROR message')
logging.critical('A CRITICAL message')
</pre> <p>And after running it like this:</p> <pre data-language="shell">python main.py 2&gt;stderr.log &gt;stdout.log
</pre> <p>We can see the results are as expected:</p> <pre data-language="shell">$ more *.log
::::::::::::::
app.log
::::::::::::::
DEBUG    - A DEBUG message
INFO     - An INFO message
WARNING  - A WARNING message
ERROR    - An ERROR message
CRITICAL - A CRITICAL message
::::::::::::::
stderr.log
::::::::::::::
ERROR    - An ERROR message
CRITICAL - A CRITICAL message
::::::::::::::
stdout.log
::::::::::::::
INFO     - An INFO message
WARNING  - A WARNING message
</pre> </section> <section id="configuration-server-example"> <h2>Configuration server example</h2> <p>Here is an example of a module using the logging configuration server:</p> <pre data-language="python">import logging
import logging.config
import time
import os

# read initial config file
logging.config.fileConfig('logging.conf')

# create and start listener on port 9999
t = logging.config.listen(9999)
t.start()

logger = logging.getLogger('simpleExample')

try:
    # loop through logging calls to see the difference
    # new configurations make, until Ctrl+C is pressed
    while True:
        logger.debug('debug message')
        logger.info('info message')
        logger.warning('warn message')
        logger.error('error message')
        logger.critical('critical message')
        time.sleep(5)
except KeyboardInterrupt:
    # cleanup
    logging.config.stopListening()
    t.join()
</pre> <p>And here is a script that takes a filename and sends that file to the server, properly preceded with the binary-encoded length, as the new logging configuration:</p> <pre data-language="python">#!/usr/bin/env python
import socket, sys, struct

with open(sys.argv[1], 'rb') as f:
    data_to_send = f.read()

HOST = 'localhost'
PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('connecting...')
s.connect((HOST, PORT))
print('sending config...')
s.send(struct.pack('&gt;L', len(data_to_send)))
s.send(data_to_send)
s.close()
print('complete')
</pre> </section> <section id="dealing-with-handlers-that-block"> <span id="blocking-handlers"></span><h2>Dealing with handlers that block</h2> <p>Sometimes you have to get your logging handlers to do their work without blocking the thread you’re logging from. This is common in web applications, though of course it also occurs in other scenarios.</p> <p>A common culprit which demonstrates sluggish behaviour is the <a class="reference internal" href="../library/logging.handlers#logging.handlers.SMTPHandler" title="logging.handlers.SMTPHandler"><code>SMTPHandler</code></a>: sending emails can take a long time, for a number of reasons outside the developer’s control (for example, a poorly performing mail or network infrastructure). But almost any network-based handler can block: Even a <a class="reference internal" href="../library/logging.handlers#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><code>SocketHandler</code></a> operation may do a DNS query under the hood which is too slow (and this query can be deep in the socket library code, below the Python layer, and outside your control).</p> <p>One solution is to use a two-part approach. For the first part, attach only a <a class="reference internal" href="../library/logging.handlers#logging.handlers.QueueHandler" title="logging.handlers.QueueHandler"><code>QueueHandler</code></a> to those loggers which are accessed from performance-critical threads. They simply write to their queue, which can be sized to a large enough capacity or initialized with no upper bound to their size. The write to the queue will typically be accepted quickly, though you will probably need to catch the <a class="reference internal" href="../library/queue#queue.Full" title="queue.Full"><code>queue.Full</code></a> exception as a precaution in your code. If you are a library developer who has performance-critical threads in their code, be sure to document this (together with a suggestion to attach only <code>QueueHandlers</code> to your loggers) for the benefit of other developers who will use your code.</p> <p>The second part of the solution is <a class="reference internal" href="../library/logging.handlers#logging.handlers.QueueListener" title="logging.handlers.QueueListener"><code>QueueListener</code></a>, which has been designed as the counterpart to <a class="reference internal" href="../library/logging.handlers#logging.handlers.QueueHandler" title="logging.handlers.QueueHandler"><code>QueueHandler</code></a>. A <a class="reference internal" href="../library/logging.handlers#logging.handlers.QueueListener" title="logging.handlers.QueueListener"><code>QueueListener</code></a> is very simple: it’s passed a queue and some handlers, and it fires up an internal thread which listens to its queue for LogRecords sent from <code>QueueHandlers</code> (or any other source of <code>LogRecords</code>, for that matter). The <code>LogRecords</code> are removed from the queue and passed to the handlers for processing.</p> <p>The advantage of having a separate <a class="reference internal" href="../library/logging.handlers#logging.handlers.QueueListener" title="logging.handlers.QueueListener"><code>QueueListener</code></a> class is that you can use the same instance to service multiple <code>QueueHandlers</code>. This is more resource-friendly than, say, having threaded versions of the existing handler classes, which would eat up one thread per handler for no particular benefit.</p> <p>An example of using these two classes follows (imports omitted):</p> <pre data-language="python">que = queue.Queue(-1)  # no limit on size
queue_handler = QueueHandler(que)
handler = logging.StreamHandler()
listener = QueueListener(que, handler)
root = logging.getLogger()
root.addHandler(queue_handler)
formatter = logging.Formatter('%(threadName)s: %(message)s')
handler.setFormatter(formatter)
listener.start()
# The log output will display the thread which generated
# the event (the main thread) rather than the internal
# thread which monitors the internal queue. This is what
# you want to happen.
root.warning('Look out!')
listener.stop()
</pre> <p>which, when run, will produce:</p> <pre data-language="none">MainThread: Look out!
</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Although the earlier discussion wasn’t specifically talking about async code, but rather about slow logging handlers, it should be noted that when logging from async code, network and even file handlers could lead to problems (blocking the event loop) because some logging is done from <a class="reference internal" href="../library/asyncio#module-asyncio" title="asyncio: Asynchronous I/O."><code>asyncio</code></a> internals. It might be best, if any async code is used in an application, to use the above approach for logging, so that any blocking code runs only in the <code>QueueListener</code> thread.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Prior to Python 3.5, the <a class="reference internal" href="../library/logging.handlers#logging.handlers.QueueListener" title="logging.handlers.QueueListener"><code>QueueListener</code></a> always passed every message received from the queue to every handler it was initialized with. (This was because it was assumed that level filtering was all done on the other side, where the queue is filled.) From 3.5 onwards, this behaviour can be changed by passing a keyword argument <code>respect_handler_level=True</code> to the listener’s constructor. When this is done, the listener compares the level of each message with the handler’s level, and only passes a message to a handler if it’s appropriate to do so.</p> </div> </section> <section id="sending-and-receiving-logging-events-across-a-network"> <span id="network-logging"></span><h2>Sending and receiving logging events across a network</h2> <p>Let’s say you want to send logging events across a network, and handle them at the receiving end. A simple way of doing this is attaching a <a class="reference internal" href="../library/logging.handlers#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><code>SocketHandler</code></a> instance to the root logger at the sending end:</p> <pre data-language="python">import logging, logging.handlers

rootLogger = logging.getLogger('')
rootLogger.setLevel(logging.DEBUG)
socketHandler = logging.handlers.SocketHandler('localhost',
                    logging.handlers.DEFAULT_TCP_LOGGING_PORT)
# don't bother with a formatter, since a socket handler sends the event as
# an unformatted pickle
rootLogger.addHandler(socketHandler)

# Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.')

# Now, define a couple of other loggers which might represent areas in your
# application:

logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')

logger1.debug('Quick zephyrs blow, vexing daft Jim.')
logger1.info('How quickly daft jumping zebras vex.')
logger2.warning('Jail zesty vixen who grabbed pay from quack.')
logger2.error('The five boxing wizards jump quickly.')
</pre> <p>At the receiving end, you can set up a receiver using the <a class="reference internal" href="../library/socketserver#module-socketserver" title="socketserver: A framework for network servers."><code>socketserver</code></a> module. Here is a basic working example:</p> <pre data-language="python">import pickle
import logging
import logging.handlers
import socketserver
import struct


class LogRecordStreamHandler(socketserver.StreamRequestHandler):
    """Handler for a streaming logging request.

    This basically logs the record using whatever logging policy is
    configured locally.
    """

    def handle(self):
        """
        Handle multiple requests - each expected to be a 4-byte length,
        followed by the LogRecord in pickle format. Logs the record
        according to whatever policy is configured locally.
        """
        while True:
            chunk = self.connection.recv(4)
            if len(chunk) &lt; 4:
                break
            slen = struct.unpack('&gt;L', chunk)[0]
            chunk = self.connection.recv(slen)
            while len(chunk) &lt; slen:
                chunk = chunk + self.connection.recv(slen - len(chunk))
            obj = self.unPickle(chunk)
            record = logging.makeLogRecord(obj)
            self.handleLogRecord(record)

    def unPickle(self, data):
        return pickle.loads(data)

    def handleLogRecord(self, record):
        # if a name is specified, we use the named logger rather than the one
        # implied by the record.
        if self.server.logname is not None:
            name = self.server.logname
        else:
            name = record.name
        logger = logging.getLogger(name)
        # N.B. EVERY record gets logged. This is because Logger.handle
        # is normally called AFTER logger-level filtering. If you want
        # to do filtering, do it at the client end to save wasting
        # cycles and network bandwidth!
        logger.handle(record)

class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
    """
    Simple TCP socket-based logging receiver suitable for testing.
    """

    allow_reuse_address = True

    def __init__(self, host='localhost',
                 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
                 handler=LogRecordStreamHandler):
        socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
        self.abort = 0
        self.timeout = 1
        self.logname = None

    def serve_until_stopped(self):
        import select
        abort = 0
        while not abort:
            rd, wr, ex = select.select([self.socket.fileno()],
                                       [], [],
                                       self.timeout)
            if rd:
                self.handle_request()
            abort = self.abort

def main():
    logging.basicConfig(
        format='%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s')
    tcpserver = LogRecordSocketReceiver()
    print('About to start TCP server...')
    tcpserver.serve_until_stopped()

if __name__ == '__main__':
    main()
</pre> <p>First run the server, and then the client. On the client side, nothing is printed on the console; on the server side, you should see something like:</p> <pre data-language="none">About to start TCP server...
   59 root            INFO     Jackdaws love my big sphinx of quartz.
   59 myapp.area1     DEBUG    Quick zephyrs blow, vexing daft Jim.
   69 myapp.area1     INFO     How quickly daft jumping zebras vex.
   69 myapp.area2     WARNING  Jail zesty vixen who grabbed pay from quack.
   69 myapp.area2     ERROR    The five boxing wizards jump quickly.
</pre> <p>Note that there are some security issues with pickle in some scenarios. If these affect you, you can use an alternative serialization scheme by overriding the <a class="reference internal" href="../library/logging.handlers#logging.handlers.SocketHandler.makePickle" title="logging.handlers.SocketHandler.makePickle"><code>makePickle()</code></a> method and implementing your alternative there, as well as adapting the above script to use your alternative serialization.</p> <section id="running-a-logging-socket-listener-in-production"> <h3>Running a logging socket listener in production</h3> <p>To run a logging listener in production, you may need to use a process-management tool such as <a class="reference external" href="http://supervisord.org/">Supervisor</a>. <a class="reference external" href="https://gist.github.com/vsajip/4b227eeec43817465ca835ca66f75e2b">Here is a Gist</a> which provides the bare-bones files to run the above functionality using Supervisor. It consists of the following files:</p> <table class="docutils align-default">  <thead> <tr>
<th class="head"><p>File</p></th> <th class="head"><p>Purpose</p></th> </tr> </thead>  <tr>
<td><p><code>prepare.sh</code></p></td> <td><p>A Bash script to prepare the environment for testing</p></td> </tr> <tr>
<td><p><code>supervisor.conf</code></p></td> <td><p>The Supervisor configuration file, which has entries for the listener and a multi-process web application</p></td> </tr> <tr>
<td><p><code>ensure_app.sh</code></p></td> <td><p>A Bash script to ensure that Supervisor is running with the above configuration</p></td> </tr> <tr>
<td><p><code>log_listener.py</code></p></td> <td><p>The socket listener program which receives log events and records them to a file</p></td> </tr> <tr>
<td><p><code>main.py</code></p></td> <td><p>A simple web application which performs logging via a socket connected to the listener</p></td> </tr> <tr>
<td><p><code>webapp.json</code></p></td> <td><p>A JSON configuration file for the web application</p></td> </tr> <tr>
<td><p><code>client.py</code></p></td> <td><p>A Python script to exercise the web application</p></td> </tr>  </table> <p>The web application uses <a class="reference external" href="https://gunicorn.org/">Gunicorn</a>, which is a popular web application server that starts multiple worker processes to handle requests. This example setup shows how the workers can write to the same log file without conflicting with one another — they all go through the socket listener.</p> <p>To test these files, do the following in a POSIX environment:</p> <ol class="arabic simple"> <li>Download <a class="reference external" href="https://gist.github.com/vsajip/4b227eeec43817465ca835ca66f75e2b">the Gist</a> as a ZIP archive using the <span class="guilabel">Download ZIP</span> button.</li> <li>Unzip the above files from the archive into a scratch directory.</li> <li>In the scratch directory, run <code>bash prepare.sh</code> to get things ready. This creates a <code>run</code> subdirectory to contain Supervisor-related and log files, and a <code>venv</code> subdirectory to contain a virtual environment into which <code>bottle</code>, <code>gunicorn</code> and <code>supervisor</code> are installed.</li> <li>Run <code>bash ensure_app.sh</code> to ensure that Supervisor is running with the above configuration.</li> <li>Run <code>venv/bin/python client.py</code> to exercise the web application, which will lead to records being written to the log.</li> <li>Inspect the log files in the <code>run</code> subdirectory. You should see the most recent log lines in files matching the pattern <code>app.log*</code>. They won’t be in any particular order, since they have been handled concurrently by different worker processes in a non-deterministic way.</li> <li>You can shut down the listener and the web application by running <code>venv/bin/supervisorctl -c supervisor.conf shutdown</code>.</li> </ol> <p>You may need to tweak the configuration files in the unlikely event that the configured ports clash with something else in your test environment.</p> </section> </section> <section id="adding-contextual-information-to-your-logging-output"> <span id="context-info"></span><h2>Adding contextual information to your logging output</h2> <p>Sometimes you want logging output to contain contextual information in addition to the parameters passed to the logging call. For example, in a networked application, it may be desirable to log client-specific information in the log (e.g. remote client’s username, or IP address). Although you could use the <em>extra</em> parameter to achieve this, it’s not always convenient to pass the information in this way. While it might be tempting to create <a class="reference internal" href="../library/logging#logging.Logger" title="logging.Logger"><code>Logger</code></a> instances on a per-connection basis, this is not a good idea because these instances are not garbage collected. While this is not a problem in practice, when the number of <a class="reference internal" href="../library/logging#logging.Logger" title="logging.Logger"><code>Logger</code></a> instances is dependent on the level of granularity you want to use in logging an application, it could be hard to manage if the number of <a class="reference internal" href="../library/logging#logging.Logger" title="logging.Logger"><code>Logger</code></a> instances becomes effectively unbounded.</p> <section id="using-loggeradapters-to-impart-contextual-information"> <h3>Using LoggerAdapters to impart contextual information</h3> <p>An easy way in which you can pass contextual information to be output along with logging event information is to use the <a class="reference internal" href="../library/logging#logging.LoggerAdapter" title="logging.LoggerAdapter"><code>LoggerAdapter</code></a> class. This class is designed to look like a <a class="reference internal" href="../library/logging#logging.Logger" title="logging.Logger"><code>Logger</code></a>, so that you can call <a class="reference internal" href="../library/logging#logging.debug" title="logging.debug"><code>debug()</code></a>, <a class="reference internal" href="../library/logging#logging.info" title="logging.info"><code>info()</code></a>, <a class="reference internal" href="../library/logging#logging.warning" title="logging.warning"><code>warning()</code></a>, <a class="reference internal" href="../library/logging#logging.error" title="logging.error"><code>error()</code></a>, <a class="reference internal" href="../library/logging#logging.exception" title="logging.exception"><code>exception()</code></a>, <a class="reference internal" href="../library/logging#logging.critical" title="logging.critical"><code>critical()</code></a> and <a class="reference internal" href="../library/logging#logging.log" title="logging.log"><code>log()</code></a>. These methods have the same signatures as their counterparts in <a class="reference internal" href="../library/logging#logging.Logger" title="logging.Logger"><code>Logger</code></a>, so you can use the two types of instances interchangeably.</p> <p>When you create an instance of <a class="reference internal" href="../library/logging#logging.LoggerAdapter" title="logging.LoggerAdapter"><code>LoggerAdapter</code></a>, you pass it a <a class="reference internal" href="../library/logging#logging.Logger" title="logging.Logger"><code>Logger</code></a> instance and a dict-like object which contains your contextual information. When you call one of the logging methods on an instance of <a class="reference internal" href="../library/logging#logging.LoggerAdapter" title="logging.LoggerAdapter"><code>LoggerAdapter</code></a>, it delegates the call to the underlying instance of <a class="reference internal" href="../library/logging#logging.Logger" title="logging.Logger"><code>Logger</code></a> passed to its constructor, and arranges to pass the contextual information in the delegated call. Here’s a snippet from the code of <a class="reference internal" href="../library/logging#logging.LoggerAdapter" title="logging.LoggerAdapter"><code>LoggerAdapter</code></a>:</p> <pre data-language="python">def debug(self, msg, /, *args, **kwargs):
    """
    Delegate a debug call to the underlying logger, after adding
    contextual information from this adapter instance.
    """
    msg, kwargs = self.process(msg, kwargs)
    self.logger.debug(msg, *args, **kwargs)
</pre> <p>The <a class="reference internal" href="../library/logging#logging.LoggerAdapter.process" title="logging.LoggerAdapter.process"><code>process()</code></a> method of <a class="reference internal" href="../library/logging#logging.LoggerAdapter" title="logging.LoggerAdapter"><code>LoggerAdapter</code></a> is where the contextual information is added to the logging output. It’s passed the message and keyword arguments of the logging call, and it passes back (potentially) modified versions of these to use in the call to the underlying logger. The default implementation of this method leaves the message alone, but inserts an ‘extra’ key in the keyword argument whose value is the dict-like object passed to the constructor. Of course, if you had passed an ‘extra’ keyword argument in the call to the adapter, it will be silently overwritten.</p> <p>The advantage of using ‘extra’ is that the values in the dict-like object are merged into the <a class="reference internal" href="../library/logging#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> instance’s __dict__, allowing you to use customized strings with your <a class="reference internal" href="../library/logging#logging.Formatter" title="logging.Formatter"><code>Formatter</code></a> instances which know about the keys of the dict-like object. If you need a different method, e.g. if you want to prepend or append the contextual information to the message string, you just need to subclass <a class="reference internal" href="../library/logging#logging.LoggerAdapter" title="logging.LoggerAdapter"><code>LoggerAdapter</code></a> and override <a class="reference internal" href="../library/logging#logging.LoggerAdapter.process" title="logging.LoggerAdapter.process"><code>process()</code></a> to do what you need. Here is a simple example:</p> <pre data-language="python">class CustomAdapter(logging.LoggerAdapter):
    """
    This example adapter expects the passed in dict-like object to have a
    'connid' key, whose value in brackets is prepended to the log message.
    """
    def process(self, msg, kwargs):
        return '[%s] %s' % (self.extra['connid'], msg), kwargs
</pre> <p>which you can use like this:</p> <pre data-language="python">logger = logging.getLogger(__name__)
adapter = CustomAdapter(logger, {'connid': some_conn_id})
</pre> <p>Then any events that you log to the adapter will have the value of <code>some_conn_id</code> prepended to the log messages.</p> <section id="using-objects-other-than-dicts-to-pass-contextual-information"> <h4>Using objects other than dicts to pass contextual information</h4> <p>You don’t need to pass an actual dict to a <a class="reference internal" href="../library/logging#logging.LoggerAdapter" title="logging.LoggerAdapter"><code>LoggerAdapter</code></a> - you could pass an instance of a class which implements <code>__getitem__</code> and <code>__iter__</code> so that it looks like a dict to logging. This would be useful if you want to generate values dynamically (whereas the values in a dict would be constant).</p> </section> </section> <section id="using-filters-to-impart-contextual-information"> <span id="filters-contextual"></span><h3>Using Filters to impart contextual information</h3> <p>You can also add contextual information to log output using a user-defined <a class="reference internal" href="../library/logging#logging.Filter" title="logging.Filter"><code>Filter</code></a>. <code>Filter</code> instances are allowed to modify the <code>LogRecords</code> passed to them, including adding additional attributes which can then be output using a suitable format string, or if needed a custom <a class="reference internal" href="../library/logging#logging.Formatter" title="logging.Formatter"><code>Formatter</code></a>.</p> <p>For example in a web application, the request being processed (or at least, the interesting parts of it) can be stored in a threadlocal (<a class="reference internal" href="../library/threading#threading.local" title="threading.local"><code>threading.local</code></a>) variable, and then accessed from a <code>Filter</code> to add, say, information from the request - say, the remote IP address and remote user’s username - to the <code>LogRecord</code>, using the attribute names ‘ip’ and ‘user’ as in the <code>LoggerAdapter</code> example above. In that case, the same format string can be used to get similar output to that shown above. Here’s an example script:</p> <pre data-language="python">import logging
from random import choice

class ContextFilter(logging.Filter):
    """
    This is a filter which injects contextual information into the log.

    Rather than use actual contextual information, we just use random
    data in this demo.
    """

    USERS = ['jim', 'fred', 'sheila']
    IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']

    def filter(self, record):

        record.ip = choice(ContextFilter.IPS)
        record.user = choice(ContextFilter.USERS)
        return True

if __name__ == '__main__':
    levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
    a1 = logging.getLogger('a.b.c')
    a2 = logging.getLogger('d.e.f')

    f = ContextFilter()
    a1.addFilter(f)
    a2.addFilter(f)
    a1.debug('A debug message')
    a1.info('An info message with %s', 'some parameters')
    for x in range(10):
        lvl = choice(levels)
        lvlname = logging.getLevelName(lvl)
        a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')
</pre> <p>which, when run, produces something like:</p> <pre data-language="none">2010-09-06 22:38:15,292 a.b.c DEBUG    IP: 123.231.231.123 User: fred     A debug message
2010-09-06 22:38:15,300 a.b.c INFO     IP: 192.168.0.1     User: sheila   An info message with some parameters
2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters
2010-09-06 22:38:15,300 d.e.f ERROR    IP: 127.0.0.1       User: jim      A message at ERROR level with 2 parameters
2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 127.0.0.1       User: sheila   A message at DEBUG level with 2 parameters
2010-09-06 22:38:15,300 d.e.f ERROR    IP: 123.231.231.123 User: fred     A message at ERROR level with 2 parameters
2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1     User: jim      A message at CRITICAL level with 2 parameters
2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters
2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 192.168.0.1     User: jim      A message at DEBUG level with 2 parameters
2010-09-06 22:38:15,301 d.e.f ERROR    IP: 127.0.0.1       User: sheila   A message at ERROR level with 2 parameters
2010-09-06 22:38:15,301 d.e.f DEBUG    IP: 123.231.231.123 User: fred     A message at DEBUG level with 2 parameters
2010-09-06 22:38:15,301 d.e.f INFO     IP: 123.231.231.123 User: fred     A message at INFO level with 2 parameters
</pre> </section> </section> <section id="use-of-contextvars"> <h2>Use of <code>contextvars</code>
</h2> <p>Since Python 3.7, the <a class="reference internal" href="../library/contextvars#module-contextvars" title="contextvars: Context Variables"><code>contextvars</code></a> module has provided context-local storage which works for both <a class="reference internal" href="../library/threading#module-threading" title="threading: Thread-based parallelism."><code>threading</code></a> and <a class="reference internal" href="../library/asyncio#module-asyncio" title="asyncio: Asynchronous I/O."><code>asyncio</code></a> processing needs. This type of storage may thus be generally preferable to thread-locals. The following example shows how, in a multi-threaded environment, logs can populated with contextual information such as, for example, request attributes handled by web applications.</p> <p>For the purposes of illustration, say that you have different web applications, each independent of the other but running in the same Python process and using a library common to them. How can each of these applications have their own log, where all logging messages from the library (and other request processing code) are directed to the appropriate application’s log file, while including in the log additional contextual information such as client IP, HTTP request method and client username?</p> <p>Let’s assume that the library can be simulated by the following code:</p> <pre data-language="python"># webapplib.py
import logging
import time

logger = logging.getLogger(__name__)

def useful():
    # Just a representative event logged from the library
    logger.debug('Hello from webapplib!')
    # Just sleep for a bit so other threads get to run
    time.sleep(0.01)
</pre> <p>We can simulate the multiple web applications by means of two simple classes, <code>Request</code> and <code>WebApp</code>. These simulate how real threaded web applications work - each request is handled by a thread:</p> <pre data-language="python"># main.py
import argparse
from contextvars import ContextVar
import logging
import os
from random import choice
import threading
import webapplib

logger = logging.getLogger(__name__)
root = logging.getLogger()
root.setLevel(logging.DEBUG)

class Request:
    """
    A simple dummy request class which just holds dummy HTTP request method,
    client IP address and client username
    """
    def __init__(self, method, ip, user):
        self.method = method
        self.ip = ip
        self.user = user

# A dummy set of requests which will be used in the simulation - we'll just pick
# from this list randomly. Note that all GET requests are from 192.168.2.XXX
# addresses, whereas POST requests are from 192.16.3.XXX addresses. Three users
# are represented in the sample requests.

REQUESTS = [
    Request('GET', '192.168.2.20', 'jim'),
    Request('POST', '192.168.3.20', 'fred'),
    Request('GET', '192.168.2.21', 'sheila'),
    Request('POST', '192.168.3.21', 'jim'),
    Request('GET', '192.168.2.22', 'fred'),
    Request('POST', '192.168.3.22', 'sheila'),
]

# Note that the format string includes references to request context information
# such as HTTP method, client IP and username

formatter = logging.Formatter('%(threadName)-11s %(appName)s %(name)-9s %(user)-6s %(ip)s %(method)-4s %(message)s')

# Create our context variables. These will be filled at the start of request
# processing, and used in the logging that happens during that processing

ctx_request = ContextVar('request')
ctx_appname = ContextVar('appname')

class InjectingFilter(logging.Filter):
    """
    A filter which injects context-specific information into logs and ensures
    that only information for a specific webapp is included in its log
    """
    def __init__(self, app):
        self.app = app

    def filter(self, record):
        request = ctx_request.get()
        record.method = request.method
        record.ip = request.ip
        record.user = request.user
        record.appName = appName = ctx_appname.get()
        return appName == self.app.name

class WebApp:
    """
    A dummy web application class which has its own handler and filter for a
    webapp-specific log.
    """
    def __init__(self, name):
        self.name = name
        handler = logging.FileHandler(name + '.log', 'w')
        f = InjectingFilter(self)
        handler.setFormatter(formatter)
        handler.addFilter(f)
        root.addHandler(handler)
        self.num_requests = 0

    def process_request(self, request):
        """
        This is the dummy method for processing a request. It's called on a
        different thread for every request. We store the context information into
        the context vars before doing anything else.
        """
        ctx_request.set(request)
        ctx_appname.set(self.name)
        self.num_requests += 1
        logger.debug('Request processing started')
        webapplib.useful()
        logger.debug('Request processing finished')

def main():
    fn = os.path.splitext(os.path.basename(__file__))[0]
    adhf = argparse.ArgumentDefaultsHelpFormatter
    ap = argparse.ArgumentParser(formatter_class=adhf, prog=fn,
                                 description='Simulate a couple of web '
                                             'applications handling some '
                                             'requests, showing how request '
                                             'context can be used to '
                                             'populate logs')
    aa = ap.add_argument
    aa('--count', '-c', type=int, default=100, help='How many requests to simulate')
    options = ap.parse_args()

    # Create the dummy webapps and put them in a list which we can use to select
    # from randomly
    app1 = WebApp('app1')
    app2 = WebApp('app2')
    apps = [app1, app2]
    threads = []
    # Add a common handler which will capture all events
    handler = logging.FileHandler('app.log', 'w')
    handler.setFormatter(formatter)
    root.addHandler(handler)

    # Generate calls to process requests
    for i in range(options.count):
        try:
            # Pick an app at random and a request for it to process
            app = choice(apps)
            request = choice(REQUESTS)
            # Process the request in its own thread
            t = threading.Thread(target=app.process_request, args=(request,))
            threads.append(t)
            t.start()
        except KeyboardInterrupt:
            break

    # Wait for the threads to terminate
    for t in threads:
        t.join()

    for app in apps:
        print('%s processed %s requests' % (app.name, app.num_requests))

if __name__ == '__main__':
    main()
</pre> <p>If you run the above, you should find that roughly half the requests go into <code>app1.log</code> and the rest into <code>app2.log</code>, and the all the requests are logged to <code>app.log</code>. Each webapp-specific log will contain only log entries for only that webapp, and the request information will be displayed consistently in the log (i.e. the information in each dummy request will always appear together in a log line). This is illustrated by the following shell output:</p> <pre data-language="shell">~/logging-contextual-webapp$ python main.py
app1 processed 51 requests
app2 processed 49 requests
~/logging-contextual-webapp$ wc -l *.log
  153 app1.log
  147 app2.log
  300 app.log
  600 total
~/logging-contextual-webapp$ head -3 app1.log
Thread-3 (process_request) app1 __main__  jim    192.168.3.21 POST Request processing started
Thread-3 (process_request) app1 webapplib jim    192.168.3.21 POST Hello from webapplib!
Thread-5 (process_request) app1 __main__  jim    192.168.3.21 POST Request processing started
~/logging-contextual-webapp$ head -3 app2.log
Thread-1 (process_request) app2 __main__  sheila 192.168.2.21 GET  Request processing started
Thread-1 (process_request) app2 webapplib sheila 192.168.2.21 GET  Hello from webapplib!
Thread-2 (process_request) app2 __main__  jim    192.168.2.20 GET  Request processing started
~/logging-contextual-webapp$ head app.log
Thread-1 (process_request) app2 __main__  sheila 192.168.2.21 GET  Request processing started
Thread-1 (process_request) app2 webapplib sheila 192.168.2.21 GET  Hello from webapplib!
Thread-2 (process_request) app2 __main__  jim    192.168.2.20 GET  Request processing started
Thread-3 (process_request) app1 __main__  jim    192.168.3.21 POST Request processing started
Thread-2 (process_request) app2 webapplib jim    192.168.2.20 GET  Hello from webapplib!
Thread-3 (process_request) app1 webapplib jim    192.168.3.21 POST Hello from webapplib!
Thread-4 (process_request) app2 __main__  fred   192.168.2.22 GET  Request processing started
Thread-5 (process_request) app1 __main__  jim    192.168.3.21 POST Request processing started
Thread-4 (process_request) app2 webapplib fred   192.168.2.22 GET  Hello from webapplib!
Thread-6 (process_request) app1 __main__  jim    192.168.3.21 POST Request processing started
~/logging-contextual-webapp$ grep app1 app1.log | wc -l
153
~/logging-contextual-webapp$ grep app2 app2.log | wc -l
147
~/logging-contextual-webapp$ grep app1 app.log | wc -l
153
~/logging-contextual-webapp$ grep app2 app.log | wc -l
147
</pre> </section> <section id="imparting-contextual-information-in-handlers"> <h2>Imparting contextual information in handlers</h2> <p>Each <a class="reference internal" href="../library/logging#logging.Handler" title="logging.Handler"><code>Handler</code></a> has its own chain of filters. If you want to add contextual information to a <a class="reference internal" href="../library/logging#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> without leaking it to other handlers, you can use a filter that returns a new <a class="reference internal" href="../library/logging#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> instead of modifying it in-place, as shown in the following script:</p> <pre data-language="python">import copy
import logging

def filter(record: logging.LogRecord):
    record = copy.copy(record)
    record.user = 'jim'
    return record

if __name__ == '__main__':
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    handler = logging.StreamHandler()
    formatter = logging.Formatter('%(message)s from %(user)-8s')
    handler.setFormatter(formatter)
    handler.addFilter(filter)
    logger.addHandler(handler)

    logger.info('A log message')
</pre> </section> <section id="logging-to-a-single-file-from-multiple-processes"> <span id="multiple-processes"></span><h2>Logging to a single file from multiple processes</h2> <p>Although logging is thread-safe, and logging to a single file from multiple threads in a single process <em>is</em> supported, logging to a single file from <em>multiple processes</em> is <em>not</em> supported, because there is no standard way to serialize access to a single file across multiple processes in Python. If you need to log to a single file from multiple processes, one way of doing this is to have all the processes log to a <a class="reference internal" href="../library/logging.handlers#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><code>SocketHandler</code></a>, and have a separate process which implements a socket server which reads from the socket and logs to file. (If you prefer, you can dedicate one thread in one of the existing processes to perform this function.) <a class="reference internal" href="#network-logging"><span class="std std-ref">This section</span></a> documents this approach in more detail and includes a working socket receiver which can be used as a starting point for you to adapt in your own applications.</p> <p>You could also write your own handler which uses the <a class="reference internal" href="../library/multiprocessing#multiprocessing.Lock" title="multiprocessing.Lock"><code>Lock</code></a> class from the <a class="reference internal" href="../library/multiprocessing#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code>multiprocessing</code></a> module to serialize access to the file from your processes. The existing <a class="reference internal" href="../library/logging.handlers#logging.FileHandler" title="logging.FileHandler"><code>FileHandler</code></a> and subclasses do not make use of <a class="reference internal" href="../library/multiprocessing#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code>multiprocessing</code></a> at present, though they may do so in the future. Note that at present, the <a class="reference internal" href="../library/multiprocessing#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code>multiprocessing</code></a> module does not provide working lock functionality on all platforms (see <a class="reference external" href="https://bugs.python.org/issue3770">https://bugs.python.org/issue3770</a>).</p> <p>Alternatively, you can use a <code>Queue</code> and a <a class="reference internal" href="../library/logging.handlers#logging.handlers.QueueHandler" title="logging.handlers.QueueHandler"><code>QueueHandler</code></a> to send all logging events to one of the processes in your multi-process application. The following example script demonstrates how you can do this; in the example a separate listener process listens for events sent by other processes and logs them according to its own logging configuration. Although the example only demonstrates one way of doing it (for example, you may want to use a listener thread rather than a separate listener process – the implementation would be analogous) it does allow for completely different logging configurations for the listener and the other processes in your application, and can be used as the basis for code meeting your own specific requirements:</p> <pre data-language="python"># You'll need these imports in your own code
import logging
import logging.handlers
import multiprocessing

# Next two import lines for this demo only
from random import choice, random
import time

#
# Because you'll want to define the logging configurations for listener and workers, the
# listener and worker process functions take a configurer parameter which is a callable
# for configuring logging for that process. These functions are also passed the queue,
# which they use for communication.
#
# In practice, you can configure the listener however you want, but note that in this
# simple example, the listener does not apply level or filter logic to received records.
# In practice, you would probably want to do this logic in the worker processes, to avoid
# sending events which would be filtered out between processes.
#
# The size of the rotated files is made small so you can see the results easily.
def listener_configurer():
    root = logging.getLogger()
    h = logging.handlers.RotatingFileHandler('mptest.log', 'a', 300, 10)
    f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
    h.setFormatter(f)
    root.addHandler(h)

# This is the listener process top-level loop: wait for logging events
# (LogRecords)on the queue and handle them, quit when you get a None for a
# LogRecord.
def listener_process(queue, configurer):
    configurer()
    while True:
        try:
            record = queue.get()
            if record is None:  # We send this as a sentinel to tell the listener to quit.
                break
            logger = logging.getLogger(record.name)
            logger.handle(record)  # No level or filter logic applied - just do it!
        except Exception:
            import sys, traceback
            print('Whoops! Problem:', file=sys.stderr)
            traceback.print_exc(file=sys.stderr)

# Arrays used for random selections in this demo

LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
          logging.ERROR, logging.CRITICAL]

LOGGERS = ['a.b.c', 'd.e.f']

MESSAGES = [
    'Random message #1',
    'Random message #2',
    'Random message #3',
]

# The worker configuration is done at the start of the worker process run.
# Note that on Windows you can't rely on fork semantics, so each process
# will run the logging configuration code when it starts.
def worker_configurer(queue):
    h = logging.handlers.QueueHandler(queue)  # Just the one handler needed
    root = logging.getLogger()
    root.addHandler(h)
    # send all messages, for demo; no other level or filter logic applied.
    root.setLevel(logging.DEBUG)

# This is the worker process top-level loop, which just logs ten events with
# random intervening delays before terminating.
# The print messages are just so you know it's doing something!
def worker_process(queue, configurer):
    configurer(queue)
    name = multiprocessing.current_process().name
    print('Worker started: %s' % name)
    for i in range(10):
        time.sleep(random())
        logger = logging.getLogger(choice(LOGGERS))
        level = choice(LEVELS)
        message = choice(MESSAGES)
        logger.log(level, message)
    print('Worker finished: %s' % name)

# Here's where the demo gets orchestrated. Create the queue, create and start
# the listener, create ten workers and start them, wait for them to finish,
# then send a None to the queue to tell the listener to finish.
def main():
    queue = multiprocessing.Queue(-1)
    listener = multiprocessing.Process(target=listener_process,
                                       args=(queue, listener_configurer))
    listener.start()
    workers = []
    for i in range(10):
        worker = multiprocessing.Process(target=worker_process,
                                         args=(queue, worker_configurer))
        workers.append(worker)
        worker.start()
    for w in workers:
        w.join()
    queue.put_nowait(None)
    listener.join()

if __name__ == '__main__':
    main()
</pre> <p>A variant of the above script keeps the logging in the main process, in a separate thread:</p> <pre data-language="python">import logging
import logging.config
import logging.handlers
from multiprocessing import Process, Queue
import random
import threading
import time

def logger_thread(q):
    while True:
        record = q.get()
        if record is None:
            break
        logger = logging.getLogger(record.name)
        logger.handle(record)


def worker_process(q):
    qh = logging.handlers.QueueHandler(q)
    root = logging.getLogger()
    root.setLevel(logging.DEBUG)
    root.addHandler(qh)
    levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
              logging.CRITICAL]
    loggers = ['foo', 'foo.bar', 'foo.bar.baz',
               'spam', 'spam.ham', 'spam.ham.eggs']
    for i in range(100):
        lvl = random.choice(levels)
        logger = logging.getLogger(random.choice(loggers))
        logger.log(lvl, 'Message no. %d', i)

if __name__ == '__main__':
    q = Queue()
    d = {
        'version': 1,
        'formatters': {
            'detailed': {
                'class': 'logging.Formatter',
                'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
            }
        },
        'handlers': {
            'console': {
                'class': 'logging.StreamHandler',
                'level': 'INFO',
            },
            'file': {
                'class': 'logging.FileHandler',
                'filename': 'mplog.log',
                'mode': 'w',
                'formatter': 'detailed',
            },
            'foofile': {
                'class': 'logging.FileHandler',
                'filename': 'mplog-foo.log',
                'mode': 'w',
                'formatter': 'detailed',
            },
            'errors': {
                'class': 'logging.FileHandler',
                'filename': 'mplog-errors.log',
                'mode': 'w',
                'level': 'ERROR',
                'formatter': 'detailed',
            },
        },
        'loggers': {
            'foo': {
                'handlers': ['foofile']
            }
        },
        'root': {
            'level': 'DEBUG',
            'handlers': ['console', 'file', 'errors']
        },
    }
    workers = []
    for i in range(5):
        wp = Process(target=worker_process, name='worker %d' % (i + 1), args=(q,))
        workers.append(wp)
        wp.start()
    logging.config.dictConfig(d)
    lp = threading.Thread(target=logger_thread, args=(q,))
    lp.start()
    # At this point, the main process could do some useful work of its own
    # Once it's done that, it can wait for the workers to terminate...
    for wp in workers:
        wp.join()
    # And now tell the logging thread to finish up, too
    q.put(None)
    lp.join()
</pre> <p>This variant shows how you can e.g. apply configuration for particular loggers - e.g. the <code>foo</code> logger has a special handler which stores all events in the <code>foo</code> subsystem in a file <code>mplog-foo.log</code>. This will be used by the logging machinery in the main process (even though the logging events are generated in the worker processes) to direct the messages to the appropriate destinations.</p> <section id="using-concurrent-futures-processpoolexecutor"> <h3>Using concurrent.futures.ProcessPoolExecutor</h3> <p>If you want to use <a class="reference internal" href="../library/concurrent.futures#concurrent.futures.ProcessPoolExecutor" title="concurrent.futures.ProcessPoolExecutor"><code>concurrent.futures.ProcessPoolExecutor</code></a> to start your worker processes, you need to create the queue slightly differently. Instead of</p> <pre data-language="python">queue = multiprocessing.Queue(-1)
</pre> <p>you should use</p> <pre data-language="python">queue = multiprocessing.Manager().Queue(-1)  # also works with the examples above
</pre> <p>and you can then replace the worker creation from this:</p> <pre data-language="python">workers = []
for i in range(10):
    worker = multiprocessing.Process(target=worker_process,
                                     args=(queue, worker_configurer))
    workers.append(worker)
    worker.start()
for w in workers:
    w.join()
</pre> <p>to this (remembering to first import <a class="reference internal" href="../library/concurrent.futures#module-concurrent.futures" title="concurrent.futures: Execute computations concurrently using threads or processes."><code>concurrent.futures</code></a>):</p> <pre data-language="python">with concurrent.futures.ProcessPoolExecutor(max_workers=10) as executor:
    for i in range(10):
        executor.submit(worker_process, queue, worker_configurer)
</pre> </section> <section id="deploying-web-applications-using-gunicorn-and-uwsgi"> <h3>Deploying Web applications using Gunicorn and uWSGI</h3> <p>When deploying Web applications using <a class="reference external" href="https://gunicorn.org/">Gunicorn</a> or <a class="reference external" href="https://uwsgi-docs.readthedocs.io/en/latest/">uWSGI</a> (or similar), multiple worker processes are created to handle client requests. In such environments, avoid creating file-based handlers directly in your web application. Instead, use a <a class="reference internal" href="../library/logging.handlers#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><code>SocketHandler</code></a> to log from the web application to a listener in a separate process. This can be set up using a process management tool such as Supervisor - see <a class="reference internal" href="#running-a-logging-socket-listener-in-production">Running a logging socket listener in production</a> for more details.</p> </section> </section> <section id="using-file-rotation"> <h2>Using file rotation</h2> <p>Sometimes you want to let a log file grow to a certain size, then open a new file and log to that. You may want to keep a certain number of these files, and when that many files have been created, rotate the files so that the number of files and the size of the files both remain bounded. For this usage pattern, the logging package provides a <a class="reference internal" href="../library/logging.handlers#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><code>RotatingFileHandler</code></a>:</p> <pre data-language="python">import glob
import logging
import logging.handlers

LOG_FILENAME = 'logging_rotatingfile_example.out'

# Set up a specific logger with our desired output level
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)

# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(
              LOG_FILENAME, maxBytes=20, backupCount=5)

my_logger.addHandler(handler)

# Log some messages
for i in range(20):
    my_logger.debug('i = %d' % i)

# See what files are created
logfiles = glob.glob('%s*' % LOG_FILENAME)

for filename in logfiles:
    print(filename)
</pre> <p>The result should be 6 separate files, each with part of the log history for the application:</p> <pre data-language="none">logging_rotatingfile_example.out
logging_rotatingfile_example.out.1
logging_rotatingfile_example.out.2
logging_rotatingfile_example.out.3
logging_rotatingfile_example.out.4
logging_rotatingfile_example.out.5
</pre> <p>The most current file is always <code>logging_rotatingfile_example.out</code>, and each time it reaches the size limit it is renamed with the suffix <code>.1</code>. Each of the existing backup files is renamed to increment the suffix (<code>.1</code> becomes <code>.2</code>, etc.) and the <code>.6</code> file is erased.</p> <p>Obviously this example sets the log length much too small as an extreme example. You would want to set <em>maxBytes</em> to an appropriate value.</p> </section> <section id="use-of-alternative-formatting-styles"> <span id="format-styles"></span><h2>Use of alternative formatting styles</h2> <p>When logging was added to the Python standard library, the only way of formatting messages with variable content was to use the %-formatting method. Since then, Python has gained two new formatting approaches: <a class="reference internal" href="../library/string#string.Template" title="string.Template"><code>string.Template</code></a> (added in Python 2.4) and <a class="reference internal" href="../library/stdtypes#str.format" title="str.format"><code>str.format()</code></a> (added in Python 2.6).</p> <p>Logging (as of 3.2) provides improved support for these two additional formatting styles. The <a class="reference internal" href="../library/logging#logging.Formatter" title="logging.Formatter"><code>Formatter</code></a> class been enhanced to take an additional, optional keyword parameter named <code>style</code>. This defaults to <code>'%'</code>, but other possible values are <code>'{'</code> and <code>'$'</code>, which correspond to the other two formatting styles. Backwards compatibility is maintained by default (as you would expect), but by explicitly specifying a style parameter, you get the ability to specify format strings which work with <a class="reference internal" href="../library/stdtypes#str.format" title="str.format"><code>str.format()</code></a> or <a class="reference internal" href="../library/string#string.Template" title="string.Template"><code>string.Template</code></a>. Here’s an example console session to show the possibilities:</p> <pre data-language="pycon">&gt;&gt;&gt; import logging
&gt;&gt;&gt; root = logging.getLogger()
&gt;&gt;&gt; root.setLevel(logging.DEBUG)
&gt;&gt;&gt; handler = logging.StreamHandler()
&gt;&gt;&gt; bf = logging.Formatter('{asctime} {name} {levelname:8s} {message}',
...                        style='{')
&gt;&gt;&gt; handler.setFormatter(bf)
&gt;&gt;&gt; root.addHandler(handler)
&gt;&gt;&gt; logger = logging.getLogger('foo.bar')
&gt;&gt;&gt; logger.debug('This is a DEBUG message')
2010-10-28 15:11:55,341 foo.bar DEBUG    This is a DEBUG message
&gt;&gt;&gt; logger.critical('This is a CRITICAL message')
2010-10-28 15:12:11,526 foo.bar CRITICAL This is a CRITICAL message
&gt;&gt;&gt; df = logging.Formatter('$asctime $name ${levelname} $message',
...                        style='$')
&gt;&gt;&gt; handler.setFormatter(df)
&gt;&gt;&gt; logger.debug('This is a DEBUG message')
2010-10-28 15:13:06,924 foo.bar DEBUG This is a DEBUG message
&gt;&gt;&gt; logger.critical('This is a CRITICAL message')
2010-10-28 15:13:11,494 foo.bar CRITICAL This is a CRITICAL message
&gt;&gt;&gt;
</pre> <p>Note that the formatting of logging messages for final output to logs is completely independent of how an individual logging message is constructed. That can still use %-formatting, as shown here:</p> <pre data-language="python">&gt;&gt;&gt; logger.error('This is an%s %s %s', 'other,', 'ERROR,', 'message')
2010-10-28 15:19:29,833 foo.bar ERROR This is another, ERROR, message
&gt;&gt;&gt;
</pre> <p>Logging calls (<code>logger.debug()</code>, <code>logger.info()</code> etc.) only take positional parameters for the actual logging message itself, with keyword parameters used only for determining options for how to handle the actual logging call (e.g. the <code>exc_info</code> keyword parameter to indicate that traceback information should be logged, or the <code>extra</code> keyword parameter to indicate additional contextual information to be added to the log). So you cannot directly make logging calls using <a class="reference internal" href="../library/stdtypes#str.format" title="str.format"><code>str.format()</code></a> or <a class="reference internal" href="../library/string#string.Template" title="string.Template"><code>string.Template</code></a> syntax, because internally the logging package uses %-formatting to merge the format string and the variable arguments. There would be no changing this while preserving backward compatibility, since all logging calls which are out there in existing code will be using %-format strings.</p> <p>There is, however, a way that you can use {}- and $- formatting to construct your individual log messages. Recall that for a message you can use an arbitrary object as a message format string, and that the logging package will call <code>str()</code> on that object to get the actual format string. Consider the following two classes:</p> <pre data-language="python">class BraceMessage:
    def __init__(self, fmt, /, *args, **kwargs):
        self.fmt = fmt
        self.args = args
        self.kwargs = kwargs

    def __str__(self):
        return self.fmt.format(*self.args, **self.kwargs)

class DollarMessage:
    def __init__(self, fmt, /, **kwargs):
        self.fmt = fmt
        self.kwargs = kwargs

    def __str__(self):
        from string import Template
        return Template(self.fmt).substitute(**self.kwargs)
</pre> <p>Either of these can be used in place of a format string, to allow {}- or $-formatting to be used to build the actual “message” part which appears in the formatted log output in place of “%(message)s” or “{message}” or “$message”. It’s a little unwieldy to use the class names whenever you want to log something, but it’s quite palatable if you use an alias such as __ (double underscore — not to be confused with _, the single underscore used as a synonym/alias for <a class="reference internal" href="../library/gettext#gettext.gettext" title="gettext.gettext"><code>gettext.gettext()</code></a> or its brethren).</p> <p>The above classes are not included in Python, though they’re easy enough to copy and paste into your own code. They can be used as follows (assuming that they’re declared in a module called <code>wherever</code>):</p> <pre data-language="pycon">&gt;&gt;&gt; from wherever import BraceMessage as __
&gt;&gt;&gt; print(__('Message with {0} {name}', 2, name='placeholders'))
Message with 2 placeholders
&gt;&gt;&gt; class Point: pass
...
&gt;&gt;&gt; p = Point()
&gt;&gt;&gt; p.x = 0.5
&gt;&gt;&gt; p.y = 0.5
&gt;&gt;&gt; print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})',
...       point=p))
Message with coordinates: (0.50, 0.50)
&gt;&gt;&gt; from wherever import DollarMessage as __
&gt;&gt;&gt; print(__('Message with $num $what', num=2, what='placeholders'))
Message with 2 placeholders
&gt;&gt;&gt;
</pre> <p>While the above examples use <code>print()</code> to show how the formatting works, you would of course use <code>logger.debug()</code> or similar to actually log using this approach.</p> <p>One thing to note is that you pay no significant performance penalty with this approach: the actual formatting happens not when you make the logging call, but when (and if) the logged message is actually about to be output to a log by a handler. So the only slightly unusual thing which might trip you up is that the parentheses go around the format string and the arguments, not just the format string. That’s because the __ notation is just syntax sugar for a constructor call to one of the <code><em>XXX</em>Message</code> classes.</p> <p>If you prefer, you can use a <a class="reference internal" href="../library/logging#logging.LoggerAdapter" title="logging.LoggerAdapter"><code>LoggerAdapter</code></a> to achieve a similar effect to the above, as in the following example:</p> <pre data-language="python">import logging

class Message:
    def __init__(self, fmt, args):
        self.fmt = fmt
        self.args = args

    def __str__(self):
        return self.fmt.format(*self.args)

class StyleAdapter(logging.LoggerAdapter):
    def __init__(self, logger, extra=None):
        super().__init__(logger, extra or {})

    def log(self, level, msg, /, *args, **kwargs):
        if self.isEnabledFor(level):
            msg, kwargs = self.process(msg, kwargs)
            self.logger._log(level, Message(msg, args), (), **kwargs)

logger = StyleAdapter(logging.getLogger(__name__))

def main():
    logger.debug('Hello, {}', 'world!')

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    main()
</pre> <p>The above script should log the message <code>Hello, world!</code> when run with Python 3.2 or later.</p> </section> <section id="customizing-logrecord"> <span id="custom-logrecord"></span><h2>Customizing <code>LogRecord</code>
</h2> <p>Every logging event is represented by a <a class="reference internal" href="../library/logging#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> instance. When an event is logged and not filtered out by a logger’s level, a <a class="reference internal" href="../library/logging#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> is created, populated with information about the event and then passed to the handlers for that logger (and its ancestors, up to and including the logger where further propagation up the hierarchy is disabled). Before Python 3.2, there were only two places where this creation was done:</p> <ul class="simple"> <li>
<a class="reference internal" href="../library/logging#logging.Logger.makeRecord" title="logging.Logger.makeRecord"><code>Logger.makeRecord()</code></a>, which is called in the normal process of logging an event. This invoked <a class="reference internal" href="../library/logging#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> directly to create an instance.</li> <li>
<a class="reference internal" href="../library/logging#logging.makeLogRecord" title="logging.makeLogRecord"><code>makeLogRecord()</code></a>, which is called with a dictionary containing attributes to be added to the LogRecord. This is typically invoked when a suitable dictionary has been received over the network (e.g. in pickle form via a <a class="reference internal" href="../library/logging.handlers#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><code>SocketHandler</code></a>, or in JSON form via an <a class="reference internal" href="../library/logging.handlers#logging.handlers.HTTPHandler" title="logging.handlers.HTTPHandler"><code>HTTPHandler</code></a>).</li> </ul> <p>This has usually meant that if you need to do anything special with a <a class="reference internal" href="../library/logging#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a>, you’ve had to do one of the following.</p> <ul class="simple"> <li>Create your own <a class="reference internal" href="../library/logging#logging.Logger" title="logging.Logger"><code>Logger</code></a> subclass, which overrides <a class="reference internal" href="../library/logging#logging.Logger.makeRecord" title="logging.Logger.makeRecord"><code>Logger.makeRecord()</code></a>, and set it using <a class="reference internal" href="../library/logging#logging.setLoggerClass" title="logging.setLoggerClass"><code>setLoggerClass()</code></a> before any loggers that you care about are instantiated.</li> <li>Add a <a class="reference internal" href="../library/logging#logging.Filter" title="logging.Filter"><code>Filter</code></a> to a logger or handler, which does the necessary special manipulation you need when its <a class="reference internal" href="../library/logging#logging.Filter.filter" title="logging.Filter.filter"><code>filter()</code></a> method is called.</li> </ul> <p>The first approach would be a little unwieldy in the scenario where (say) several different libraries wanted to do different things. Each would attempt to set its own <a class="reference internal" href="../library/logging#logging.Logger" title="logging.Logger"><code>Logger</code></a> subclass, and the one which did this last would win.</p> <p>The second approach works reasonably well for many cases, but does not allow you to e.g. use a specialized subclass of <a class="reference internal" href="../library/logging#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a>. Library developers can set a suitable filter on their loggers, but they would have to remember to do this every time they introduced a new logger (which they would do simply by adding new packages or modules and doing</p> <pre data-language="python">logger = logging.getLogger(__name__)
</pre> <p>at module level). It’s probably one too many things to think about. Developers could also add the filter to a <a class="reference internal" href="../library/logging.handlers#logging.NullHandler" title="logging.NullHandler"><code>NullHandler</code></a> attached to their top-level logger, but this would not be invoked if an application developer attached a handler to a lower-level library logger — so output from that handler would not reflect the intentions of the library developer.</p> <p>In Python 3.2 and later, <a class="reference internal" href="../library/logging#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> creation is done through a factory, which you can specify. The factory is just a callable you can set with <a class="reference internal" href="../library/logging#logging.setLogRecordFactory" title="logging.setLogRecordFactory"><code>setLogRecordFactory()</code></a>, and interrogate with <a class="reference internal" href="../library/logging#logging.getLogRecordFactory" title="logging.getLogRecordFactory"><code>getLogRecordFactory()</code></a>. The factory is invoked with the same signature as the <a class="reference internal" href="../library/logging#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> constructor, as <a class="reference internal" href="../library/logging#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> is the default setting for the factory.</p> <p>This approach allows a custom factory to control all aspects of LogRecord creation. For example, you could return a subclass, or just add some additional attributes to the record once created, using a pattern similar to this:</p> <pre data-language="python">old_factory = logging.getLogRecordFactory()

def record_factory(*args, **kwargs):
    record = old_factory(*args, **kwargs)
    record.custom_attribute = 0xdecafbad
    return record

logging.setLogRecordFactory(record_factory)
</pre> <p>This pattern allows different libraries to chain factories together, and as long as they don’t overwrite each other’s attributes or unintentionally overwrite the attributes provided as standard, there should be no surprises. However, it should be borne in mind that each link in the chain adds run-time overhead to all logging operations, and the technique should only be used when the use of a <a class="reference internal" href="../library/logging#logging.Filter" title="logging.Filter"><code>Filter</code></a> does not provide the desired result.</p> </section> <section id="subclassing-queuehandler-a-zeromq-example"> <span id="zeromq-handlers"></span><h2>Subclassing QueueHandler - a ZeroMQ example</h2> <p>You can use a <a class="reference internal" href="../library/logging.handlers#logging.handlers.QueueHandler" title="logging.handlers.QueueHandler"><code>QueueHandler</code></a> subclass to send messages to other kinds of queues, for example a ZeroMQ ‘publish’ socket. In the example below,the socket is created separately and passed to the handler (as its ‘queue’):</p> <pre data-language="python">import zmq   # using pyzmq, the Python binding for ZeroMQ
import json  # for serializing records portably

ctx = zmq.Context()
sock = zmq.Socket(ctx, zmq.PUB)  # or zmq.PUSH, or other suitable value
sock.bind('tcp://*:5556')        # or wherever

class ZeroMQSocketHandler(QueueHandler):
    def enqueue(self, record):
        self.queue.send_json(record.__dict__)


handler = ZeroMQSocketHandler(sock)
</pre> <p>Of course there are other ways of organizing this, for example passing in the data needed by the handler to create the socket:</p> <pre data-language="python">class ZeroMQSocketHandler(QueueHandler):
    def __init__(self, uri, socktype=zmq.PUB, ctx=None):
        self.ctx = ctx or zmq.Context()
        socket = zmq.Socket(self.ctx, socktype)
        socket.bind(uri)
        super().__init__(socket)

    def enqueue(self, record):
        self.queue.send_json(record.__dict__)

    def close(self):
        self.queue.close()
</pre> </section> <section id="subclassing-queuelistener-a-zeromq-example"> <h2>Subclassing QueueListener - a ZeroMQ example</h2> <p>You can also subclass <a class="reference internal" href="../library/logging.handlers#logging.handlers.QueueListener" title="logging.handlers.QueueListener"><code>QueueListener</code></a> to get messages from other kinds of queues, for example a ZeroMQ ‘subscribe’ socket. Here’s an example:</p> <pre data-language="python">class ZeroMQSocketListener(QueueListener):
    def __init__(self, uri, /, *handlers, **kwargs):
        self.ctx = kwargs.get('ctx') or zmq.Context()
        socket = zmq.Socket(self.ctx, zmq.SUB)
        socket.setsockopt_string(zmq.SUBSCRIBE, '')  # subscribe to everything
        socket.connect(uri)
        super().__init__(socket, *handlers, **kwargs)

    def dequeue(self):
        msg = self.queue.recv_json()
        return logging.makeLogRecord(msg)
</pre> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt>
<code>Module</code> <a class="reference internal" href="../library/logging#module-logging" title="logging: Flexible event logging system for applications."><code>logging</code></a>
</dt>
<dd>
<p>API reference for the logging module.</p> </dd> <dt>
<code>Module</code> <a class="reference internal" href="../library/logging.config#module-logging.config" title="logging.config: Configuration of the logging module."><code>logging.config</code></a>
</dt>
<dd>
<p>Configuration API for the logging module.</p> </dd> <dt>
<code>Module</code> <a class="reference internal" href="../library/logging.handlers#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code>logging.handlers</code></a>
</dt>
<dd>
<p>Useful handlers included with the logging module.</p> </dd> </dl> <p><a class="reference internal" href="logging#logging-basic-tutorial"><span class="std std-ref">A basic logging tutorial</span></a></p> <p><a class="reference internal" href="logging#logging-advanced-tutorial"><span class="std std-ref">A more advanced logging tutorial</span></a></p> </div> </section> <section id="an-example-dictionary-based-configuration"> <h2>An example dictionary-based configuration</h2> <p>Below is an example of a logging configuration dictionary - it’s taken from the <a class="reference external" href="https://docs.djangoproject.com/en/stable/topics/logging/#configuring-logging">documentation on the Django project</a>. This dictionary is passed to <a class="reference internal" href="../library/logging.config#logging.config.dictConfig" title="logging.config.dictConfig"><code>dictConfig()</code></a> to put the configuration into effect:</p> <pre data-language="python">LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'filters': {
        'special': {
            '()': 'project.logging.SpecialFilter',
            'foo': 'bar',
        }
    },
    'handlers': {
        'null': {
            'level':'DEBUG',
            'class':'django.utils.log.NullHandler',
        },
        'console':{
            'level':'DEBUG',
            'class':'logging.StreamHandler',
            'formatter': 'simple'
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'filters': ['special']
        }
    },
    'loggers': {
        'django': {
            'handlers':['null'],
            'propagate': True,
            'level':'INFO',
        },
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': False,
        },
        'myproject.custom': {
            'handlers': ['console', 'mail_admins'],
            'level': 'INFO',
            'filters': ['special']
        }
    }
}
</pre> <p>For more information about this configuration, you can see the <a class="reference external" href="https://docs.djangoproject.com/en/stable/topics/logging/#configuring-logging">relevant section</a> of the Django documentation.</p> </section> <section id="using-a-rotator-and-namer-to-customize-log-rotation-processing"> <span id="cookbook-rotator-namer"></span><h2>Using a rotator and namer to customize log rotation processing</h2> <p>An example of how you can define a namer and rotator is given in the following runnable script, which shows gzip compression of the log file:</p> <pre data-language="python">import gzip
import logging
import logging.handlers
import os
import shutil

def namer(name):
    return name + ".gz"

def rotator(source, dest):
    with open(source, 'rb') as f_in:
        with gzip.open(dest, 'wb') as f_out:
            shutil.copyfileobj(f_in, f_out)
    os.remove(source)


rh = logging.handlers.RotatingFileHandler('rotated.log', maxBytes=128, backupCount=5)
rh.rotator = rotator
rh.namer = namer

root = logging.getLogger()
root.setLevel(logging.INFO)
root.addHandler(rh)
f = logging.Formatter('%(asctime)s %(message)s')
rh.setFormatter(f)
for i in range(1000):
    root.info(f'Message no. {i + 1}')
</pre> <p>After running this, you will see six new files, five of which are compressed:</p> <pre data-language="shell">$ ls rotated.log*
rotated.log       rotated.log.2.gz  rotated.log.4.gz
rotated.log.1.gz  rotated.log.3.gz  rotated.log.5.gz
$ zcat rotated.log.1.gz
2023-01-20 02:28:17,767 Message no. 996
2023-01-20 02:28:17,767 Message no. 997
2023-01-20 02:28:17,767 Message no. 998
</pre> </section> <section id="a-more-elaborate-multiprocessing-example"> <h2>A more elaborate multiprocessing example</h2> <p>The following working example shows how logging can be used with multiprocessing using configuration files. The configurations are fairly simple, but serve to illustrate how more complex ones could be implemented in a real multiprocessing scenario.</p> <p>In the example, the main process spawns a listener process and some worker processes. Each of the main process, the listener and the workers have three separate configurations (the workers all share the same configuration). We can see logging in the main process, how the workers log to a QueueHandler and how the listener implements a QueueListener and a more complex logging configuration, and arranges to dispatch events received via the queue to the handlers specified in the configuration. Note that these configurations are purely illustrative, but you should be able to adapt this example to your own scenario.</p> <p>Here’s the script - the docstrings and the comments hopefully explain how it works:</p> <pre data-language="python">import logging
import logging.config
import logging.handlers
from multiprocessing import Process, Queue, Event, current_process
import os
import random
import time

class MyHandler:
    """
    A simple handler for logging events. It runs in the listener process and
    dispatches events to loggers based on the name in the received record,
    which then get dispatched, by the logging system, to the handlers
    configured for those loggers.
    """

    def handle(self, record):
        if record.name == "root":
            logger = logging.getLogger()
        else:
            logger = logging.getLogger(record.name)

        if logger.isEnabledFor(record.levelno):
            # The process name is transformed just to show that it's the listener
            # doing the logging to files and console
            record.processName = '%s (for %s)' % (current_process().name, record.processName)
            logger.handle(record)

def listener_process(q, stop_event, config):
    """
    This could be done in the main process, but is just done in a separate
    process for illustrative purposes.

    This initialises logging according to the specified configuration,
    starts the listener and waits for the main process to signal completion
    via the event. The listener is then stopped, and the process exits.
    """
    logging.config.dictConfig(config)
    listener = logging.handlers.QueueListener(q, MyHandler())
    listener.start()
    if os.name == 'posix':
        # On POSIX, the setup logger will have been configured in the
        # parent process, but should have been disabled following the
        # dictConfig call.
        # On Windows, since fork isn't used, the setup logger won't
        # exist in the child, so it would be created and the message
        # would appear - hence the "if posix" clause.
        logger = logging.getLogger('setup')
        logger.critical('Should not appear, because of disabled logger ...')
    stop_event.wait()
    listener.stop()

def worker_process(config):
    """
    A number of these are spawned for the purpose of illustration. In
    practice, they could be a heterogeneous bunch of processes rather than
    ones which are identical to each other.

    This initialises logging according to the specified configuration,
    and logs a hundred messages with random levels to randomly selected
    loggers.

    A small sleep is added to allow other processes a chance to run. This
    is not strictly needed, but it mixes the output from the different
    processes a bit more than if it's left out.
    """
    logging.config.dictConfig(config)
    levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
              logging.CRITICAL]
    loggers = ['foo', 'foo.bar', 'foo.bar.baz',
               'spam', 'spam.ham', 'spam.ham.eggs']
    if os.name == 'posix':
        # On POSIX, the setup logger will have been configured in the
        # parent process, but should have been disabled following the
        # dictConfig call.
        # On Windows, since fork isn't used, the setup logger won't
        # exist in the child, so it would be created and the message
        # would appear - hence the "if posix" clause.
        logger = logging.getLogger('setup')
        logger.critical('Should not appear, because of disabled logger ...')
    for i in range(100):
        lvl = random.choice(levels)
        logger = logging.getLogger(random.choice(loggers))
        logger.log(lvl, 'Message no. %d', i)
        time.sleep(0.01)

def main():
    q = Queue()
    # The main process gets a simple configuration which prints to the console.
    config_initial = {
        'version': 1,
        'handlers': {
            'console': {
                'class': 'logging.StreamHandler',
                'level': 'INFO'
            }
        },
        'root': {
            'handlers': ['console'],
            'level': 'DEBUG'
        }
    }
    # The worker process configuration is just a QueueHandler attached to the
    # root logger, which allows all messages to be sent to the queue.
    # We disable existing loggers to disable the "setup" logger used in the
    # parent process. This is needed on POSIX because the logger will
    # be there in the child following a fork().
    config_worker = {
        'version': 1,
        'disable_existing_loggers': True,
        'handlers': {
            'queue': {
                'class': 'logging.handlers.QueueHandler',
                'queue': q
            }
        },
        'root': {
            'handlers': ['queue'],
            'level': 'DEBUG'
        }
    }
    # The listener process configuration shows that the full flexibility of
    # logging configuration is available to dispatch events to handlers however
    # you want.
    # We disable existing loggers to disable the "setup" logger used in the
    # parent process. This is needed on POSIX because the logger will
    # be there in the child following a fork().
    config_listener = {
        'version': 1,
        'disable_existing_loggers': True,
        'formatters': {
            'detailed': {
                'class': 'logging.Formatter',
                'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
            },
            'simple': {
                'class': 'logging.Formatter',
                'format': '%(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
            }
        },
        'handlers': {
            'console': {
                'class': 'logging.StreamHandler',
                'formatter': 'simple',
                'level': 'INFO'
            },
            'file': {
                'class': 'logging.FileHandler',
                'filename': 'mplog.log',
                'mode': 'w',
                'formatter': 'detailed'
            },
            'foofile': {
                'class': 'logging.FileHandler',
                'filename': 'mplog-foo.log',
                'mode': 'w',
                'formatter': 'detailed'
            },
            'errors': {
                'class': 'logging.FileHandler',
                'filename': 'mplog-errors.log',
                'mode': 'w',
                'formatter': 'detailed',
                'level': 'ERROR'
            }
        },
        'loggers': {
            'foo': {
                'handlers': ['foofile']
            }
        },
        'root': {
            'handlers': ['console', 'file', 'errors'],
            'level': 'DEBUG'
        }
    }
    # Log some initial events, just to show that logging in the parent works
    # normally.
    logging.config.dictConfig(config_initial)
    logger = logging.getLogger('setup')
    logger.info('About to create workers ...')
    workers = []
    for i in range(5):
        wp = Process(target=worker_process, name='worker %d' % (i + 1),
                     args=(config_worker,))
        workers.append(wp)
        wp.start()
        logger.info('Started worker: %s', wp.name)
    logger.info('About to create listener ...')
    stop_event = Event()
    lp = Process(target=listener_process, name='listener',
                 args=(q, stop_event, config_listener))
    lp.start()
    logger.info('Started listener')
    # We now hang around for the workers to finish their work.
    for wp in workers:
        wp.join()
    # Workers all done, listening can now stop.
    # Logging in the parent still works normally.
    logger.info('Telling listener to stop ...')
    stop_event.set()
    lp.join()
    logger.info('All done.')

if __name__ == '__main__':
    main()
</pre> </section> <section id="inserting-a-bom-into-messages-sent-to-a-sysloghandler"> <h2>Inserting a BOM into messages sent to a SysLogHandler</h2> <p><span class="target" id="index-0"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc5424.html"><strong>RFC 5424</strong></a> requires that a Unicode message be sent to a syslog daemon as a set of bytes which have the following structure: an optional pure-ASCII component, followed by a UTF-8 Byte Order Mark (BOM), followed by Unicode encoded using UTF-8. (See the <span class="target" id="index-1"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc5424.html#section-6"><strong>relevant section of the specification</strong></a>.)</p> <p>In Python 3.1, code was added to <a class="reference internal" href="../library/logging.handlers#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><code>SysLogHandler</code></a> to insert a BOM into the message, but unfortunately, it was implemented incorrectly, with the BOM appearing at the beginning of the message and hence not allowing any pure-ASCII component to appear before it.</p> <p>As this behaviour is broken, the incorrect BOM insertion code is being removed from Python 3.2.4 and later. However, it is not being replaced, and if you want to produce <span class="target" id="index-2"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc5424.html"><strong>RFC 5424</strong></a>-compliant messages which include a BOM, an optional pure-ASCII sequence before it and arbitrary Unicode after it, encoded using UTF-8, then you need to do the following:</p> <ol class="arabic"> <li>
<p>Attach a <a class="reference internal" href="../library/logging#logging.Formatter" title="logging.Formatter"><code>Formatter</code></a> instance to your <a class="reference internal" href="../library/logging.handlers#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><code>SysLogHandler</code></a> instance, with a format string such as:</p> <pre data-language="python">'ASCII section\ufeffUnicode section'
</pre> <p>The Unicode code point U+FEFF, when encoded using UTF-8, will be encoded as a UTF-8 BOM – the byte-string <code>b'\xef\xbb\xbf'</code>.</p> </li> <li>Replace the ASCII section with whatever placeholders you like, but make sure that the data that appears in there after substitution is always ASCII (that way, it will remain unchanged after UTF-8 encoding).</li> <li>Replace the Unicode section with whatever placeholders you like; if the data which appears there after substitution contains characters outside the ASCII range, that’s fine – it will be encoded using UTF-8.</li> </ol> <p>The formatted message <em>will</em> be encoded using UTF-8 encoding by <code>SysLogHandler</code>. If you follow the above rules, you should be able to produce <span class="target" id="index-3"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc5424.html"><strong>RFC 5424</strong></a>-compliant messages. If you don’t, logging may not complain, but your messages will not be RFC 5424-compliant, and your syslog daemon may complain.</p> </section> <section id="implementing-structured-logging"> <h2>Implementing structured logging</h2> <p>Although most logging messages are intended for reading by humans, and thus not readily machine-parseable, there might be circumstances where you want to output messages in a structured format which <em>is</em> capable of being parsed by a program (without needing complex regular expressions to parse the log message). This is straightforward to achieve using the logging package. There are a number of ways in which this could be achieved, but the following is a simple approach which uses JSON to serialise the event in a machine-parseable manner:</p> <pre data-language="python">import json
import logging

class StructuredMessage:
    def __init__(self, message, /, **kwargs):
        self.message = message
        self.kwargs = kwargs

    def __str__(self):
        return '%s &gt;&gt;&gt; %s' % (self.message, json.dumps(self.kwargs))

_ = StructuredMessage   # optional, to improve readability

logging.basicConfig(level=logging.INFO, format='%(message)s')
logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456))
</pre> <p>If the above script is run, it prints:</p> <pre data-language="none">message 1 &gt;&gt;&gt; {"fnum": 123.456, "num": 123, "bar": "baz", "foo": "bar"}
</pre> <p>Note that the order of items might be different according to the version of Python used.</p> <p>If you need more specialised processing, you can use a custom JSON encoder, as in the following complete example:</p> <pre data-language="python">import json
import logging


class Encoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, set):
            return tuple(o)
        elif isinstance(o, str):
            return o.encode('unicode_escape').decode('ascii')
        return super().default(o)

class StructuredMessage:
    def __init__(self, message, /, **kwargs):
        self.message = message
        self.kwargs = kwargs

    def __str__(self):
        s = Encoder().encode(self.kwargs)
        return '%s &gt;&gt;&gt; %s' % (self.message, s)

_ = StructuredMessage   # optional, to improve readability

def main():
    logging.basicConfig(level=logging.INFO, format='%(message)s')
    logging.info(_('message 1', set_value={1, 2, 3}, snowman='\u2603'))

if __name__ == '__main__':
    main()
</pre> <p>When the above script is run, it prints:</p> <pre data-language="none">message 1 &gt;&gt;&gt; {"snowman": "\u2603", "set_value": [1, 2, 3]}
</pre> <p>Note that the order of items might be different according to the version of Python used.</p> </section> <section id="customizing-handlers-with-dictconfig"> <span id="custom-handlers"></span><h2>Customizing handlers with dictConfig()</h2> <p>There are times when you want to customize logging handlers in particular ways, and if you use <a class="reference internal" href="../library/logging.config#logging.config.dictConfig" title="logging.config.dictConfig"><code>dictConfig()</code></a> you may be able to do this without subclassing. As an example, consider that you may want to set the ownership of a log file. On POSIX, this is easily done using <a class="reference internal" href="../library/shutil#shutil.chown" title="shutil.chown"><code>shutil.chown()</code></a>, but the file handlers in the stdlib don’t offer built-in support. You can customize handler creation using a plain function such as:</p> <pre data-language="python">def owned_file_handler(filename, mode='a', encoding=None, owner=None):
    if owner:
        if not os.path.exists(filename):
            open(filename, 'a').close()
        shutil.chown(filename, *owner)
    return logging.FileHandler(filename, mode, encoding)
</pre> <p>You can then specify, in a logging configuration passed to <a class="reference internal" href="../library/logging.config#logging.config.dictConfig" title="logging.config.dictConfig"><code>dictConfig()</code></a>, that a logging handler be created by calling this function:</p> <pre data-language="python">LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'default': {
            'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
        },
    },
    'handlers': {
        'file':{
            # The values below are popped from this dictionary and
            # used to create the handler, set the handler's level and
            # its formatter.
            '()': owned_file_handler,
            'level':'DEBUG',
            'formatter': 'default',
            # The values below are passed to the handler creator callable
            # as keyword arguments.
            'owner': ['pulse', 'pulse'],
            'filename': 'chowntest.log',
            'mode': 'w',
            'encoding': 'utf-8',
        },
    },
    'root': {
        'handlers': ['file'],
        'level': 'DEBUG',
    },
}
</pre> <p>In this example I am setting the ownership using the <code>pulse</code> user and group, just for the purposes of illustration. Putting it together into a working script, <code>chowntest.py</code>:</p> <pre data-language="python">import logging, logging.config, os, shutil

def owned_file_handler(filename, mode='a', encoding=None, owner=None):
    if owner:
        if not os.path.exists(filename):
            open(filename, 'a').close()
        shutil.chown(filename, *owner)
    return logging.FileHandler(filename, mode, encoding)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'default': {
            'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
        },
    },
    'handlers': {
        'file':{
            # The values below are popped from this dictionary and
            # used to create the handler, set the handler's level and
            # its formatter.
            '()': owned_file_handler,
            'level':'DEBUG',
            'formatter': 'default',
            # The values below are passed to the handler creator callable
            # as keyword arguments.
            'owner': ['pulse', 'pulse'],
            'filename': 'chowntest.log',
            'mode': 'w',
            'encoding': 'utf-8',
        },
    },
    'root': {
        'handlers': ['file'],
        'level': 'DEBUG',
    },
}

logging.config.dictConfig(LOGGING)
logger = logging.getLogger('mylogger')
logger.debug('A debug message')
</pre> <p>To run this, you will probably need to run as <code>root</code>:</p> <pre data-language="shell">$ sudo python3.3 chowntest.py
$ cat chowntest.log
2013-11-05 09:34:51,128 DEBUG mylogger A debug message
$ ls -l chowntest.log
-rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log
</pre> <p>Note that this example uses Python 3.3 because that’s where <a class="reference internal" href="../library/shutil#shutil.chown" title="shutil.chown"><code>shutil.chown()</code></a> makes an appearance. This approach should work with any Python version that supports <a class="reference internal" href="../library/logging.config#logging.config.dictConfig" title="logging.config.dictConfig"><code>dictConfig()</code></a> - namely, Python 2.7, 3.2 or later. With pre-3.3 versions, you would need to implement the actual ownership change using e.g. <a class="reference internal" href="../library/os#os.chown" title="os.chown"><code>os.chown()</code></a>.</p> <p>In practice, the handler-creating function may be in a utility module somewhere in your project. Instead of the line in the configuration:</p> <pre data-language="python">'()': owned_file_handler,
</pre> <p>you could use e.g.:</p> <pre data-language="python">'()': 'ext://project.util.owned_file_handler',
</pre> <p>where <code>project.util</code> can be replaced with the actual name of the package where the function resides. In the above working script, using <code>'ext://__main__.owned_file_handler'</code> should work. Here, the actual callable is resolved by <a class="reference internal" href="../library/logging.config#logging.config.dictConfig" title="logging.config.dictConfig"><code>dictConfig()</code></a> from the <code>ext://</code> specification.</p> <p>This example hopefully also points the way to how you could implement other types of file change - e.g. setting specific POSIX permission bits - in the same way, using <a class="reference internal" href="../library/os#os.chmod" title="os.chmod"><code>os.chmod()</code></a>.</p> <p>Of course, the approach could also be extended to types of handler other than a <a class="reference internal" href="../library/logging.handlers#logging.FileHandler" title="logging.FileHandler"><code>FileHandler</code></a> - for example, one of the rotating file handlers, or a different type of handler altogether.</p> </section> <section id="using-particular-formatting-styles-throughout-your-application"> <span id="formatting-styles"></span><h2>Using particular formatting styles throughout your application</h2> <p>In Python 3.2, the <a class="reference internal" href="../library/logging#logging.Formatter" title="logging.Formatter"><code>Formatter</code></a> gained a <code>style</code> keyword parameter which, while defaulting to <code>%</code> for backward compatibility, allowed the specification of <code>{</code> or <code>$</code> to support the formatting approaches supported by <a class="reference internal" href="../library/stdtypes#str.format" title="str.format"><code>str.format()</code></a> and <a class="reference internal" href="../library/string#string.Template" title="string.Template"><code>string.Template</code></a>. Note that this governs the formatting of logging messages for final output to logs, and is completely orthogonal to how an individual logging message is constructed.</p> <p>Logging calls (<a class="reference internal" href="../library/logging#logging.Logger.debug" title="logging.Logger.debug"><code>debug()</code></a>, <a class="reference internal" href="../library/logging#logging.Logger.info" title="logging.Logger.info"><code>info()</code></a> etc.) only take positional parameters for the actual logging message itself, with keyword parameters used only for determining options for how to handle the logging call (e.g. the <code>exc_info</code> keyword parameter to indicate that traceback information should be logged, or the <code>extra</code> keyword parameter to indicate additional contextual information to be added to the log). So you cannot directly make logging calls using <a class="reference internal" href="../library/stdtypes#str.format" title="str.format"><code>str.format()</code></a> or <a class="reference internal" href="../library/string#string.Template" title="string.Template"><code>string.Template</code></a> syntax, because internally the logging package uses %-formatting to merge the format string and the variable arguments. There would be no changing this while preserving backward compatibility, since all logging calls which are out there in existing code will be using %-format strings.</p> <p>There have been suggestions to associate format styles with specific loggers, but that approach also runs into backward compatibility problems because any existing code could be using a given logger name and using %-formatting.</p> <p>For logging to work interoperably between any third-party libraries and your code, decisions about formatting need to be made at the level of the individual logging call. This opens up a couple of ways in which alternative formatting styles can be accommodated.</p> <section id="using-logrecord-factories"> <h3>Using LogRecord factories</h3> <p>In Python 3.2, along with the <a class="reference internal" href="../library/logging#logging.Formatter" title="logging.Formatter"><code>Formatter</code></a> changes mentioned above, the logging package gained the ability to allow users to set their own <a class="reference internal" href="../library/logging#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> subclasses, using the <a class="reference internal" href="../library/logging#logging.setLogRecordFactory" title="logging.setLogRecordFactory"><code>setLogRecordFactory()</code></a> function. You can use this to set your own subclass of <a class="reference internal" href="../library/logging#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a>, which does the Right Thing by overriding the <a class="reference internal" href="../library/logging#logging.LogRecord.getMessage" title="logging.LogRecord.getMessage"><code>getMessage()</code></a> method. The base class implementation of this method is where the <code>msg % args</code> formatting happens, and where you can substitute your alternate formatting; however, you should be careful to support all formatting styles and allow %-formatting as the default, to ensure interoperability with other code. Care should also be taken to call <code>str(self.msg)</code>, just as the base implementation does.</p> <p>Refer to the reference documentation on <a class="reference internal" href="../library/logging#logging.setLogRecordFactory" title="logging.setLogRecordFactory"><code>setLogRecordFactory()</code></a> and <a class="reference internal" href="../library/logging#logging.LogRecord" title="logging.LogRecord"><code>LogRecord</code></a> for more information.</p> </section> <section id="using-custom-message-objects"> <h3>Using custom message objects</h3> <p>There is another, perhaps simpler way that you can use {}- and $- formatting to construct your individual log messages. You may recall (from <a class="reference internal" href="logging#arbitrary-object-messages"><span class="std std-ref">Using arbitrary objects as messages</span></a>) that when logging you can use an arbitrary object as a message format string, and that the logging package will call <a class="reference internal" href="../library/stdtypes#str" title="str"><code>str()</code></a> on that object to get the actual format string. Consider the following two classes:</p> <pre data-language="python">class BraceMessage:
    def __init__(self, fmt, /, *args, **kwargs):
        self.fmt = fmt
        self.args = args
        self.kwargs = kwargs

    def __str__(self):
        return self.fmt.format(*self.args, **self.kwargs)

class DollarMessage:
    def __init__(self, fmt, /, **kwargs):
        self.fmt = fmt
        self.kwargs = kwargs

    def __str__(self):
        from string import Template
        return Template(self.fmt).substitute(**self.kwargs)
</pre> <p>Either of these can be used in place of a format string, to allow {}- or $-formatting to be used to build the actual “message” part which appears in the formatted log output in place of “%(message)s” or “{message}” or “$message”. If you find it a little unwieldy to use the class names whenever you want to log something, you can make it more palatable if you use an alias such as <code>M</code> or <code>_</code> for the message (or perhaps <code>__</code>, if you are using <code>_</code> for localization).</p> <p>Examples of this approach are given below. Firstly, formatting with <a class="reference internal" href="../library/stdtypes#str.format" title="str.format"><code>str.format()</code></a>:</p> <pre data-language="python">&gt;&gt;&gt; __ = BraceMessage
&gt;&gt;&gt; print(__('Message with {0} {1}', 2, 'placeholders'))
Message with 2 placeholders
&gt;&gt;&gt; class Point: pass
...
&gt;&gt;&gt; p = Point()
&gt;&gt;&gt; p.x = 0.5
&gt;&gt;&gt; p.y = 0.5
&gt;&gt;&gt; print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', point=p))
Message with coordinates: (0.50, 0.50)
</pre> <p>Secondly, formatting with <a class="reference internal" href="../library/string#string.Template" title="string.Template"><code>string.Template</code></a>:</p> <pre data-language="python">&gt;&gt;&gt; __ = DollarMessage
&gt;&gt;&gt; print(__('Message with $num $what', num=2, what='placeholders'))
Message with 2 placeholders
&gt;&gt;&gt;
</pre> <p>One thing to note is that you pay no significant performance penalty with this approach: the actual formatting happens not when you make the logging call, but when (and if) the logged message is actually about to be output to a log by a handler. So the only slightly unusual thing which might trip you up is that the parentheses go around the format string and the arguments, not just the format string. That’s because the __ notation is just syntax sugar for a constructor call to one of the <code><em>XXX</em>Message</code> classes shown above.</p> </section> </section> <section id="configuring-filters-with-dictconfig"> <span id="filters-dictconfig"></span><h2>Configuring filters with dictConfig()</h2> <p>You <em>can</em> configure filters using <a class="reference internal" href="../library/logging.config#logging.config.dictConfig" title="logging.config.dictConfig"><code>dictConfig()</code></a>, though it might not be obvious at first glance how to do it (hence this recipe). Since <a class="reference internal" href="../library/logging#logging.Filter" title="logging.Filter"><code>Filter</code></a> is the only filter class included in the standard library, and it is unlikely to cater to many requirements (it’s only there as a base class), you will typically need to define your own <a class="reference internal" href="../library/logging#logging.Filter" title="logging.Filter"><code>Filter</code></a> subclass with an overridden <a class="reference internal" href="../library/logging#logging.Filter.filter" title="logging.Filter.filter"><code>filter()</code></a> method. To do this, specify the <code>()</code> key in the configuration dictionary for the filter, specifying a callable which will be used to create the filter (a class is the most obvious, but you can provide any callable which returns a <a class="reference internal" href="../library/logging#logging.Filter" title="logging.Filter"><code>Filter</code></a> instance). Here is a complete example:</p> <pre data-language="python">import logging
import logging.config
import sys

class MyFilter(logging.Filter):
    def __init__(self, param=None):
        self.param = param

    def filter(self, record):
        if self.param is None:
            allow = True
        else:
            allow = self.param not in record.msg
        if allow:
            record.msg = 'changed: ' + record.msg
        return allow

LOGGING = {
    'version': 1,
    'filters': {
        'myfilter': {
            '()': MyFilter,
            'param': 'noshow',
        }
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'filters': ['myfilter']
        }
    },
    'root': {
        'level': 'DEBUG',
        'handlers': ['console']
    },
}

if __name__ == '__main__':
    logging.config.dictConfig(LOGGING)
    logging.debug('hello')
    logging.debug('hello - noshow')
</pre> <p>This example shows how you can pass configuration data to the callable which constructs the instance, in the form of keyword parameters. When run, the above script will print:</p> <pre data-language="none">changed: hello
</pre> <p>which shows that the filter is working as configured.</p> <p>A couple of extra points to note:</p> <ul class="simple"> <li>If you can’t refer to the callable directly in the configuration (e.g. if it lives in a different module, and you can’t import it directly where the configuration dictionary is), you can use the form <code>ext://...</code> as described in <a class="reference internal" href="../library/logging.config#logging-config-dict-externalobj"><span class="std std-ref">Access to external objects</span></a>. For example, you could have used the text <code>'ext://__main__.MyFilter'</code> instead of <code>MyFilter</code> in the above example.</li> <li>As well as for filters, this technique can also be used to configure custom handlers and formatters. See <a class="reference internal" href="../library/logging.config#logging-config-dict-userdef"><span class="std std-ref">User-defined objects</span></a> for more information on how logging supports using user-defined objects in its configuration, and see the other cookbook recipe <a class="reference internal" href="#custom-handlers"><span class="std std-ref">Customizing handlers with dictConfig()</span></a> above.</li> </ul> </section> <section id="customized-exception-formatting"> <span id="custom-format-exception"></span><h2>Customized exception formatting</h2> <p>There might be times when you want to do customized exception formatting - for argument’s sake, let’s say you want exactly one line per logged event, even when exception information is present. You can do this with a custom formatter class, as shown in the following example:</p> <pre data-language="python">import logging

class OneLineExceptionFormatter(logging.Formatter):
    def formatException(self, exc_info):
        """
        Format an exception so that it prints on a single line.
        """
        result = super().formatException(exc_info)
        return repr(result)  # or format into one line however you want to

    def format(self, record):
        s = super().format(record)
        if record.exc_text:
            s = s.replace('\n', '') + '|'
        return s

def configure_logging():
    fh = logging.FileHandler('output.txt', 'w')
    f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|',
                                  '%d/%m/%Y %H:%M:%S')
    fh.setFormatter(f)
    root = logging.getLogger()
    root.setLevel(logging.DEBUG)
    root.addHandler(fh)

def main():
    configure_logging()
    logging.info('Sample message')
    try:
        x = 1 / 0
    except ZeroDivisionError as e:
        logging.exception('ZeroDivisionError: %s', e)

if __name__ == '__main__':
    main()
</pre> <p>When run, this produces a file with exactly two lines:</p> <pre data-language="none">28/01/2015 07:21:23|INFO|Sample message|
28/01/2015 07:21:23|ERROR|ZeroDivisionError: integer division or modulo by zero|'Traceback (most recent call last):\n  File "logtest7.py", line 30, in main\n    x = 1 / 0\nZeroDivisionError: integer division or modulo by zero'|
</pre> <p>While the above treatment is simplistic, it points the way to how exception information can be formatted to your liking. The <a class="reference internal" href="../library/traceback#module-traceback" title="traceback: Print or retrieve a stack traceback."><code>traceback</code></a> module may be helpful for more specialized needs.</p> </section> <section id="speaking-logging-messages"> <span id="spoken-messages"></span><h2>Speaking logging messages</h2> <p>There might be situations when it is desirable to have logging messages rendered in an audible rather than a visible format. This is easy to do if you have text-to-speech (TTS) functionality available in your system, even if it doesn’t have a Python binding. Most TTS systems have a command line program you can run, and this can be invoked from a handler using <a class="reference internal" href="../library/subprocess#module-subprocess" title="subprocess: Subprocess management."><code>subprocess</code></a>. It’s assumed here that TTS command line programs won’t expect to interact with users or take a long time to complete, and that the frequency of logged messages will be not so high as to swamp the user with messages, and that it’s acceptable to have the messages spoken one at a time rather than concurrently, The example implementation below waits for one message to be spoken before the next is processed, and this might cause other handlers to be kept waiting. Here is a short example showing the approach, which assumes that the <code>espeak</code> TTS package is available:</p> <pre data-language="python">import logging
import subprocess
import sys

class TTSHandler(logging.Handler):
    def emit(self, record):
        msg = self.format(record)
        # Speak slowly in a female English voice
        cmd = ['espeak', '-s150', '-ven+f3', msg]
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        # wait for the program to finish
        p.communicate()

def configure_logging():
    h = TTSHandler()
    root = logging.getLogger()
    root.addHandler(h)
    # the default formatter just returns the message
    root.setLevel(logging.DEBUG)

def main():
    logging.info('Hello')
    logging.debug('Goodbye')

if __name__ == '__main__':
    configure_logging()
    sys.exit(main())
</pre> <p>When run, this script should say “Hello” and then “Goodbye” in a female voice.</p> <p>The above approach can, of course, be adapted to other TTS systems and even other systems altogether which can process messages via external programs run from a command line.</p> </section> <section id="buffering-logging-messages-and-outputting-them-conditionally"> <span id="buffered-logging"></span><h2>Buffering logging messages and outputting them conditionally</h2> <p>There might be situations where you want to log messages in a temporary area and only output them if a certain condition occurs. For example, you may want to start logging debug events in a function, and if the function completes without errors, you don’t want to clutter the log with the collected debug information, but if there is an error, you want all the debug information to be output as well as the error.</p> <p>Here is an example which shows how you could do this using a decorator for your functions where you want logging to behave this way. It makes use of the <a class="reference internal" href="../library/logging.handlers#logging.handlers.MemoryHandler" title="logging.handlers.MemoryHandler"><code>logging.handlers.MemoryHandler</code></a>, which allows buffering of logged events until some condition occurs, at which point the buffered events are <code>flushed</code> - passed to another handler (the <code>target</code> handler) for processing. By default, the <code>MemoryHandler</code> flushed when its buffer gets filled up or an event whose level is greater than or equal to a specified threshold is seen. You can use this recipe with a more specialised subclass of <code>MemoryHandler</code> if you want custom flushing behavior.</p> <p>The example script has a simple function, <code>foo</code>, which just cycles through all the logging levels, writing to <code>sys.stderr</code> to say what level it’s about to log at, and then actually logging a message at that level. You can pass a parameter to <code>foo</code> which, if true, will log at ERROR and CRITICAL levels - otherwise, it only logs at DEBUG, INFO and WARNING levels.</p> <p>The script just arranges to decorate <code>foo</code> with a decorator which will do the conditional logging that’s required. The decorator takes a logger as a parameter and attaches a memory handler for the duration of the call to the decorated function. The decorator can be additionally parameterised using a target handler, a level at which flushing should occur, and a capacity for the buffer (number of records buffered). These default to a <a class="reference internal" href="../library/logging.handlers#logging.StreamHandler" title="logging.StreamHandler"><code>StreamHandler</code></a> which writes to <code>sys.stderr</code>, <code>logging.ERROR</code> and <code>100</code> respectively.</p> <p>Here’s the script:</p> <pre data-language="python">import logging
from logging.handlers import MemoryHandler
import sys

logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())

def log_if_errors(logger, target_handler=None, flush_level=None, capacity=None):
    if target_handler is None:
        target_handler = logging.StreamHandler()
    if flush_level is None:
        flush_level = logging.ERROR
    if capacity is None:
        capacity = 100
    handler = MemoryHandler(capacity, flushLevel=flush_level, target=target_handler)

    def decorator(fn):
        def wrapper(*args, **kwargs):
            logger.addHandler(handler)
            try:
                return fn(*args, **kwargs)
            except Exception:
                logger.exception('call failed')
                raise
            finally:
                super(MemoryHandler, handler).flush()
                logger.removeHandler(handler)
        return wrapper

    return decorator

def write_line(s):
    sys.stderr.write('%s\n' % s)

def foo(fail=False):
    write_line('about to log at DEBUG ...')
    logger.debug('Actually logged at DEBUG')
    write_line('about to log at INFO ...')
    logger.info('Actually logged at INFO')
    write_line('about to log at WARNING ...')
    logger.warning('Actually logged at WARNING')
    if fail:
        write_line('about to log at ERROR ...')
        logger.error('Actually logged at ERROR')
        write_line('about to log at CRITICAL ...')
        logger.critical('Actually logged at CRITICAL')
    return fail

decorated_foo = log_if_errors(logger)(foo)

if __name__ == '__main__':
    logger.setLevel(logging.DEBUG)
    write_line('Calling undecorated foo with False')
    assert not foo(False)
    write_line('Calling undecorated foo with True')
    assert foo(True)
    write_line('Calling decorated foo with False')
    assert not decorated_foo(False)
    write_line('Calling decorated foo with True')
    assert decorated_foo(True)
</pre> <p>When this script is run, the following output should be observed:</p> <pre data-language="none">Calling undecorated foo with False
about to log at DEBUG ...
about to log at INFO ...
about to log at WARNING ...
Calling undecorated foo with True
about to log at DEBUG ...
about to log at INFO ...
about to log at WARNING ...
about to log at ERROR ...
about to log at CRITICAL ...
Calling decorated foo with False
about to log at DEBUG ...
about to log at INFO ...
about to log at WARNING ...
Calling decorated foo with True
about to log at DEBUG ...
about to log at INFO ...
about to log at WARNING ...
about to log at ERROR ...
Actually logged at DEBUG
Actually logged at INFO
Actually logged at WARNING
Actually logged at ERROR
about to log at CRITICAL ...
Actually logged at CRITICAL
</pre> <p>As you can see, actual logging output only occurs when an event is logged whose severity is ERROR or greater, but in that case, any previous events at lower severities are also logged.</p> <p>You can of course use the conventional means of decoration:</p> <pre data-language="python">@log_if_errors(logger)
def foo(fail=False):
    ...
</pre> </section> <section id="sending-logging-messages-to-email-with-buffering"> <span id="buffered-smtp"></span><h2>Sending logging messages to email, with buffering</h2> <p>To illustrate how you can send log messages via email, so that a set number of messages are sent per email, you can subclass <a class="reference internal" href="../library/logging.handlers#logging.handlers.BufferingHandler" title="logging.handlers.BufferingHandler"><code>BufferingHandler</code></a>. In the following example, which you can adapt to suit your specific needs, a simple test harness is provided which allows you to run the script with command line arguments specifying what you typically need to send things via SMTP. (Run the downloaded script with the <code>-h</code> argument to see the required and optional arguments.)</p> <pre data-language="python">import logging
import logging.handlers
import smtplib

class BufferingSMTPHandler(logging.handlers.BufferingHandler):
    def __init__(self, mailhost, port, username, password, fromaddr, toaddrs,
                 subject, capacity):
        logging.handlers.BufferingHandler.__init__(self, capacity)
        self.mailhost = mailhost
        self.mailport = port
        self.username = username
        self.password = password
        self.fromaddr = fromaddr
        if isinstance(toaddrs, str):
            toaddrs = [toaddrs]
        self.toaddrs = toaddrs
        self.subject = subject
        self.setFormatter(logging.Formatter("%(asctime)s %(levelname)-5s %(message)s"))

    def flush(self):
        if len(self.buffer) &gt; 0:
            try:
                smtp = smtplib.SMTP(self.mailhost, self.mailport)
                smtp.starttls()
                smtp.login(self.username, self.password)
                msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (self.fromaddr, ','.join(self.toaddrs), self.subject)
                for record in self.buffer:
                    s = self.format(record)
                    msg = msg + s + "\r\n"
                smtp.sendmail(self.fromaddr, self.toaddrs, msg)
                smtp.quit()
            except Exception:
                if logging.raiseExceptions:
                    raise
            self.buffer = []

if __name__ == '__main__':
    import argparse

    ap = argparse.ArgumentParser()
    aa = ap.add_argument
    aa('host', metavar='HOST', help='SMTP server')
    aa('--port', '-p', type=int, default=587, help='SMTP port')
    aa('user', metavar='USER', help='SMTP username')
    aa('password', metavar='PASSWORD', help='SMTP password')
    aa('to', metavar='TO', help='Addressee for emails')
    aa('sender', metavar='SENDER', help='Sender email address')
    aa('--subject', '-s',
       default='Test Logging email from Python logging module (buffering)',
       help='Subject of email')
    options = ap.parse_args()
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    h = BufferingSMTPHandler(options.host, options.port, options.user,
                             options.password, options.sender,
                             options.to, options.subject, 10)
    logger.addHandler(h)
    for i in range(102):
        logger.info("Info index = %d", i)
    h.flush()
    h.close()
</pre> <p>If you run this script and your SMTP server is correctly set up, you should find that it sends eleven emails to the addressee you specify. The first ten emails will each have ten log messages, and the eleventh will have two messages. That makes up 102 messages as specified in the script.</p> </section> <section id="formatting-times-using-utc-gmt-via-configuration"> <span id="utc-formatting"></span><h2>Formatting times using UTC (GMT) via configuration</h2> <p>Sometimes you want to format times using UTC, which can be done using a class such as <code>UTCFormatter</code>, shown below:</p> <pre data-language="python">import logging
import time

class UTCFormatter(logging.Formatter):
    converter = time.gmtime
</pre> <p>and you can then use the <code>UTCFormatter</code> in your code instead of <a class="reference internal" href="../library/logging#logging.Formatter" title="logging.Formatter"><code>Formatter</code></a>. If you want to do that via configuration, you can use the <a class="reference internal" href="../library/logging.config#logging.config.dictConfig" title="logging.config.dictConfig"><code>dictConfig()</code></a> API with an approach illustrated by the following complete example:</p> <pre data-language="python">import logging
import logging.config
import time

class UTCFormatter(logging.Formatter):
    converter = time.gmtime

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'utc': {
            '()': UTCFormatter,
            'format': '%(asctime)s %(message)s',
        },
        'local': {
            'format': '%(asctime)s %(message)s',
        }
    },
    'handlers': {
        'console1': {
            'class': 'logging.StreamHandler',
            'formatter': 'utc',
        },
        'console2': {
            'class': 'logging.StreamHandler',
            'formatter': 'local',
        },
    },
    'root': {
        'handlers': ['console1', 'console2'],
   }
}

if __name__ == '__main__':
    logging.config.dictConfig(LOGGING)
    logging.warning('The local time is %s', time.asctime())
</pre> <p>When this script is run, it should print something like:</p> <pre data-language="none">2015-10-17 12:53:29,501 The local time is Sat Oct 17 13:53:29 2015
2015-10-17 13:53:29,501 The local time is Sat Oct 17 13:53:29 2015
</pre> <p>showing how the time is formatted both as local time and UTC, one for each handler.</p> </section> <section id="using-a-context-manager-for-selective-logging"> <span id="context-manager"></span><h2>Using a context manager for selective logging</h2> <p>There are times when it would be useful to temporarily change the logging configuration and revert it back after doing something. For this, a context manager is the most obvious way of saving and restoring the logging context. Here is a simple example of such a context manager, which allows you to optionally change the logging level and add a logging handler purely in the scope of the context manager:</p> <pre data-language="python">import logging
import sys

class LoggingContext:
    def __init__(self, logger, level=None, handler=None, close=True):
        self.logger = logger
        self.level = level
        self.handler = handler
        self.close = close

    def __enter__(self):
        if self.level is not None:
            self.old_level = self.logger.level
            self.logger.setLevel(self.level)
        if self.handler:
            self.logger.addHandler(self.handler)

    def __exit__(self, et, ev, tb):
        if self.level is not None:
            self.logger.setLevel(self.old_level)
        if self.handler:
            self.logger.removeHandler(self.handler)
        if self.handler and self.close:
            self.handler.close()
        # implicit return of None =&gt; don't swallow exceptions
</pre> <p>If you specify a level value, the logger’s level is set to that value in the scope of the with block covered by the context manager. If you specify a handler, it is added to the logger on entry to the block and removed on exit from the block. You can also ask the manager to close the handler for you on block exit - you could do this if you don’t need the handler any more.</p> <p>To illustrate how it works, we can add the following block of code to the above:</p> <pre data-language="python">if __name__ == '__main__':
    logger = logging.getLogger('foo')
    logger.addHandler(logging.StreamHandler())
    logger.setLevel(logging.INFO)
    logger.info('1. This should appear just once on stderr.')
    logger.debug('2. This should not appear.')
    with LoggingContext(logger, level=logging.DEBUG):
        logger.debug('3. This should appear once on stderr.')
    logger.debug('4. This should not appear.')
    h = logging.StreamHandler(sys.stdout)
    with LoggingContext(logger, level=logging.DEBUG, handler=h, close=True):
        logger.debug('5. This should appear twice - once on stderr and once on stdout.')
    logger.info('6. This should appear just once on stderr.')
    logger.debug('7. This should not appear.')
</pre> <p>We initially set the logger’s level to <code>INFO</code>, so message #1 appears and message #2 doesn’t. We then change the level to <code>DEBUG</code> temporarily in the following <code>with</code> block, and so message #3 appears. After the block exits, the logger’s level is restored to <code>INFO</code> and so message #4 doesn’t appear. In the next <code>with</code> block, we set the level to <code>DEBUG</code> again but also add a handler writing to <code>sys.stdout</code>. Thus, message #5 appears twice on the console (once via <code>stderr</code> and once via <code>stdout</code>). After the <code>with</code> statement’s completion, the status is as it was before so message #6 appears (like message #1) whereas message #7 doesn’t (just like message #2).</p> <p>If we run the resulting script, the result is as follows:</p> <pre data-language="shell">$ python logctx.py
1. This should appear just once on stderr.
3. This should appear once on stderr.
5. This should appear twice - once on stderr and once on stdout.
5. This should appear twice - once on stderr and once on stdout.
6. This should appear just once on stderr.
</pre> <p>If we run it again, but pipe <code>stderr</code> to <code>/dev/null</code>, we see the following, which is the only message written to <code>stdout</code>:</p> <pre data-language="shell">$ python logctx.py 2&gt;/dev/null
5. This should appear twice - once on stderr and once on stdout.
</pre> <p>Once again, but piping <code>stdout</code> to <code>/dev/null</code>, we get:</p> <pre data-language="shell">$ python logctx.py &gt;/dev/null
1. This should appear just once on stderr.
3. This should appear once on stderr.
5. This should appear twice - once on stderr and once on stdout.
6. This should appear just once on stderr.
</pre> <p>In this case, the message #5 printed to <code>stdout</code> doesn’t appear, as expected.</p> <p>Of course, the approach described here can be generalised, for example to attach logging filters temporarily. Note that the above code works in Python 2 as well as Python 3.</p> </section> <section id="a-cli-application-starter-template"> <span id="starter-template"></span><h2>A CLI application starter template</h2> <p>Here’s an example which shows how you can:</p> <ul class="simple"> <li>Use a logging level based on command-line arguments</li> <li>Dispatch to multiple subcommands in separate files, all logging at the same level in a consistent way</li> <li>Make use of simple, minimal configuration</li> </ul> <p>Suppose we have a command-line application whose job is to stop, start or restart some services. This could be organised for the purposes of illustration as a file <code>app.py</code> that is the main script for the application, with individual commands implemented in <code>start.py</code>, <code>stop.py</code> and <code>restart.py</code>. Suppose further that we want to control the verbosity of the application via a command-line argument, defaulting to <code>logging.INFO</code>. Here’s one way that <code>app.py</code> could be written:</p> <pre data-language="python">import argparse
import importlib
import logging
import os
import sys

def main(args=None):
    scriptname = os.path.basename(__file__)
    parser = argparse.ArgumentParser(scriptname)
    levels = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')
    parser.add_argument('--log-level', default='INFO', choices=levels)
    subparsers = parser.add_subparsers(dest='command',
                                       help='Available commands:')
    start_cmd = subparsers.add_parser('start', help='Start a service')
    start_cmd.add_argument('name', metavar='NAME',
                           help='Name of service to start')
    stop_cmd = subparsers.add_parser('stop',
                                     help='Stop one or more services')
    stop_cmd.add_argument('names', metavar='NAME', nargs='+',
                          help='Name of service to stop')
    restart_cmd = subparsers.add_parser('restart',
                                        help='Restart one or more services')
    restart_cmd.add_argument('names', metavar='NAME', nargs='+',
                             help='Name of service to restart')
    options = parser.parse_args()
    # the code to dispatch commands could all be in this file. For the purposes
    # of illustration only, we implement each command in a separate module.
    try:
        mod = importlib.import_module(options.command)
        cmd = getattr(mod, 'command')
    except (ImportError, AttributeError):
        print('Unable to find the code for command \'%s\'' % options.command)
        return 1
    # Could get fancy here and load configuration from file or dictionary
    logging.basicConfig(level=options.log_level,
                        format='%(levelname)s %(name)s %(message)s')
    cmd(options)

if __name__ == '__main__':
    sys.exit(main())
</pre> <p>And the <code>start</code>, <code>stop</code> and <code>restart</code> commands can be implemented in separate modules, like so for starting:</p> <pre data-language="python"># start.py
import logging

logger = logging.getLogger(__name__)

def command(options):
    logger.debug('About to start %s', options.name)
    # actually do the command processing here ...
    logger.info('Started the \'%s\' service.', options.name)
</pre> <p>and thus for stopping:</p> <pre data-language="python"># stop.py
import logging

logger = logging.getLogger(__name__)

def command(options):
    n = len(options.names)
    if n == 1:
        plural = ''
        services = '\'%s\'' % options.names[0]
    else:
        plural = 's'
        services = ', '.join('\'%s\'' % name for name in options.names)
        i = services.rfind(', ')
        services = services[:i] + ' and ' + services[i + 2:]
    logger.debug('About to stop %s', services)
    # actually do the command processing here ...
    logger.info('Stopped the %s service%s.', services, plural)
</pre> <p>and similarly for restarting:</p> <pre data-language="python"># restart.py
import logging

logger = logging.getLogger(__name__)

def command(options):
    n = len(options.names)
    if n == 1:
        plural = ''
        services = '\'%s\'' % options.names[0]
    else:
        plural = 's'
        services = ', '.join('\'%s\'' % name for name in options.names)
        i = services.rfind(', ')
        services = services[:i] + ' and ' + services[i + 2:]
    logger.debug('About to restart %s', services)
    # actually do the command processing here ...
    logger.info('Restarted the %s service%s.', services, plural)
</pre> <p>If we run this application with the default log level, we get output like this:</p> <pre data-language="shell">$ python app.py start foo
INFO start Started the 'foo' service.

$ python app.py stop foo bar
INFO stop Stopped the 'foo' and 'bar' services.

$ python app.py restart foo bar baz
INFO restart Restarted the 'foo', 'bar' and 'baz' services.
</pre> <p>The first word is the logging level, and the second word is the module or package name of the place where the event was logged.</p> <p>If we change the logging level, then we can change the information sent to the log. For example, if we want more information:</p> <pre data-language="shell">$ python app.py --log-level DEBUG start foo
DEBUG start About to start foo
INFO start Started the 'foo' service.

$ python app.py --log-level DEBUG stop foo bar
DEBUG stop About to stop 'foo' and 'bar'
INFO stop Stopped the 'foo' and 'bar' services.

$ python app.py --log-level DEBUG restart foo bar baz
DEBUG restart About to restart 'foo', 'bar' and 'baz'
INFO restart Restarted the 'foo', 'bar' and 'baz' services.
</pre> <p>And if we want less:</p> <pre data-language="shell">$ python app.py --log-level WARNING start foo
$ python app.py --log-level WARNING stop foo bar
$ python app.py --log-level WARNING restart foo bar baz
</pre> <p>In this case, the commands don’t print anything to the console, since nothing at <code>WARNING</code> level or above is logged by them.</p> </section> <section id="a-qt-gui-for-logging"> <span id="qt-gui"></span><h2>A Qt GUI for logging</h2> <p>A question that comes up from time to time is about how to log to a GUI application. The <a class="reference external" href="https://www.qt.io/">Qt</a> framework is a popular cross-platform UI framework with Python bindings using <a class="reference external" href="https://pypi.org/project/PySide2/">PySide2</a> or <a class="reference external" href="https://pypi.org/project/PyQt5/">PyQt5</a> libraries.</p> <p>The following example shows how to log to a Qt GUI. This introduces a simple <code>QtHandler</code> class which takes a callable, which should be a slot in the main thread that does GUI updates. A worker thread is also created to show how you can log to the GUI from both the UI itself (via a button for manual logging) as well as a worker thread doing work in the background (here, just logging messages at random levels with random short delays in between).</p> <p>The worker thread is implemented using Qt’s <code>QThread</code> class rather than the <a class="reference internal" href="../library/threading#module-threading" title="threading: Thread-based parallelism."><code>threading</code></a> module, as there are circumstances where one has to use <code>QThread</code>, which offers better integration with other <code>Qt</code> components.</p> <p>The code should work with recent releases of either <code>PySide2</code> or <code>PyQt5</code>. You should be able to adapt the approach to earlier versions of Qt. Please refer to the comments in the code snippet for more detailed information.</p> <pre data-language="python">import datetime
import logging
import random
import sys
import time

# Deal with minor differences between PySide2 and PyQt5
try:
    from PySide2 import QtCore, QtGui, QtWidgets
    Signal = QtCore.Signal
    Slot = QtCore.Slot
except ImportError:
    from PyQt5 import QtCore, QtGui, QtWidgets
    Signal = QtCore.pyqtSignal
    Slot = QtCore.pyqtSlot


logger = logging.getLogger(__name__)


#
# Signals need to be contained in a QObject or subclass in order to be correctly
# initialized.
#
class Signaller(QtCore.QObject):
    signal = Signal(str, logging.LogRecord)

#
# Output to a Qt GUI is only supposed to happen on the main thread. So, this
# handler is designed to take a slot function which is set up to run in the main
# thread. In this example, the function takes a string argument which is a
# formatted log message, and the log record which generated it. The formatted
# string is just a convenience - you could format a string for output any way
# you like in the slot function itself.
#
# You specify the slot function to do whatever GUI updates you want. The handler
# doesn't know or care about specific UI elements.
#
class QtHandler(logging.Handler):
    def __init__(self, slotfunc, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.signaller = Signaller()
        self.signaller.signal.connect(slotfunc)

    def emit(self, record):
        s = self.format(record)
        self.signaller.signal.emit(s, record)

#
# This example uses QThreads, which means that the threads at the Python level
# are named something like "Dummy-1". The function below gets the Qt name of the
# current thread.
#
def ctname():
    return QtCore.QThread.currentThread().objectName()


#
# Used to generate random levels for logging.
#
LEVELS = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
          logging.CRITICAL)

#
# This worker class represents work that is done in a thread separate to the
# main thread. The way the thread is kicked off to do work is via a button press
# that connects to a slot in the worker.
#
# Because the default threadName value in the LogRecord isn't much use, we add
# a qThreadName which contains the QThread name as computed above, and pass that
# value in an "extra" dictionary which is used to update the LogRecord with the
# QThread name.
#
# This example worker just outputs messages sequentially, interspersed with
# random delays of the order of a few seconds.
#
class Worker(QtCore.QObject):
    @Slot()
    def start(self):
        extra = {'qThreadName': ctname() }
        logger.debug('Started work', extra=extra)
        i = 1
        # Let the thread run until interrupted. This allows reasonably clean
        # thread termination.
        while not QtCore.QThread.currentThread().isInterruptionRequested():
            delay = 0.5 + random.random() * 2
            time.sleep(delay)
            level = random.choice(LEVELS)
            logger.log(level, 'Message after delay of %3.1f: %d', delay, i, extra=extra)
            i += 1

#
# Implement a simple UI for this cookbook example. This contains:
#
# * A read-only text edit window which holds formatted log messages
# * A button to start work and log stuff in a separate thread
# * A button to log something from the main thread
# * A button to clear the log window
#
class Window(QtWidgets.QWidget):

    COLORS = {
        logging.DEBUG: 'black',
        logging.INFO: 'blue',
        logging.WARNING: 'orange',
        logging.ERROR: 'red',
        logging.CRITICAL: 'purple',
    }

    def __init__(self, app):
        super().__init__()
        self.app = app
        self.textedit = te = QtWidgets.QPlainTextEdit(self)
        # Set whatever the default monospace font is for the platform
        f = QtGui.QFont('nosuchfont')
        f.setStyleHint(f.Monospace)
        te.setFont(f)
        te.setReadOnly(True)
        PB = QtWidgets.QPushButton
        self.work_button = PB('Start background work', self)
        self.log_button = PB('Log a message at a random level', self)
        self.clear_button = PB('Clear log window', self)
        self.handler = h = QtHandler(self.update_status)
        # Remember to use qThreadName rather than threadName in the format string.
        fs = '%(asctime)s %(qThreadName)-12s %(levelname)-8s %(message)s'
        formatter = logging.Formatter(fs)
        h.setFormatter(formatter)
        logger.addHandler(h)
        # Set up to terminate the QThread when we exit
        app.aboutToQuit.connect(self.force_quit)

        # Lay out all the widgets
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(te)
        layout.addWidget(self.work_button)
        layout.addWidget(self.log_button)
        layout.addWidget(self.clear_button)
        self.setFixedSize(900, 400)

        # Connect the non-worker slots and signals
        self.log_button.clicked.connect(self.manual_update)
        self.clear_button.clicked.connect(self.clear_display)

        # Start a new worker thread and connect the slots for the worker
        self.start_thread()
        self.work_button.clicked.connect(self.worker.start)
        # Once started, the button should be disabled
        self.work_button.clicked.connect(lambda : self.work_button.setEnabled(False))

    def start_thread(self):
        self.worker = Worker()
        self.worker_thread = QtCore.QThread()
        self.worker.setObjectName('Worker')
        self.worker_thread.setObjectName('WorkerThread')  # for qThreadName
        self.worker.moveToThread(self.worker_thread)
        # This will start an event loop in the worker thread
        self.worker_thread.start()

    def kill_thread(self):
        # Just tell the worker to stop, then tell it to quit and wait for that
        # to happen
        self.worker_thread.requestInterruption()
        if self.worker_thread.isRunning():
            self.worker_thread.quit()
            self.worker_thread.wait()
        else:
            print('worker has already exited.')

    def force_quit(self):
        # For use when the window is closed
        if self.worker_thread.isRunning():
            self.kill_thread()

    # The functions below update the UI and run in the main thread because
    # that's where the slots are set up

    @Slot(str, logging.LogRecord)
    def update_status(self, status, record):
        color = self.COLORS.get(record.levelno, 'black')
        s = '&lt;pre&gt;&lt;font color="%s"&gt;%s&lt;/font&gt;&lt;/pre&gt;' % (color, status)
        self.textedit.appendHtml(s)

    @Slot()
    def manual_update(self):
        # This function uses the formatted message passed in, but also uses
        # information from the record to format the message in an appropriate
        # color according to its severity (level).
        level = random.choice(LEVELS)
        extra = {'qThreadName': ctname() }
        logger.log(level, 'Manually logged!', extra=extra)

    @Slot()
    def clear_display(self):
        self.textedit.clear()


def main():
    QtCore.QThread.currentThread().setObjectName('MainThread')
    logging.getLogger().setLevel(logging.DEBUG)
    app = QtWidgets.QApplication(sys.argv)
    example = Window(app)
    example.show()
    sys.exit(app.exec_())

if __name__=='__main__':
    main()
</pre> </section> <section id="logging-to-syslog-with-rfc5424-support"> <h2>Logging to syslog with RFC5424 support</h2> <p>Although <span class="target" id="index-4"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc5424.html"><strong>RFC 5424</strong></a> dates from 2009, most syslog servers are configured by default to use the older <span class="target" id="index-5"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc3164.html"><strong>RFC 3164</strong></a>, which hails from 2001. When <code>logging</code> was added to Python in 2003, it supported the earlier (and only existing) protocol at the time. Since RFC5424 came out, as there has not been widespread deployment of it in syslog servers, the <a class="reference internal" href="../library/logging.handlers#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><code>SysLogHandler</code></a> functionality has not been updated.</p> <p>RFC 5424 contains some useful features such as support for structured data, and if you need to be able to log to a syslog server with support for it, you can do so with a subclassed handler which looks something like this:</p> <pre data-language="python">import datetime
import logging.handlers
import re
import socket
import time

class SysLogHandler5424(logging.handlers.SysLogHandler):

    tz_offset = re.compile(r'([+-]\d{2})(\d{2})$')
    escaped = re.compile(r'([\]"\\])')

    def __init__(self, *args, **kwargs):
        self.msgid = kwargs.pop('msgid', None)
        self.appname = kwargs.pop('appname', None)
        super().__init__(*args, **kwargs)

    def format(self, record):
        version = 1
        asctime = datetime.datetime.fromtimestamp(record.created).isoformat()
        m = self.tz_offset.match(time.strftime('%z'))
        has_offset = False
        if m and time.timezone:
            hrs, mins = m.groups()
            if int(hrs) or int(mins):
                has_offset = True
        if not has_offset:
            asctime += 'Z'
        else:
            asctime += f'{hrs}:{mins}'
        try:
            hostname = socket.gethostname()
        except Exception:
            hostname = '-'
        appname = self.appname or '-'
        procid = record.process
        msgid = '-'
        msg = super().format(record)
        sdata = '-'
        if hasattr(record, 'structured_data'):
            sd = record.structured_data
            # This should be a dict where the keys are SD-ID and the value is a
            # dict mapping PARAM-NAME to PARAM-VALUE (refer to the RFC for what these
            # mean)
            # There's no error checking here - it's purely for illustration, and you
            # can adapt this code for use in production environments
            parts = []

            def replacer(m):
                g = m.groups()
                return '\\' + g[0]

            for sdid, dv in sd.items():
                part = f'[{sdid}'
                for k, v in dv.items():
                    s = str(v)
                    s = self.escaped.sub(replacer, s)
                    part += f' {k}="{s}"'
                part += ']'
                parts.append(part)
            sdata = ''.join(parts)
        return f'{version} {asctime} {hostname} {appname} {procid} {msgid} {sdata} {msg}'
</pre> <p>You’ll need to be familiar with RFC 5424 to fully understand the above code, and it may be that you have slightly different needs (e.g. for how you pass structural data to the log). Nevertheless, the above should be adaptable to your speciric needs. With the above handler, you’d pass structured data using something like this:</p> <pre data-language="python">sd = {
    'foo@12345': {'bar': 'baz', 'baz': 'bozz', 'fizz': r'buzz'},
    'foo@54321': {'rab': 'baz', 'zab': 'bozz', 'zzif': r'buzz'}
}
extra = {'structured_data': sd}
i = 1
logger.debug('Message %d', i, extra=extra)
</pre> </section> <section id="how-to-treat-a-logger-like-an-output-stream"> <h2>How to treat a logger like an output stream</h2> <p>Sometimes, you need to interface to a third-party API which expects a file-like object to write to, but you want to direct the API’s output to a logger. You can do this using a class which wraps a logger with a file-like API. Here’s a short script illustrating such a class:</p> <pre data-language="python">import logging

class LoggerWriter:
    def __init__(self, logger, level):
        self.logger = logger
        self.level = level

    def write(self, message):
        if message != '\n':  # avoid printing bare newlines, if you like
            self.logger.log(self.level, message)

    def flush(self):
        # doesn't actually do anything, but might be expected of a file-like
        # object - so optional depending on your situation
        pass

    def close(self):
        # doesn't actually do anything, but might be expected of a file-like
        # object - so optional depending on your situation. You might want
        # to set a flag so that later calls to write raise an exception
        pass

def main():
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger('demo')
    info_fp = LoggerWriter(logger, logging.INFO)
    debug_fp = LoggerWriter(logger, logging.DEBUG)
    print('An INFO message', file=info_fp)
    print('A DEBUG message', file=debug_fp)

if __name__ == "__main__":
    main()
</pre> <p>When this script is run, it prints</p> <pre data-language="text">INFO:demo:An INFO message
DEBUG:demo:A DEBUG message
</pre> <p>You could also use <code>LoggerWriter</code> to redirect <code>sys.stdout</code> and <code>sys.stderr</code> by doing something like this:</p> <pre data-language="python">import sys

sys.stdout = LoggerWriter(logger, logging.INFO)
sys.stderr = LoggerWriter(logger, logging.WARNING)
</pre> <p>You should do this <em>after</em> configuring logging for your needs. In the above example, the <a class="reference internal" href="../library/logging#logging.basicConfig" title="logging.basicConfig"><code>basicConfig()</code></a> call does this (using the <code>sys.stderr</code> value <em>before</em> it is overwritten by a <code>LoggerWriter</code> instance). Then, you’d get this kind of result:</p> <pre data-language="pycon">&gt;&gt;&gt; print('Foo')
INFO:demo:Foo
&gt;&gt;&gt; print('Bar', file=sys.stderr)
WARNING:demo:Bar
&gt;&gt;&gt;
</pre> <p>Of course, the examples above show output according to the format used by <a class="reference internal" href="../library/logging#logging.basicConfig" title="logging.basicConfig"><code>basicConfig()</code></a>, but you can use a different formatter when you configure logging.</p> <p>Note that with the above scheme, you are somewhat at the mercy of buffering and the sequence of write calls which you are intercepting. For example, with the definition of <code>LoggerWriter</code> above, if you have the snippet</p> <pre data-language="python">sys.stderr = LoggerWriter(logger, logging.WARNING)
1 / 0
</pre> <p>then running the script results in</p> <pre data-language="text">WARNING:demo:Traceback (most recent call last):

WARNING:demo:  File "/home/runner/cookbook-loggerwriter/test.py", line 53, in &lt;module&gt;

WARNING:demo:
WARNING:demo:main()
WARNING:demo:  File "/home/runner/cookbook-loggerwriter/test.py", line 49, in main

WARNING:demo:
WARNING:demo:1 / 0
WARNING:demo:ZeroDivisionError
WARNING:demo::
WARNING:demo:division by zero
</pre> <p>As you can see, this output isn’t ideal. That’s because the underlying code which writes to <code>sys.stderr</code> makes multiple writes, each of which results in a separate logged line (for example, the last three lines above). To get around this problem, you need to buffer things and only output log lines when newlines are seen. Let’s use a slghtly better implementation of <code>LoggerWriter</code>:</p> <pre data-language="python">class BufferingLoggerWriter(LoggerWriter):
    def __init__(self, logger, level):
        super().__init__(logger, level)
        self.buffer = ''

    def write(self, message):
        if '\n' not in message:
            self.buffer += message
        else:
            parts = message.split('\n')
            if self.buffer:
                s = self.buffer + parts.pop(0)
                self.logger.log(self.level, s)
            self.buffer = parts.pop()
            for part in parts:
                self.logger.log(self.level, part)
</pre> <p>This just buffers up stuff until a newline is seen, and then logs complete lines. With this approach, you get better output:</p> <pre data-language="text">WARNING:demo:Traceback (most recent call last):
WARNING:demo:  File "/home/runner/cookbook-loggerwriter/main.py", line 55, in &lt;module&gt;
WARNING:demo:    main()
WARNING:demo:  File "/home/runner/cookbook-loggerwriter/main.py", line 52, in main
WARNING:demo:    1/0
WARNING:demo:ZeroDivisionError: division by zero
</pre> </section> <section id="patterns-to-avoid"> <h2>Patterns to avoid</h2> <p>Although the preceding sections have described ways of doing things you might need to do or deal with, it is worth mentioning some usage patterns which are <em>unhelpful</em>, and which should therefore be avoided in most cases. The following sections are in no particular order.</p> <section id="opening-the-same-log-file-multiple-times"> <h3>Opening the same log file multiple times</h3> <p>On Windows, you will generally not be able to open the same file multiple times as this will lead to a “file is in use by another process” error. However, on POSIX platforms you’ll not get any errors if you open the same file multiple times. This could be done accidentally, for example by:</p> <ul class="simple"> <li>Adding a file handler more than once which references the same file (e.g. by a copy/paste/forget-to-change error).</li> <li>Opening two files that look different, as they have different names, but are the same because one is a symbolic link to the other.</li> <li>Forking a process, following which both parent and child have a reference to the same file. This might be through use of the <a class="reference internal" href="../library/multiprocessing#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code>multiprocessing</code></a> module, for example.</li> </ul> <p>Opening a file multiple times might <em>appear</em> to work most of the time, but can lead to a number of problems in practice:</p> <ul class="simple"> <li>Logging output can be garbled because multiple threads or processes try to write to the same file. Although logging guards against concurrent use of the same handler instance by multiple threads, there is no such protection if concurrent writes are attempted by two different threads using two different handler instances which happen to point to the same file.</li> <li>An attempt to delete a file (e.g. during file rotation) silently fails, because there is another reference pointing to it. This can lead to confusion and wasted debugging time - log entries end up in unexpected places, or are lost altogether. Or a file that was supposed to be moved remains in place, and grows in size unexpectedly despite size-based rotation being supposedly in place.</li> </ul> <p>Use the techniques outlined in <a class="reference internal" href="#multiple-processes"><span class="std std-ref">Logging to a single file from multiple processes</span></a> to circumvent such issues.</p> </section> <section id="using-loggers-as-attributes-in-a-class-or-passing-them-as-parameters"> <h3>Using loggers as attributes in a class or passing them as parameters</h3> <p>While there might be unusual cases where you’ll need to do this, in general there is no point because loggers are singletons. Code can always access a given logger instance by name using <code>logging.getLogger(name)</code>, so passing instances around and holding them as instance attributes is pointless. Note that in other languages such as Java and C#, loggers are often static class attributes. However, this pattern doesn’t make sense in Python, where the module (and not the class) is the unit of software decomposition.</p> </section> <section id="adding-handlers-other-than-nullhandler-to-a-logger-in-a-library"> <h3>Adding handlers other than <a class="reference internal" href="../library/logging.handlers#logging.NullHandler" title="logging.NullHandler"><code>NullHandler</code></a> to a logger in a library</h3> <p>Configuring logging by adding handlers, formatters and filters is the responsibility of the application developer, not the library developer. If you are maintaining a library, ensure that you don’t add handlers to any of your loggers other than a <a class="reference internal" href="../library/logging.handlers#logging.NullHandler" title="logging.NullHandler"><code>NullHandler</code></a> instance.</p> </section> <section id="creating-a-lot-of-loggers"> <h3>Creating a lot of loggers</h3> <p>Loggers are singletons that are never freed during a script execution, and so creating lots of loggers will use up memory which can’t then be freed. Rather than create a logger per e.g. file processed or network connection made, use the <a class="reference internal" href="#context-info"><span class="std std-ref">existing mechanisms</span></a> for passing contextual information into your logs and restrict the loggers created to those describing areas within your application (generally modules, but occasionally slightly more fine-grained than that).</p> </section> </section> <section id="other-resources"> <span id="cookbook-ref-links"></span><h2>Other resources</h2> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt>
<code>Module</code> <a class="reference internal" href="../library/logging#module-logging" title="logging: Flexible event logging system for applications."><code>logging</code></a>
</dt>
<dd>
<p>API reference for the logging module.</p> </dd> <dt>
<code>Module</code> <a class="reference internal" href="../library/logging.config#module-logging.config" title="logging.config: Configuration of the logging module."><code>logging.config</code></a>
</dt>
<dd>
<p>Configuration API for the logging module.</p> </dd> <dt>
<code>Module</code> <a class="reference internal" href="../library/logging.handlers#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code>logging.handlers</code></a>
</dt>
<dd>
<p>Useful handlers included with the logging module.</p> </dd> </dl> <p><a class="reference internal" href="logging#logging-basic-tutorial"><span class="std std-ref">Basic Tutorial</span></a></p> <p><a class="reference internal" href="logging#logging-advanced-tutorial"><span class="std std-ref">Advanced Tutorial</span></a></p> </div> </section> <div class="_attribution">
  <p class="_attribution-p">
    &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
    <a href="https://docs.python.org/3.12/howto/logging-cookbook.html" class="_attribution-link">https://docs.python.org/3.12/howto/logging-cookbook.html</a>
  </p>
</div>