-
Notifications
You must be signed in to change notification settings - Fork 395
/
Copy pathlogging-cookbook.po
6179 lines (5761 loc) · 250 KB
/
logging-cookbook.po
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
# Copyright (C) 2001-2020, Python Software Foundation
# This file is distributed under the same license as the Python package.
# Maintained by the python-doc-es workteam.
# docs-es@python.org /
# https://mail.python.org/mailman3/lists/docs-es.python.org/
# Check https://github.com/python/python-docs-es/blob/3.8/TRANSLATORS to
# get the list of volunteers
#
msgid ""
msgstr ""
"Project-Id-Version: Python 3.8\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2024-11-21 16:38-0300\n"
"PO-Revision-Date: 2022-10-27 15:51-0300\n"
"Last-Translator: Carlos A. Crespo <lvccrespo@gmail.com>\n"
"Language: es\n"
"Language-Team: python-doc-es\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.16.0\n"
#: ../Doc/howto/logging-cookbook.rst:5
msgid "Logging Cookbook"
msgstr "Libro de recetas de Logging"
#: ../Doc/howto/logging-cookbook.rst
msgid "Author"
msgstr "Autor"
#: ../Doc/howto/logging-cookbook.rst:7
msgid "Vinay Sajip <vinay_sajip at red-dove dot com>"
msgstr "Vinay Sajip <vinay_sajip at red-dove dot com>"
#: ../Doc/howto/logging-cookbook.rst:9
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 ""
"Esta página contiene un número de recetas sobre *logging*, que han sido "
"útiles en el pasado. Para obtener enlaces al tutorial e información de "
"referencia, consulte :ref:`cookbook-ref-links`."
#: ../Doc/howto/logging-cookbook.rst:16
msgid "Using logging in multiple modules"
msgstr "Usar logging en múltiples módulos"
#: ../Doc/howto/logging-cookbook.rst:18
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 ""
"Múltiples llamadas a ``logging.getLogger('someLogger')`` retornan una "
"referencia al mismo objeto logger. Esto es cierto no solo dentro del mismo "
"módulo, sino también en todos los módulos siempre que estén ejecutándose en "
"el mismo proceso del intérprete de Python. Es válido para las referencias al "
"mismo objeto. Además, el código de la aplicación puede definir y configurar "
"un logger primario en un módulo y crear (pero no configurar) un logger "
"secundario en un módulo separado, y todas las llamadas al secundario pasarán "
"al principal. A continuación un módulo principal::"
#: ../Doc/howto/logging-cookbook.rst:26
#, python-format
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 ""
# Esto me confunde un poco. Cuando menciona módulo principal / auxiliar en los
# ejemplos, ¿se refiere a principal y secundario que está en el cuerpo del
# texto? ¿no convendría unificar?
#: ../Doc/howto/logging-cookbook.rst:56
msgid "Here is the auxiliary module::"
msgstr "Y aquí un módulo auxiliar::"
#: ../Doc/howto/logging-cookbook.rst:58
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 ""
#: ../Doc/howto/logging-cookbook.rst:76
msgid "The output looks like this:"
msgstr "El resultado se ve así:"
#: ../Doc/howto/logging-cookbook.rst:78
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 ""
#: ../Doc/howto/logging-cookbook.rst:102
msgid "Logging from multiple threads"
msgstr "Logging desde múltiples hilos"
#: ../Doc/howto/logging-cookbook.rst:104
msgid ""
"Logging from multiple threads requires no special effort. The following "
"example shows logging from the main (initial) thread and another thread::"
msgstr ""
"Realizar *logging* desde múltiples hilos (*threads*) no requiere ningún "
"esfuerzo especial. El siguiente ejemplo muestra el logging desde el hilo "
"principal (inicial) y otro hilo::"
#: ../Doc/howto/logging-cookbook.rst:107
#, python-format
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 ""
#: ../Doc/howto/logging-cookbook.rst:133
msgid "When run, the script should print something like the following:"
msgstr "Cuando se ejecuta, el script debe imprimir algo como lo siguiente:"
#: ../Doc/howto/logging-cookbook.rst:135
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 ""
#: ../Doc/howto/logging-cookbook.rst:155
msgid ""
"This shows the logging output interspersed as one might expect. This "
"approach works for more threads than shown here, of course."
msgstr ""
"Esto muestra la salida de logging intercalada como cabría esperar. Por "
"supuesto, este enfoque funciona para más hilos de lo que se muestran aquí."
#: ../Doc/howto/logging-cookbook.rst:159
msgid "Multiple handlers and formatters"
msgstr "Múltiples gestores y formateadores"
#: ../Doc/howto/logging-cookbook.rst:161
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 ""
"Los *loggers* son simples objetos Python. El método :meth:`~Logger."
"addHandler` no tiene una cuota mínima o máxima para la cantidad de gestores "
"(*handlers*) que puede agregar. A veces será beneficioso para una aplicación "
"registrar todos los mensajes de todas las prioridades en un archivo de texto "
"mientras se registran simultáneamente los errores o más en la consola. Para "
"configurar esto, simplemente configure los gestores apropiados. Las llamadas "
"de logging en el código de la aplicación permanecerán sin cambios. Aquí hay "
"una ligera modificación al ejemplo de configuración simple anterior basado "
"en módulo::"
#: ../Doc/howto/logging-cookbook.rst:169
#, python-format
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 ""
#: ../Doc/howto/logging-cookbook.rst:194
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 ""
"Tenga en cuenta que el código de la 'aplicación' no se preocupa por los "
"gestores múltiples. Todo lo que cambió fue la adición y configuración de un "
"nuevo gestor llamado *fh*."
#: ../Doc/howto/logging-cookbook.rst:197
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 ""
"La capacidad de crear nuevos gestores con filtros de mayor o menor prioridad "
"puede ser muy útil al escribir y probar una aplicación. En lugar de usar "
"muchas declaraciones ``print`` para la depuración, use ``logger.debug``: a "
"diferencia de las declaraciones de impresión, que tendrá que eliminar o "
"comentar más tarde, las declaraciones de *logger.debug* pueden permanecer "
"intactas en el código fuente y permanecen inactivas hasta que las necesite "
"nuevamente. En ese momento, el único cambio que debe realizar es modificar "
"el nivel de prioridad del *logger* y/o gestor para depurar."
#: ../Doc/howto/logging-cookbook.rst:208
msgid "Logging to multiple destinations"
msgstr "Logging en múltiples destinos"
#: ../Doc/howto/logging-cookbook.rst:210
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 ""
"Supongamos que desea que la consola y un archivo tengan diferentes formatos "
"de mensaje y salida de log para diferentes situaciones. Por ejemplo, desea "
"registrar mensajes con un nivel DEBUG y superiores en un archivo y enviar "
"mensajes con nivel INFO y superior a la consola. Además, suponga que desea "
"grabar una marca de tiempo en el archivo y no imprimirlo en la consola. "
"Puede lograr este comportamiento haciendo lo siguiente::"
#: ../Doc/howto/logging-cookbook.rst:216
#, python-format
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 ""
#: ../Doc/howto/logging-cookbook.rst:248
msgid "When you run this, on the console you will see"
msgstr "Cuando ejecute esto, en la consola verá"
#: ../Doc/howto/logging-cookbook.rst:250
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 ""
#: ../Doc/howto/logging-cookbook.rst:257
msgid "and in the file you will see something like"
msgstr "y en el archivo verá algo como"
#: ../Doc/howto/logging-cookbook.rst:259
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 ""
#: ../Doc/howto/logging-cookbook.rst:267
msgid ""
"As you can see, the DEBUG message only shows up in the file. The other "
"messages are sent to both destinations."
msgstr ""
"Como se puede ver, el mensaje DEBUG sólo se muestra en el archivo. Los otros "
"mensajes se envían a los dos destinos."
#: ../Doc/howto/logging-cookbook.rst:270
msgid ""
"This example uses console and file handlers, but you can use any number and "
"combination of handlers you choose."
msgstr ""
"Este ejemplo usa gestores de consola y archivos, pero puede usar cualquier "
"número y combinación de los gestores que elija."
#: ../Doc/howto/logging-cookbook.rst:273
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 ""
"Tenga en cuenta que la elección anterior del nombre del archivo de registro "
"``/tmp/myapp.log`` implica el uso de una ubicación estándar para los "
"archivos temporales en los sistemas POSIX. En Windows, es posible que tenga "
"que elegir un nombre de directorio diferente para el registro - sólo "
"asegúrese de que el directorio existe y que tiene los permisos para crear y "
"actualizar archivos en él."
#: ../Doc/howto/logging-cookbook.rst:282
msgid "Custom handling of levels"
msgstr "Gestión personalizada de niveles"
#: ../Doc/howto/logging-cookbook.rst:284
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 ""
"A veces, es posible que desee hacer algo ligeramente diferente del manejo "
"estándar de niveles, donde todos los niveles por encima de un umbral son "
"procesados por un gestor. Para ello, es necesario utilizar filtros. Veamos "
"un escenario en el que se desea organizar las cosas de la siguiente manera:"
#: ../Doc/howto/logging-cookbook.rst:289
msgid "Send messages of severity ``INFO`` and ``WARNING`` to ``sys.stdout``"
msgstr "Enviar mensajes de gravedad ``INFO`` y ``WARNING`` a ``sys.stdout``"
#: ../Doc/howto/logging-cookbook.rst:290
msgid "Send messages of severity ``ERROR`` and above to ``sys.stderr``"
msgstr "Enviar mensajes de gravedad ``ERROR`` y superiores a ``sys.stderr``"
#: ../Doc/howto/logging-cookbook.rst:291
msgid "Send messages of severity ``DEBUG`` and above to file ``app.log``"
msgstr ""
"Envía los mensajes de gravedad ``DEBUG`` y superiores al archivo ``app.log``"
#: ../Doc/howto/logging-cookbook.rst:293
msgid "Suppose you configure logging with the following JSON:"
msgstr "Supongamos que se configura el registro con el siguiente JSON:"
#: ../Doc/howto/logging-cookbook.rst:295
#, python-format
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 ""
#: ../Doc/howto/logging-cookbook.rst:335
#, fuzzy
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 ""
"Esta configuración hace *casi* lo que queremos, excepto que ``sys.stdout`` "
"mostraría mensajes de gravedad ``ERROR`` y superiores, así como mensajes "
"``INFO`` y ``WARNING``. Para evitarlo, podemos configurar un filtro que "
"excluya esos mensajes y añadirlo al gestor correspondiente. Esto se puede "
"configurar añadiendo una sección ``filters`` paralela a ``formatters`` y "
"``handlers``:"
#: ../Doc/howto/logging-cookbook.rst:341
msgid ""
"{\n"
" \"filters\": {\n"
" \"warnings_and_below\": {\n"
" \"()\" : \"__main__.filter_maker\",\n"
" \"level\": \"WARNING\"\n"
" }\n"
" }\n"
"}"
msgstr ""
#: ../Doc/howto/logging-cookbook.rst:352
msgid "and changing the section on the ``stdout`` handler to add it:"
msgstr "y cambiando la sección del gestor ``stdout`` para añadirlo:"
#: ../Doc/howto/logging-cookbook.rst:354
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 ""
#: ../Doc/howto/logging-cookbook.rst:366
msgid ""
"A filter is just a function, so we can define the ``filter_maker`` (a "
"factory function) as follows:"
msgstr ""
"Un filtro no es más que una función, por lo que podemos definir el "
"``filter_maker`` (una función de fábrica) como sigue:"
#: ../Doc/howto/logging-cookbook.rst:369
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 ""
#: ../Doc/howto/logging-cookbook.rst:379
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 ""
"Esto convierte el argumento de la cadena de caracteres pasada en un nivel "
"numérico, y retorna una función que sólo retorna ``True`` si el nivel del "
"registro pasado está en o por debajo del nivel especificado. Ten en cuenta "
"que en este ejemplo se ha definido el ``filter_maker`` en un script de "
"prueba ``main.py`` que se ejecuta desde la línea de comandos, por lo que su "
"módulo será ``__main__`` - de ahí el ``__main__.filter_maker`` en la "
"configuración del filtro. Tendrás que cambiar eso si lo defines en un módulo "
"diferente."
#: ../Doc/howto/logging-cookbook.rst:387
msgid "With the filter added, we can run ``main.py``, which in full is:"
msgstr ""
"Con el filtro añadido, podemos ejecutar ``main.py``, que en su totalidad es:"
#: ../Doc/howto/logging-cookbook.rst:389
#, python-format
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 ""
#: ../Doc/howto/logging-cookbook.rst:457
msgid "And after running it like this:"
msgstr "Y después de ejecutarlo de esta manera:"
#: ../Doc/howto/logging-cookbook.rst:459
msgid "python main.py 2>stderr.log >stdout.log"
msgstr ""
#: ../Doc/howto/logging-cookbook.rst:463
msgid "We can see the results are as expected:"
msgstr "Podemos ver que los resultados son los esperados:"
#: ../Doc/howto/logging-cookbook.rst:465
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 ""
#: ../Doc/howto/logging-cookbook.rst:489
msgid "Configuration server example"
msgstr "Ejemplo de servidor de configuración"
#: ../Doc/howto/logging-cookbook.rst:491
msgid "Here is an example of a module using the logging configuration server::"
msgstr ""
"Aquí hay un ejemplo de un módulo que usa el servidor de configuración "
"logging::"
#: ../Doc/howto/logging-cookbook.rst:493
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 ""
#: ../Doc/howto/logging-cookbook.rst:522
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 ""
"Y aquí hay un script que toma un nombre de archivo y envía ese archivo al "
"servidor, precedido adecuadamente con la longitud codificada en binario, "
"como la nueva configuración de logging::"
#: ../Doc/howto/logging-cookbook.rst:526
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 ""
#: ../Doc/howto/logging-cookbook.rst:547
msgid "Dealing with handlers that block"
msgstr "Tratar con gestores que bloquean"
#: ../Doc/howto/logging-cookbook.rst:551
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 ""
"A veces tiene que hacer que sus gestores de registro hagan su trabajo sin "
"bloquear el hilo desde el que está iniciando sesión. Esto es común en las "
"aplicaciones web, aunque, por supuesto, también ocurre en otros escenarios."
# -"under the hood": de bajo nivel? más técnicas?
#: ../Doc/howto/logging-cookbook.rst:555
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 ""
"Un responsable habitual que ejemplifica un comportamiento lento es la :class:"
"`SMTPHandler`: el envío de correos electrónicos puede llevar mucho tiempo, "
"por varias razones fuera del control del desarrollador (por ejemplo, una "
"infraestructura de red o correo de bajo rendimiento). Pero casi cualquier "
"controlador basado en red puede bloquear: incluso una operación :class:"
"`SocketHandler` puede estar haciendo a bajo nivel una consulta DNS que es "
"demasiado lenta (y esta consulta puede estar en el código de la biblioteca "
"de socket, debajo de la capa de Python, y fuera de su control)."
#: ../Doc/howto/logging-cookbook.rst:563
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 ""
"Una solución es utilizar un enfoque de dos partes. Para la primera parte, "
"adjunte solo una :class:`QueueHandler` a los loggers que se acceden desde "
"subprocesos críticos de rendimiento. Simplemente escriben en su cola, que "
"puede dimensionarse a una capacidad lo suficientemente grande o "
"inicializarse sin límite superior a su tamaño. La escritura en la cola "
"generalmente se aceptará rápidamente, aunque es probable que deba atrapar la "
"excepción :exc:`queue.Full` como precaución en su código. Si usted es un "
"desarrollador de bibliotecas que tiene subprocesos críticos de rendimiento "
"en su código, asegúrese de documentar esto (junto con una sugerencia de "
"adjuntar solo ``QueueHandlers`` a sus loggers) para el beneficio de otros "
"desarrolladores que usarán su código."
#: ../Doc/howto/logging-cookbook.rst:574
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 ""
"La segunda parte de la solución es :class:`QueueListener`, que fue designado "
"como la contraparte de :class:`QueueHandler`. Un :class:`QueueListener` es "
"muy simple: ha pasado una cola y algunos gestores, y activa un hilo interno "
"que escucha su cola para *LogRecords* enviados desde ``QueueHandlers`` (o "
"cualquier otra fuente de ``LogRecords``, para el caso). Los ``LogRecords`` "
"se eliminan de la cola y se pasan a los gestores para su procesamiento."
#: ../Doc/howto/logging-cookbook.rst:582
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 ""
"La ventaja de tener una clase separada :class:`QueueListener` es que puede "
"usar la misma instancia para dar servicio a múltiples ``QueueHandlers``. "
"Esto es más amigable con los recursos que, por ejemplo, tener versiones "
"enhebradas de las clases de gestores existentes, que consumirían un hilo por "
"gestor sin ningún beneficio particular."
#: ../Doc/howto/logging-cookbook.rst:587
msgid "An example of using these two classes follows (imports omitted)::"
msgstr ""
"Un ejemplo del uso de estas dos clases a continuación (se omiten *imports*)::"
#: ../Doc/howto/logging-cookbook.rst:589
#, python-format
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 ""
#: ../Doc/howto/logging-cookbook.rst:605
msgid "which, when run, will produce:"
msgstr "que, cuando se ejecuta, producirá:"
#: ../Doc/howto/logging-cookbook.rst:607
msgid "MainThread: Look out!"
msgstr ""
#: ../Doc/howto/logging-cookbook.rst:611
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 ""
"Aunque la discusión anterior no se refería específicamente al código "
"asíncrono, sino más bien a los gestores de logging lentos, hay que tener en "
"cuenta que cuando se realiza logging desde código asíncrono, los gestores de "
"red e incluso de archivos podrían dar problemas (bloqueo del bucle de "
"eventos) porque parte del logging se realiza desde los internos de :mod:"
"`asyncio`. Podría ser mejor, si se utiliza cualquier código asíncrono en una "
"aplicación, utilizar el enfoque anterior para el logging, de modo que "
"cualquier código de bloqueo se ejecute sólo en el hilo ``QueueListener``."
#: ../Doc/howto/logging-cookbook.rst:619
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 ""
"Antes de Python 3.5, :class:`QueueListener` siempre pasaba cada mensaje "
"recibido de la cola a cada controlador con el que se inicializaba. (Esto se "
"debió a que se asumió que el filtrado de nivel se realizó en el otro lado, "
"donde se llena la cola). A partir de 3.5, este comportamiento se puede "
"cambiar pasando un argumento de palabra clave ``respect_handler_level=True`` "
"al constructor del oyente . Cuando se hace esto, el oyente compara el nivel "
"de cada mensaje con el nivel del controlador y solo pasa un mensaje a un "
"controlador si es apropiado hacerlo."
#: ../Doc/howto/logging-cookbook.rst:632
msgid "Sending and receiving logging events across a network"
msgstr "Enviar y recibir eventos logging a través de una red"
#: ../Doc/howto/logging-cookbook.rst:634
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 ""
"Supongamos que desea enviar eventos de registro a través de una red y "
"gestionarlos en el extremo receptor. Una forma sencilla de hacer esto es "
"adjuntar una instancia de :class:`SocketHandler` al registrador raíz en el "
"extremo de envío::"
#: ../Doc/howto/logging-cookbook.rst:638
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 ""
#: ../Doc/howto/logging-cookbook.rst:662
msgid ""
"At the receiving end, you can set up a receiver using the :mod:"
"`socketserver` module. Here is a basic working example::"
msgstr ""
"En el extremo receptor, puede configurar un receptor usando el módulo :mod:"
"`socketserver`. Aquí hay un ejemplo básico de trabajo:"
#: ../Doc/howto/logging-cookbook.rst:665
#, python-format
msgid ""
"import pickle\n"
"import logging\n"
"import logging.handlers\n"
"import socketserver\n"
"import struct\n"
"\n"