-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlogging-cookbook.po
More file actions
5012 lines (4579 loc) · 172 KB
/
logging-cookbook.po
File metadata and controls
5012 lines (4579 loc) · 172 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SOME DESCRIPTIVE TITLE.
# Copyright (C) 2001-2026, Python Software Foundation
# This file is distributed under the same license as the Python package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
# Translators:
# python-doc bot, 2025
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Python 3.13\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-04-11 15:18+0000\n"
"PO-Revision-Date: 2025-09-15 01:03+0000\n"
"Last-Translator: python-doc bot, 2025\n"
"Language-Team: Polish (https://app.transifex.com/python-doc/teams/5390/pl/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: pl\n"
"Plural-Forms: nplurals=4; plural=(n==1 ? 0 : (n%10>=2 && n%10<=4) && "
"(n%100<12 || n%100>14) ? 1 : n!=1 && (n%10>=0 && n%10<=1) || (n%10>=5 && "
"n%10<=9) || (n%100>=12 && n%100<=14) ? 2 : 3);\n"
msgid "Logging Cookbook"
msgstr ""
msgid "Author"
msgstr "Autor"
msgid "Vinay Sajip <vinay_sajip at red-dove dot com>"
msgstr ""
msgid ""
"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 :ref:`cookbook-ref-links`."
msgstr ""
msgid "Using logging in multiple modules"
msgstr ""
msgid ""
"Multiple calls to ``logging.getLogger('someLogger')`` 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::"
msgstr ""
msgid ""
"import logging\n"
"import auxiliary_module\n"
"\n"
"# create logger with 'spam_application'\n"
"logger = logging.getLogger('spam_application')\n"
"logger.setLevel(logging.DEBUG)\n"
"# create file handler which logs even debug messages\n"
"fh = logging.FileHandler('spam.log')\n"
"fh.setLevel(logging.DEBUG)\n"
"# create console handler with a higher log level\n"
"ch = logging.StreamHandler()\n"
"ch.setLevel(logging.ERROR)\n"
"# create formatter and add it to the handlers\n"
"formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - "
"%(message)s')\n"
"fh.setFormatter(formatter)\n"
"ch.setFormatter(formatter)\n"
"# add the handlers to the logger\n"
"logger.addHandler(fh)\n"
"logger.addHandler(ch)\n"
"\n"
"logger.info('creating an instance of auxiliary_module.Auxiliary')\n"
"a = auxiliary_module.Auxiliary()\n"
"logger.info('created an instance of auxiliary_module.Auxiliary')\n"
"logger.info('calling auxiliary_module.Auxiliary.do_something')\n"
"a.do_something()\n"
"logger.info('finished auxiliary_module.Auxiliary.do_something')\n"
"logger.info('calling auxiliary_module.some_function()')\n"
"auxiliary_module.some_function()\n"
"logger.info('done with auxiliary_module.some_function()')"
msgstr ""
msgid "Here is the auxiliary module::"
msgstr ""
msgid ""
"import logging\n"
"\n"
"# create logger\n"
"module_logger = logging.getLogger('spam_application.auxiliary')\n"
"\n"
"class Auxiliary:\n"
" def __init__(self):\n"
" self.logger = logging.getLogger('spam_application.auxiliary."
"Auxiliary')\n"
" self.logger.info('creating an instance of Auxiliary')\n"
"\n"
" def do_something(self):\n"
" self.logger.info('doing something')\n"
" a = 1 + 1\n"
" self.logger.info('done doing something')\n"
"\n"
"def some_function():\n"
" module_logger.info('received a call to \"some_function\"')"
msgstr ""
msgid "The output looks like this:"
msgstr "Wynik wygląda tak:"
msgid ""
"2005-03-23 23:47:11,663 - spam_application - INFO -\n"
" creating an instance of auxiliary_module.Auxiliary\n"
"2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -\n"
" creating an instance of Auxiliary\n"
"2005-03-23 23:47:11,665 - spam_application - INFO -\n"
" created an instance of auxiliary_module.Auxiliary\n"
"2005-03-23 23:47:11,668 - spam_application - INFO -\n"
" calling auxiliary_module.Auxiliary.do_something\n"
"2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -\n"
" doing something\n"
"2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -\n"
" done doing something\n"
"2005-03-23 23:47:11,670 - spam_application - INFO -\n"
" finished auxiliary_module.Auxiliary.do_something\n"
"2005-03-23 23:47:11,671 - spam_application - INFO -\n"
" calling auxiliary_module.some_function()\n"
"2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -\n"
" received a call to 'some_function'\n"
"2005-03-23 23:47:11,673 - spam_application - INFO -\n"
" done with auxiliary_module.some_function()"
msgstr ""
msgid "Logging from multiple threads"
msgstr ""
msgid ""
"Logging from multiple threads requires no special effort. The following "
"example shows logging from the main (initial) thread and another thread::"
msgstr ""
msgid ""
"import logging\n"
"import threading\n"
"import time\n"
"\n"
"def worker(arg):\n"
" while not arg['stop']:\n"
" logging.debug('Hi from myfunc')\n"
" time.sleep(0.5)\n"
"\n"
"def main():\n"
" logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d "
"%(threadName)s %(message)s')\n"
" info = {'stop': False}\n"
" thread = threading.Thread(target=worker, args=(info,))\n"
" thread.start()\n"
" while True:\n"
" try:\n"
" logging.debug('Hello from main')\n"
" time.sleep(0.75)\n"
" except KeyboardInterrupt:\n"
" info['stop'] = True\n"
" break\n"
" thread.join()\n"
"\n"
"if __name__ == '__main__':\n"
" main()"
msgstr ""
msgid "When run, the script should print something like the following:"
msgstr ""
msgid ""
" 0 Thread-1 Hi from myfunc\n"
" 3 MainThread Hello from main\n"
" 505 Thread-1 Hi from myfunc\n"
" 755 MainThread Hello from main\n"
"1007 Thread-1 Hi from myfunc\n"
"1507 MainThread Hello from main\n"
"1508 Thread-1 Hi from myfunc\n"
"2010 Thread-1 Hi from myfunc\n"
"2258 MainThread Hello from main\n"
"2512 Thread-1 Hi from myfunc\n"
"3009 MainThread Hello from main\n"
"3013 Thread-1 Hi from myfunc\n"
"3515 Thread-1 Hi from myfunc\n"
"3761 MainThread Hello from main\n"
"4017 Thread-1 Hi from myfunc\n"
"4513 MainThread Hello from main\n"
"4518 Thread-1 Hi from myfunc"
msgstr ""
msgid ""
"This shows the logging output interspersed as one might expect. This "
"approach works for more threads than shown here, of course."
msgstr ""
msgid "Multiple handlers and formatters"
msgstr ""
msgid ""
"Loggers are plain Python objects. The :meth:`~Logger.addHandler` 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::"
msgstr ""
msgid ""
"import logging\n"
"\n"
"logger = logging.getLogger('simple_example')\n"
"logger.setLevel(logging.DEBUG)\n"
"# create file handler which logs even debug messages\n"
"fh = logging.FileHandler('spam.log')\n"
"fh.setLevel(logging.DEBUG)\n"
"# create console handler with a higher log level\n"
"ch = logging.StreamHandler()\n"
"ch.setLevel(logging.ERROR)\n"
"# create formatter and add it to the handlers\n"
"formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - "
"%(message)s')\n"
"ch.setFormatter(formatter)\n"
"fh.setFormatter(formatter)\n"
"# add the handlers to logger\n"
"logger.addHandler(ch)\n"
"logger.addHandler(fh)\n"
"\n"
"# 'application' code\n"
"logger.debug('debug message')\n"
"logger.info('info message')\n"
"logger.warning('warn message')\n"
"logger.error('error message')\n"
"logger.critical('critical message')"
msgstr ""
msgid ""
"Notice that the 'application' code does not care about multiple handlers. "
"All that changed was the addition and configuration of a new handler named "
"*fh*."
msgstr ""
msgid ""
"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 ``print`` statements for debugging, use ``logger.debug``: 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."
msgstr ""
msgid "Logging to multiple destinations"
msgstr ""
msgid ""
"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::"
msgstr ""
msgid ""
"import logging\n"
"\n"
"# set up logging to file - see previous section for more details\n"
"logging.basicConfig(level=logging.DEBUG,\n"
" format='%(asctime)s %(name)-12s %(levelname)-8s "
"%(message)s',\n"
" datefmt='%m-%d %H:%M',\n"
" filename='/tmp/myapp.log',\n"
" filemode='w')\n"
"# define a Handler which writes INFO messages or higher to the sys.stderr\n"
"console = logging.StreamHandler()\n"
"console.setLevel(logging.INFO)\n"
"# set a format which is simpler for console use\n"
"formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')\n"
"# tell the handler to use this format\n"
"console.setFormatter(formatter)\n"
"# add the handler to the root logger\n"
"logging.getLogger().addHandler(console)\n"
"\n"
"# Now, we can log to the root logger, or any other logger. First the "
"root...\n"
"logging.info('Jackdaws love my big sphinx of quartz.')\n"
"\n"
"# Now, define a couple of other loggers which might represent areas in your\n"
"# application:\n"
"\n"
"logger1 = logging.getLogger('myapp.area1')\n"
"logger2 = logging.getLogger('myapp.area2')\n"
"\n"
"logger1.debug('Quick zephyrs blow, vexing daft Jim.')\n"
"logger1.info('How quickly daft jumping zebras vex.')\n"
"logger2.warning('Jail zesty vixen who grabbed pay from quack.')\n"
"logger2.error('The five boxing wizards jump quickly.')"
msgstr ""
msgid "When you run this, on the console you will see"
msgstr ""
msgid ""
"root : INFO Jackdaws love my big sphinx of quartz.\n"
"myapp.area1 : INFO How quickly daft jumping zebras vex.\n"
"myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.\n"
"myapp.area2 : ERROR The five boxing wizards jump quickly."
msgstr ""
msgid "and in the file you will see something like"
msgstr ""
msgid ""
"10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.\n"
"10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.\n"
"10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.\n"
"10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from "
"quack.\n"
"10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly."
msgstr ""
msgid ""
"As you can see, the DEBUG message only shows up in the file. The other "
"messages are sent to both destinations."
msgstr ""
msgid ""
"This example uses console and file handlers, but you can use any number and "
"combination of handlers you choose."
msgstr ""
msgid ""
"Note that the above choice of log filename ``/tmp/myapp.log`` 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."
msgstr ""
msgid "Custom handling of levels"
msgstr ""
msgid ""
"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:"
msgstr ""
msgid "Send messages of severity ``INFO`` and ``WARNING`` to ``sys.stdout``"
msgstr ""
msgid "Send messages of severity ``ERROR`` and above to ``sys.stderr``"
msgstr ""
msgid "Send messages of severity ``DEBUG`` and above to file ``app.log``"
msgstr ""
msgid "Suppose you configure logging with the following JSON:"
msgstr ""
msgid ""
"{\n"
" \"version\": 1,\n"
" \"disable_existing_loggers\": false,\n"
" \"formatters\": {\n"
" \"simple\": {\n"
" \"format\": \"%(levelname)-8s - %(message)s\"\n"
" }\n"
" },\n"
" \"handlers\": {\n"
" \"stdout\": {\n"
" \"class\": \"logging.StreamHandler\",\n"
" \"level\": \"INFO\",\n"
" \"formatter\": \"simple\",\n"
" \"stream\": \"ext://sys.stdout\"\n"
" },\n"
" \"stderr\": {\n"
" \"class\": \"logging.StreamHandler\",\n"
" \"level\": \"ERROR\",\n"
" \"formatter\": \"simple\",\n"
" \"stream\": \"ext://sys.stderr\"\n"
" },\n"
" \"file\": {\n"
" \"class\": \"logging.FileHandler\",\n"
" \"formatter\": \"simple\",\n"
" \"filename\": \"app.log\",\n"
" \"mode\": \"w\"\n"
" }\n"
" },\n"
" \"root\": {\n"
" \"level\": \"DEBUG\",\n"
" \"handlers\": [\n"
" \"stderr\",\n"
" \"stdout\",\n"
" \"file\"\n"
" ]\n"
" }\n"
"}"
msgstr ""
msgid ""
"This configuration does *almost* what we want, except that ``sys.stdout`` "
"would show messages of severity ``ERROR`` and only events of this severity "
"and higher will be tracked as well as ``INFO`` and ``WARNING`` 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 ``filters`` "
"section parallel to ``formatters`` and ``handlers``:"
msgstr ""
msgid ""
"{\n"
" \"filters\": {\n"
" \"warnings_and_below\": {\n"
" \"()\" : \"__main__.filter_maker\",\n"
" \"level\": \"WARNING\"\n"
" }\n"
" }\n"
"}"
msgstr ""
msgid "and changing the section on the ``stdout`` handler to add it:"
msgstr ""
msgid ""
"{\n"
" \"stdout\": {\n"
" \"class\": \"logging.StreamHandler\",\n"
" \"level\": \"INFO\",\n"
" \"formatter\": \"simple\",\n"
" \"stream\": \"ext://sys.stdout\",\n"
" \"filters\": [\"warnings_and_below\"]\n"
" }\n"
"}"
msgstr ""
msgid ""
"A filter is just a function, so we can define the ``filter_maker`` (a "
"factory function) as follows:"
msgstr ""
msgid ""
"def filter_maker(level):\n"
" level = getattr(logging, level)\n"
"\n"
" def filter(record):\n"
" return record.levelno <= level\n"
"\n"
" return filter"
msgstr ""
msgid ""
"This converts the string argument passed in to a numeric level, and returns "
"a function which only returns ``True`` if the level of the passed in record "
"is at or below the specified level. Note that in this example I have defined "
"the ``filter_maker`` in a test script ``main.py`` that I run from the "
"command line, so its module will be ``__main__`` - hence the ``__main__."
"filter_maker`` in the filter configuration. You will need to change that if "
"you define it in a different module."
msgstr ""
msgid "With the filter added, we can run ``main.py``, which in full is:"
msgstr ""
msgid ""
"import json\n"
"import logging\n"
"import logging.config\n"
"\n"
"CONFIG = '''\n"
"{\n"
" \"version\": 1,\n"
" \"disable_existing_loggers\": false,\n"
" \"formatters\": {\n"
" \"simple\": {\n"
" \"format\": \"%(levelname)-8s - %(message)s\"\n"
" }\n"
" },\n"
" \"filters\": {\n"
" \"warnings_and_below\": {\n"
" \"()\" : \"__main__.filter_maker\",\n"
" \"level\": \"WARNING\"\n"
" }\n"
" },\n"
" \"handlers\": {\n"
" \"stdout\": {\n"
" \"class\": \"logging.StreamHandler\",\n"
" \"level\": \"INFO\",\n"
" \"formatter\": \"simple\",\n"
" \"stream\": \"ext://sys.stdout\",\n"
" \"filters\": [\"warnings_and_below\"]\n"
" },\n"
" \"stderr\": {\n"
" \"class\": \"logging.StreamHandler\",\n"
" \"level\": \"ERROR\",\n"
" \"formatter\": \"simple\",\n"
" \"stream\": \"ext://sys.stderr\"\n"
" },\n"
" \"file\": {\n"
" \"class\": \"logging.FileHandler\",\n"
" \"formatter\": \"simple\",\n"
" \"filename\": \"app.log\",\n"
" \"mode\": \"w\"\n"
" }\n"
" },\n"
" \"root\": {\n"
" \"level\": \"DEBUG\",\n"
" \"handlers\": [\n"
" \"stderr\",\n"
" \"stdout\",\n"
" \"file\"\n"
" ]\n"
" }\n"
"}\n"
"'''\n"
"\n"
"def filter_maker(level):\n"
" level = getattr(logging, level)\n"
"\n"
" def filter(record):\n"
" return record.levelno <= level\n"
"\n"
" return filter\n"
"\n"
"logging.config.dictConfig(json.loads(CONFIG))\n"
"logging.debug('A DEBUG message')\n"
"logging.info('An INFO message')\n"
"logging.warning('A WARNING message')\n"
"logging.error('An ERROR message')\n"
"logging.critical('A CRITICAL message')"
msgstr ""
msgid "And after running it like this:"
msgstr ""
msgid "python main.py 2>stderr.log >stdout.log"
msgstr ""
msgid "We can see the results are as expected:"
msgstr ""
msgid ""
"$ more *.log\n"
"::::::::::::::\n"
"app.log\n"
"::::::::::::::\n"
"DEBUG - A DEBUG message\n"
"INFO - An INFO message\n"
"WARNING - A WARNING message\n"
"ERROR - An ERROR message\n"
"CRITICAL - A CRITICAL message\n"
"::::::::::::::\n"
"stderr.log\n"
"::::::::::::::\n"
"ERROR - An ERROR message\n"
"CRITICAL - A CRITICAL message\n"
"::::::::::::::\n"
"stdout.log\n"
"::::::::::::::\n"
"INFO - An INFO message\n"
"WARNING - A WARNING message"
msgstr ""
msgid "Configuration server example"
msgstr ""
msgid "Here is an example of a module using the logging configuration server::"
msgstr ""
msgid ""
"import logging\n"
"import logging.config\n"
"import time\n"
"import os\n"
"\n"
"# read initial config file\n"
"logging.config.fileConfig('logging.conf')\n"
"\n"
"# create and start listener on port 9999\n"
"t = logging.config.listen(9999)\n"
"t.start()\n"
"\n"
"logger = logging.getLogger('simpleExample')\n"
"\n"
"try:\n"
" # loop through logging calls to see the difference\n"
" # new configurations make, until Ctrl+C is pressed\n"
" while True:\n"
" logger.debug('debug message')\n"
" logger.info('info message')\n"
" logger.warning('warn message')\n"
" logger.error('error message')\n"
" logger.critical('critical message')\n"
" time.sleep(5)\n"
"except KeyboardInterrupt:\n"
" # cleanup\n"
" logging.config.stopListening()\n"
" t.join()"
msgstr ""
msgid ""
"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::"
msgstr ""
msgid ""
"#!/usr/bin/env python\n"
"import socket, sys, struct\n"
"\n"
"with open(sys.argv[1], 'rb') as f:\n"
" data_to_send = f.read()\n"
"\n"
"HOST = 'localhost'\n"
"PORT = 9999\n"
"s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n"
"print('connecting...')\n"
"s.connect((HOST, PORT))\n"
"print('sending config...')\n"
"s.send(struct.pack('>L', len(data_to_send)))\n"
"s.send(data_to_send)\n"
"s.close()\n"
"print('complete')"
msgstr ""
msgid "Dealing with handlers that block"
msgstr ""
msgid ""
"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."
msgstr ""
msgid ""
"A common culprit which demonstrates sluggish behaviour is the :class:"
"`SMTPHandler`: 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 :class:`SocketHandler` 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)."
msgstr ""
msgid ""
"One solution is to use a two-part approach. For the first part, attach only "
"a :class:`QueueHandler` 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 :exc:`queue.Full` 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 ``QueueHandlers`` to your loggers) for the benefit of other "
"developers who will use your code."
msgstr ""
msgid ""
"The second part of the solution is :class:`QueueListener`, which has been "
"designed as the counterpart to :class:`QueueHandler`. A :class:"
"`QueueListener` 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 ``QueueHandlers`` (or any other source of ``LogRecords``, for that "
"matter). The ``LogRecords`` are removed from the queue and passed to the "
"handlers for processing."
msgstr ""
msgid ""
"The advantage of having a separate :class:`QueueListener` class is that you "
"can use the same instance to service multiple ``QueueHandlers``. 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."
msgstr ""
msgid "An example of using these two classes follows (imports omitted)::"
msgstr ""
msgid ""
"que = queue.Queue(-1) # no limit on size\n"
"queue_handler = QueueHandler(que)\n"
"handler = logging.StreamHandler()\n"
"listener = QueueListener(que, handler)\n"
"root = logging.getLogger()\n"
"root.addHandler(queue_handler)\n"
"formatter = logging.Formatter('%(threadName)s: %(message)s')\n"
"handler.setFormatter(formatter)\n"
"listener.start()\n"
"# The log output will display the thread which generated\n"
"# the event (the main thread) rather than the internal\n"
"# thread which monitors the internal queue. This is what\n"
"# you want to happen.\n"
"root.warning('Look out!')\n"
"listener.stop()"
msgstr ""
msgid "which, when run, will produce:"
msgstr ""
msgid "MainThread: Look out!"
msgstr ""
msgid ""
"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 :mod:"
"`asyncio` 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 ``QueueListener`` thread."
msgstr ""
msgid ""
"Prior to Python 3.5, the :class:`QueueListener` 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 ``respect_handler_level=True`` 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."
msgstr ""
msgid "Sending and receiving logging events across a network"
msgstr ""
msgid ""
"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 :class:"
"`SocketHandler` instance to the root logger at the sending end::"
msgstr ""
msgid ""
"import logging, logging.handlers\n"
"\n"
"rootLogger = logging.getLogger()\n"
"rootLogger.setLevel(logging.DEBUG)\n"
"socketHandler = logging.handlers.SocketHandler('localhost',\n"
" logging.handlers.DEFAULT_TCP_LOGGING_PORT)\n"
"# don't bother with a formatter, since a socket handler sends the event as\n"
"# an unformatted pickle\n"
"rootLogger.addHandler(socketHandler)\n"
"\n"
"# Now, we can log to the root logger, or any other logger. First the "
"root...\n"
"logging.info('Jackdaws love my big sphinx of quartz.')\n"
"\n"
"# Now, define a couple of other loggers which might represent areas in your\n"
"# application:\n"
"\n"
"logger1 = logging.getLogger('myapp.area1')\n"
"logger2 = logging.getLogger('myapp.area2')\n"
"\n"
"logger1.debug('Quick zephyrs blow, vexing daft Jim.')\n"
"logger1.info('How quickly daft jumping zebras vex.')\n"
"logger2.warning('Jail zesty vixen who grabbed pay from quack.')\n"
"logger2.error('The five boxing wizards jump quickly.')"
msgstr ""
msgid ""
"At the receiving end, you can set up a receiver using the :mod:"
"`socketserver` module. Here is a basic working example::"
msgstr ""
msgid ""
"import pickle\n"
"import logging\n"
"import logging.handlers\n"
"import socketserver\n"
"import struct\n"
"\n"
"\n"
"class LogRecordStreamHandler(socketserver.StreamRequestHandler):\n"
" \"\"\"Handler for a streaming logging request.\n"
"\n"
" This basically logs the record using whatever logging policy is\n"
" configured locally.\n"
" \"\"\"\n"
"\n"
" def handle(self):\n"
" \"\"\"\n"
" Handle multiple requests - each expected to be a 4-byte length,\n"
" followed by the LogRecord in pickle format. Logs the record\n"
" according to whatever policy is configured locally.\n"
" \"\"\"\n"
" while True:\n"
" chunk = self.connection.recv(4)\n"
" if len(chunk) < 4:\n"
" break\n"
" slen = struct.unpack('>L', chunk)[0]\n"
" chunk = self.connection.recv(slen)\n"
" while len(chunk) < slen:\n"
" chunk = chunk + self.connection.recv(slen - len(chunk))\n"
" obj = self.unPickle(chunk)\n"
" record = logging.makeLogRecord(obj)\n"
" self.handleLogRecord(record)\n"
"\n"
" def unPickle(self, data):\n"
" return pickle.loads(data)\n"
"\n"
" def handleLogRecord(self, record):\n"
" # if a name is specified, we use the named logger rather than the "
"one\n"
" # implied by the record.\n"
" if self.server.logname is not None:\n"
" name = self.server.logname\n"
" else:\n"
" name = record.name\n"
" logger = logging.getLogger(name)\n"
" # N.B. EVERY record gets logged. This is because Logger.handle\n"
" # is normally called AFTER logger-level filtering. If you want\n"
" # to do filtering, do it at the client end to save wasting\n"
" # cycles and network bandwidth!\n"
" logger.handle(record)\n"
"\n"
"class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):\n"
" \"\"\"\n"
" Simple TCP socket-based logging receiver suitable for testing.\n"
" \"\"\"\n"
"\n"
" allow_reuse_address = True\n"
"\n"
" def __init__(self, host='localhost',\n"
" port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,\n"
" handler=LogRecordStreamHandler):\n"
" socketserver.ThreadingTCPServer.__init__(self, (host, port), "
"handler)\n"
" self.abort = 0\n"
" self.timeout = 1\n"
" self.logname = None\n"
"\n"
" def serve_until_stopped(self):\n"
" import select\n"
" abort = 0\n"
" while not abort:\n"
" rd, wr, ex = select.select([self.socket.fileno()],\n"
" [], [],\n"
" self.timeout)\n"
" if rd:\n"
" self.handle_request()\n"
" abort = self.abort\n"
"\n"
"def main():\n"
" logging.basicConfig(\n"
" format='%(relativeCreated)5d %(name)-15s %(levelname)-8s "
"%(message)s')\n"
" tcpserver = LogRecordSocketReceiver()\n"
" print('About to start TCP server...')\n"
" tcpserver.serve_until_stopped()\n"
"\n"
"if __name__ == '__main__':\n"
" main()"
msgstr ""
msgid ""
"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:"
msgstr ""
msgid ""
"About to start TCP server...\n"
" 59 root INFO Jackdaws love my big sphinx of quartz.\n"
" 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.\n"
" 69 myapp.area1 INFO How quickly daft jumping zebras vex.\n"
" 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.\n"
" 69 myapp.area2 ERROR The five boxing wizards jump quickly."
msgstr ""
msgid ""
"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 :meth:`~SocketHandler.makePickle` method and implementing "
"your alternative there, as well as adapting the above script to use your "
"alternative serialization."
msgstr ""
msgid "Running a logging socket listener in production"
msgstr ""
msgid ""
"To run a logging listener in production, you may need to use a process-"
"management tool such as `Supervisor <http://supervisord.org/>`_. `Here is a "
"Gist <socket-listener-gist_>`__ which provides the bare-bones files to run "
"the above functionality using Supervisor. It consists of the following files:"
msgstr ""
msgid "File"
msgstr ""
msgid "Purpose"
msgstr ""
msgid ":file:`prepare.sh`"
msgstr ":file:`prepare.sh`"
msgid "A Bash script to prepare the environment for testing"
msgstr ""
msgid ":file:`supervisor.conf`"
msgstr ":file:`supervisor.conf`"
msgid ""
"The Supervisor configuration file, which has entries for the listener and a "
"multi-process web application"
msgstr ""
msgid ":file:`ensure_app.sh`"
msgstr ":file:`ensure_app.sh`"
msgid ""
"A Bash script to ensure that Supervisor is running with the above "
"configuration"
msgstr ""
msgid ":file:`log_listener.py`"
msgstr ":file:`log_listener.py`"
msgid ""
"The socket listener program which receives log events and records them to a "
"file"
msgstr ""
msgid ":file:`main.py`"
msgstr ":file:`main.py`"
msgid ""
"A simple web application which performs logging via a socket connected to "
"the listener"
msgstr ""
msgid ":file:`webapp.json`"
msgstr ":file:`webapp.json`"
msgid "A JSON configuration file for the web application"
msgstr ""
msgid ":file:`client.py`"
msgstr ":file:`client.py`"
msgid "A Python script to exercise the web application"
msgstr ""
msgid ""
"The web application uses `Gunicorn <https://gunicorn.org/>`_, 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."
msgstr ""
msgid "To test these files, do the following in a POSIX environment:"
msgstr ""
msgid ""
"Download `the Gist <socket-listener-gist_>`__ as a ZIP archive using the :"
"guilabel:`Download ZIP` button."
msgstr ""
msgid "Unzip the above files from the archive into a scratch directory."
msgstr ""
msgid ""
"In the scratch directory, run ``bash prepare.sh`` to get things ready. This "
"creates a :file:`run` subdirectory to contain Supervisor-related and log "
"files, and a :file:`venv` subdirectory to contain a virtual environment into "
"which ``bottle``, ``gunicorn`` and ``supervisor`` are installed."
msgstr ""
msgid ""
"Run ``bash ensure_app.sh`` to ensure that Supervisor is running with the "
"above configuration."
msgstr ""
msgid ""
"Run ``venv/bin/python client.py`` to exercise the web application, which "
"will lead to records being written to the log."
msgstr ""
msgid ""
"Inspect the log files in the :file:`run` subdirectory. You should see the "
"most recent log lines in files matching the pattern :file:`app.log*`. They "
"won't be in any particular order, since they have been handled concurrently "
"by different worker processes in a non-deterministic way."
msgstr ""
msgid ""
"You can shut down the listener and the web application by running ``venv/bin/"
"supervisorctl -c supervisor.conf shutdown``."
msgstr ""
msgid ""