forked from getlogbook/logbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.py
1325 lines (1092 loc) · 47 KB
/
handlers.py
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
# -*- coding: utf-8 -*-
"""
logbook.handlers
~~~~~~~~~~~~~~~~
The handler interface and builtin handlers.
:copyright: (c) 2010 by Armin Ronacher, Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
import os
import sys
import stat
import errno
import socket
try:
from hashlib import sha1
except ImportError:
from sha import new as sha1
import threading
import traceback
from datetime import datetime, timedelta
from itertools import izip
from threading import Lock
from logbook.base import CRITICAL, ERROR, WARNING, NOTICE, INFO, DEBUG, \
NOTSET, level_name_property, _missing, lookup_level, \
Flags, ContextObject, ContextStackManager
from logbook.helpers import any, rename, F, b, _is_text_stream
DEFAULT_FORMAT_STRING = (
u'[{record.time:%Y-%m-%d %H:%M}] '
u'{record.level_name}: {record.channel}: {record.message}'
)
SYSLOG_FORMAT_STRING = u'{record.channel}: {record.message}'
NTLOG_FORMAT_STRING = u'''\
Message Level: {record.level_name}
Location: {record.filename}:{record.lineno}
Module: {record.module}
Function: {record.func_name}
Exact Time: {record.time:%Y-%m-%d %H:%M:%S}
Event provided Message:
{record.message}
'''
TEST_FORMAT_STRING = \
u'[{record.level_name}] {record.channel}: {record.message}'
MAIL_FORMAT_STRING = u'''\
Subject: {handler.subject}
Message type: {record.level_name}
Location: {record.filename}:{record.lineno}
Module: {record.module}
Function: {record.func_name}
Time: {record.time:%Y-%m-%d %H:%M:%S}
Message:
{record.message}
'''
SYSLOG_PORT = 514
_py3 = sys.version_info >= (3, 0)
def create_syshandler(application_name, level=NOTSET):
"""Creates the handler the operating system provides. On Unix systems
this creates a :class:`SyslogHandler`, on Windows sytems it will
create a :class:`NTEventLogHandler`.
"""
if os.name == 'nt':
return NTEventLogHandler(application_name, level=level)
return SyslogHandler(application_name, level=level)
class _HandlerType(type):
"""The metaclass of handlers injects a destructor if the class has an
overridden close method. This makes it possible that the default
handler class as well as all subclasses that don't need cleanup to be
collected with less overhead.
"""
def __new__(cls, name, bases, d):
# aha, that thing has a custom close method. We will need a magic
# __del__ for it to be called on cleanup.
if bases != (ContextObject,) and 'close' in d and '__del__' not in d \
and not any(hasattr(x, '__del__') for x in bases):
def _magic_del(self):
try:
self.close()
except Exception:
# del is also invoked when init fails, so we better just
# ignore any exception that might be raised here
pass
d['__del__'] = _magic_del
return type.__new__(cls, name, bases, d)
class Handler(ContextObject):
"""Handler instances dispatch logging events to specific destinations.
The base handler class. Acts as a placeholder which defines the Handler
interface. Handlers can optionally use Formatter instances to format
records as desired. By default, no formatter is specified; in this case,
the 'raw' message as determined by record.message is logged.
To bind a handler you can use the :meth:`push_application` and
:meth:`push_thread` methods. This will push the handler on a stack of
handlers. To undo this, use the :meth:`pop_application` and
:meth:`pop_thread` methods::
handler = MyHandler()
handler.push_application()
# all here goes to that handler
handler.pop_application()
By default messages send to that handler will not go to a handler on
an outer level on the stack, if handled. This can be changed by
setting bubbling to `True`. This setup for example would not have
any effect::
handler = NullHandler(bubble=False)
handler.push_application()
Whereas this setup disables all logging for the application::
handler = NullHandler()
handler.push_application()
There are also context managers to setup the handler for the duration
of a `with`-block::
with handler.applicationbound():
...
with handler.threadbound():
...
Because `threadbound` is a common operation, it is aliased to a with
on the handler itself::
with handler:
...
"""
__metaclass__ = _HandlerType
stack_manager = ContextStackManager()
#: a flag for this handler that can be set to `True` for handlers that
#: are consuming log records but are not actually displaying it. This
#: flag is set for the :class:`NullHandler` for instance.
blackhole = False
def __init__(self, level=NOTSET, filter=None, bubble=False):
#: the level for the handler. Defaults to `NOTSET` which
#: consumes all entries.
self.level = lookup_level(level)
#: the formatter to be used on records. This is a function
#: that is passed a log record as first argument and the
#: handler as second and returns something formatted
#: (usually a unicode string)
self.formatter = None
#: the filter to be used with this handler
self.filter = filter
#: the bubble flag of this handler
self.bubble = bubble
level_name = level_name_property()
def format(self, record):
"""Formats a record with the given formatter. If no formatter
is set, the record message is returned. Generally speaking the
return value is most likely a unicode string, but nothing in
the handler interface requires a formatter to return a unicode
string.
The combination of a handler and formatter might have the
formatter return an XML element tree for example.
"""
if self.formatter is None:
return record.message
return self.formatter(record, self)
def should_handle(self, record):
"""Returns `True` if this handler wants to handle the record. The
default implementation checks the level.
"""
return record.level >= self.level
def handle(self, record):
"""Emits the record and falls back. It tries to :meth:`emit` the
record and if that fails, it will call into :meth:`handle_error` with
the record and traceback. This function itself will always emit
when called, even if the logger level is higher than the record's
level.
If this method returns `False` it signals to the calling function that
no recording took place in which case it will automatically bubble.
This should not be used to signal error situations. The default
implementation always returns `True`.
"""
try:
self.emit(record)
except Exception:
self.handle_error(record, sys.exc_info())
return True
def emit(self, record):
"""Emit the specified logging record. This should take the
record and deliver it to whereever the handler sends formatted
log records.
"""
def emit_batch(self, records, reason):
"""Some handlers may internally queue up records and want to forward
them at once to another handler. For example the
:class:`~logbook.more.FingersCrossedHandler` internally buffers
records until a level threshold is reached in which case the buffer
is sent to this method and not :meth:`emit` for each record.
The default behaviour is to call :meth:`emit` for each record in
the buffer, but handlers can use this to optimize log handling. For
instance the mail handler will try to batch up items into one mail
and not to emit mails for each record in the buffer.
Note that unlike :meth:`emit` there is no wrapper method like
:meth:`handle` that does error handling. The reason is that this
is intended to be used by other handlers which are already protected
against internal breakage.
`reason` is a string that specifies the rason why :meth:`emit_batch`
was called, and not :meth:`emit`. The following are valid values::
``'buffer'``
Records were buffered for performance reasons or because the
records were sent to another process and buffering was the only
possible way.
``'escalation'``
Escalation means that records were buffered in case the threshold
was exceeded. In this case, the last record in the list is the
record that triggered the call.
``'group'``
All the records in the list belong to the same logical component
and happened in the same process. For example there was a long
running computation and the handler is invoked with a bunch of
records that happened there. This is similar to the escalation
reason, just that the first one is the significant one, not the
last.
If a subclass overrides this and does not want to handle a specific
reason it must call into the superclass because more reasons might
appear in future releases.
Example implementation::
def emit_batch(self, records, reason):
if reason not in ('escalation', 'group'):
Handler.emit_batch(self, records, reason)
...
"""
for record in records:
self.emit(record)
def close(self):
"""Tidy up any resources used by the handler. This is automatically
called by the destructor of the class as well, but explicit calls are
encouraged. Make sure that multiple calls to close are possible.
"""
def handle_error(self, record, exc_info):
"""Handle errors which occur during an emit() call. The behaviour of
this function depends on the current `errors` setting.
Check :class:`Flags` for more information.
"""
try:
behaviour = Flags.get_flag('errors', 'print')
if behaviour == 'raise':
raise exc_info[0], exc_info[1], exc_info[2]
elif behaviour == 'print':
traceback.print_exception(*(exc_info + (None, sys.stderr)))
sys.stderr.write('Logged from file %s, line %s\n' % (
record.filename, record.lineno))
except IOError:
pass
class NullHandler(Handler):
"""A handler that does nothing, meant to be inserted in a handler chain
with ``bubble=False`` to stop further processing.
"""
blackhole = True
class WrapperHandler(Handler):
"""A class that can wrap another handler and redirect all calls to the
wrapped handler::
handler = WrapperHandler(other_handler)
Subclasses should override the :attr:`_direct_attrs` attribute as
necessary.
"""
#: a set of direct attributes that are not forwarded to the inner
#: handler. This has to be extended as necessary.
_direct_attrs = frozenset(['handler'])
def __init__(self, handler):
self.handler = handler
def __getattr__(self, name):
return getattr(self.handler, name)
def __setattr__(self, name, value):
if name in self._direct_attrs:
return Handler.__setattr__(self, name, value)
setattr(self.handler, name, value)
class StringFormatter(object):
"""Many handlers format the log entries to text format. This is done
by a callable that is passed a log record and returns an unicode
string. The default formatter for this is implemented as a class so
that it becomes possible to hook into every aspect of the formatting
process.
"""
def __init__(self, format_string):
self.format_string = format_string
def _get_format_string(self):
return self._format_string
def _set_format_string(self, value):
self._format_string = value
self._formatter = F(value)
format_string = property(_get_format_string, _set_format_string)
del _get_format_string, _set_format_string
def format_record(self, record, handler):
return self._formatter.format(record=record, handler=handler)
def format_exception(self, record):
return record.formatted_exception
def __call__(self, record, handler):
line = self.format_record(record, handler)
exc = self.format_exception(record)
if exc:
line += u'\n' + exc
return line
class StringFormatterHandlerMixin(object):
"""A mixin for handlers that provides a default integration for the
:class:`~logbook.StringFormatter` class. This is used for all handlers
by default that log text to a destination.
"""
#: a class attribute for the default format string to use if the
#: constructor was invoked with `None`.
default_format_string = DEFAULT_FORMAT_STRING
#: the class to be used for string formatting
formatter_class = StringFormatter
def __init__(self, format_string):
if format_string is None:
format_string = self.default_format_string
#: the currently attached format string as new-style format
#: string.
self.format_string = format_string
def _get_format_string(self):
if isinstance(self.formatter, StringFormatter):
return self.formatter.format_string
def _set_format_string(self, value):
if value is None:
self.formatter = None
else:
self.formatter = self.formatter_class(value)
format_string = property(_get_format_string, _set_format_string)
del _get_format_string, _set_format_string
class HashingHandlerMixin(object):
"""Mixin class for handlers that are hashing records."""
def hash_record_raw(self, record):
"""Returns a hashlib object with the hash of the record."""
hash = sha1()
hash.update(('%d\x00' % record.level).encode('ascii'))
hash.update((record.channel or u'').encode('utf-8') + b('\x00'))
hash.update(record.filename.encode('utf-8') + b('\x00'))
hash.update(b(str(record.lineno)))
return hash
def hash_record(self, record):
"""Returns a hash for a record to keep it apart from other records.
This is used for the `record_limit` feature. By default
The level, channel, filename and location are hashed.
Calls into :meth:`hash_record_raw`.
"""
return self.hash_record_raw(record).hexdigest()
class LimitingHandlerMixin(HashingHandlerMixin):
"""Mixin class for handlers that want to limit emitting records.
In the default setting it delivers all log records but it can be set up
to not send more than n mails for the same record each hour to not
overload an inbox and the network in case a message is triggered multiple
times a minute. The following example limits it to 60 mails an hour::
from datetime import timedelta
handler = MailHandler(record_limit=1,
record_delta=timedelta(minutes=1))
"""
def __init__(self, record_limit, record_delta):
self.record_limit = record_limit
self._limit_lock = Lock()
self._record_limits = {}
if record_delta is None:
record_delta = timedelta(seconds=60)
elif isinstance(record_delta, (int, long, float)):
record_delta = timedelta(seconds=record_delta)
self.record_delta = record_delta
def check_delivery(self, record):
"""Helper function to check if data should be delivered by this
handler. It returns a tuple in the form ``(suppression_count,
allow)``. The first one is the number of items that were not delivered
so far, the second is a boolean flag if a delivery should happen now.
"""
if self.record_limit is None:
return 0, True
hash = self.hash_record(record)
self._limit_lock.acquire()
try:
allow_delivery = None
suppression_count = old_count = 0
first_count = now = datetime.utcnow()
if hash in self._record_limits:
last_count, suppression_count = self._record_limits[hash]
if last_count + self.record_delta < now:
allow_delivery = True
else:
first_count = last_count
old_count = suppression_count
if not suppression_count and \
len(self._record_limits) >= self.max_record_cache:
cache_items = self._record_limits.items()
cache_items.sort()
del cache_items[:int(self._record_limits) \
* self.record_cache_prune]
self._record_limits = dict(cache_items)
self._record_limits[hash] = (first_count, old_count + 1)
if allow_delivery is None:
allow_delivery = old_count < self.record_limit
return suppression_count, allow_delivery
finally:
self._limit_lock.release()
class StreamHandler(Handler, StringFormatterHandlerMixin):
"""a handler class which writes logging records, appropriately formatted,
to a stream. note that this class does not close the stream, as sys.stdout
or sys.stderr may be used.
If a stream handler is used in a `with` statement directly it will
:meth:`close` on exit to support this pattern::
with StreamHandler(my_stream):
pass
.. admonition:: Notes on the encoding
On Python 3, the encoding parameter is only used if a stream was
passed that was opened in binary mode.
"""
def __init__(self, stream, level=NOTSET, format_string=None,
encoding=None, filter=None, bubble=False):
Handler.__init__(self, level, filter, bubble)
StringFormatterHandlerMixin.__init__(self, format_string)
self.encoding = encoding
self.lock = threading.Lock()
if stream is not _missing:
self.stream = stream
def __enter__(self):
return Handler.__enter__(self)
def __exit__(self, exc_type, exc_value, tb):
self.close()
return Handler.__exit__(self, exc_type, exc_value, tb)
def close(self):
"""The default stream handler implementation is not to close
the wrapped stream but to flush it.
"""
self.flush()
def flush(self):
"""Flushes the inner stream."""
if self.stream is not None and hasattr(self.stream, 'flush'):
self.stream.flush()
def format_and_encode(self, record):
"""Formats the record and encodes it to the stream encoding."""
stream = self.stream
rv = self.format(record) + '\n'
if not _py3 or not _is_text_stream(stream):
enc = self.encoding
if enc is None:
enc = getattr(stream, 'encoding', None) or 'utf-8'
rv = rv.encode(enc, 'replace')
return rv
def write(self, item):
"""Writes a bytestring to the stream."""
self.stream.write(item)
def emit(self, record):
self.lock.acquire()
try:
self.write(self.format_and_encode(record))
self.flush()
finally:
self.lock.release()
class FileHandler(StreamHandler):
"""A handler that does the task of opening and closing files for you.
By default the file is opened right away, but you can also `delay`
the open to the point where the first message is written.
This is useful when the handler is used with a
:class:`~logbook.more.FingersCrossedHandler` or something similar.
"""
def __init__(self, filename, mode='a', encoding=None, level=NOTSET,
format_string=None, delay=False, filter=None, bubble=False):
if encoding is None:
encoding = 'utf-8'
StreamHandler.__init__(self, None, level, format_string,
encoding, filter, bubble)
self._filename = filename
self._mode = mode
if delay:
self.stream = None
else:
self._open()
def _open(self, mode=None):
if mode is None:
mode = self._mode
self.stream = open(self._filename, mode)
def write(self, item):
if self.stream is None:
self._open()
if _py3 and isinstance(item, bytes):
self.stream.buffer.write(item)
else:
self.stream.write(item)
def close(self):
if self.stream is not None:
self.flush()
self.stream.close()
self.stream = None
def format_and_encode(self, record):
# encodes based on the stream settings, so the stream has to be
# open at the time this function is called.
if self.stream is None:
self._open()
return StreamHandler.format_and_encode(self, record)
def emit(self, record):
if self.stream is None:
self._open()
StreamHandler.emit(self, record)
class MonitoringFileHandler(FileHandler):
"""A file handler that will check if the file was moved while it was
open. This might happen on POSIX systems if an application like
logrotate moves the logfile over.
Because of different IO concepts on Windows, this handler will not
work on a windows system.
"""
def __init__(self, filename, mode='a', encoding='utf-8', level=NOTSET,
format_string=None, delay=False, filter=None, bubble=False):
FileHandler.__init__(self, filename, mode, encoding, level,
format_string, delay, filter, bubble)
if os.name == 'nt':
raise RuntimeError('MonitoringFileHandler '
'does not support Windows')
self._query_fd()
def _query_fd(self):
if self.stream is None:
self._last_stat = None, None
else:
try:
st = os.stat(self._filename)
except OSError, e:
if e.errno != 2:
raise
self._last_stat = None, None
else:
self._last_stat = st[stat.ST_DEV], st[stat.ST_INO]
def emit(self, record):
last_stat = self._last_stat
self._query_fd()
if last_stat != self._last_stat:
self.close()
FileHandler.emit(self, record)
self._query_fd()
class StderrHandler(StreamHandler):
"""A handler that writes to what is currently at stderr. At the first
glace this appears to just be a :class:`StreamHandler` with the stream
set to :data:`sys.stderr` but there is a difference: if the handler is
created globally and :data:`sys.stderr` changes later, this handler will
point to the current `stderr`, whereas a stream handler would still
point to the old one.
"""
def __init__(self, level=NOTSET, format_string=None, filter=None,
bubble=False):
StreamHandler.__init__(self, _missing, level, format_string,
None, filter, bubble)
@property
def stream(self):
return sys.stderr
class RotatingFileHandlerBase(FileHandler):
"""Baseclass for rotating file handlers.
.. versionchanged:: 0.3
This class was deprecated because the interface is not flexible
enough to implement proper file rotations. The former builtin
subclasses no longer use this baseclass.
"""
def __init__(self, *args, **kwargs):
from warnings import warn
warn(DeprecationWarning('This class is deprecated'))
FileHandler.__init__(self, *args, **kwargs)
def emit(self, record):
self.lock.acquire()
try:
msg = self.format_and_encode(record)
if self.should_rollover(record, msg):
self.perform_rollover()
self.write(msg)
self.flush()
finally:
self.lock.release()
def should_rollover(self, record, formatted_record):
"""Called with the log record and the return value of the
:meth:`format_and_encode` method. The method has then to
return `True` if a rollover should happen or `False`
otherwise.
.. versionchanged:: 0.3
Previously this method was called with the number of bytes
returned by :meth:`format_and_encode`
"""
return False
def perform_rollover(self):
"""Called if :meth:`should_rollover` returns `True` and has
to perform the actual rollover.
"""
class RotatingFileHandler(FileHandler):
"""This handler rotates based on file size. Once the maximum size
is reached it will reopen the file and start with an empty file
again. The old file is moved into a backup copy (named like the
file, but with a ``.backupnumber`` appended to the file. So if
you are logging to ``mail`` the first backup copy is called
``mail.1``.)
The default number of backups is 5. Unlike a similar logger from
the logging package, the backup count is mandatory because just
reopening the file is dangerous as it deletes the log without
asking on rollover.
"""
def __init__(self, filename, mode='a', encoding='utf-8', level=NOTSET,
format_string=None, delay=False, max_size=1024 * 1024,
backup_count=5, filter=None, bubble=False):
FileHandler.__init__(self, filename, mode, encoding, level,
format_string, delay, filter, bubble)
self.max_size = max_size
self.backup_count = backup_count
assert backup_count > 0, 'at least one backup file has to be ' \
'specified'
def should_rollover(self, record, bytes):
self.stream.seek(0, 2)
return self.stream.tell() + bytes >= self.max_size
def perform_rollover(self):
self.stream.close()
for x in xrange(self.backup_count - 1, 0, -1):
src = '%s.%d' % (self._filename, x)
dst = '%s.%d' % (self._filename, x + 1)
try:
rename(src, dst)
except OSError, e:
if e.errno != errno.ENOENT:
raise
rename(self._filename, self._filename + '.1')
self._open('w')
def emit(self, record):
self.lock.acquire()
try:
msg = self.format_and_encode(record)
if self.should_rollover(record, len(msg)):
self.perform_rollover()
self.write(msg)
self.flush()
finally:
self.lock.release()
class TimedRotatingFileHandler(FileHandler):
"""This handler rotates based on dates. It will name the file
after the filename you specify and the `date_format` pattern.
So for example if you configure your handler like this::
handler = TimedRotatingFileHandler('/var/log/foo.log',
date_formnat='%Y-%m-%d')
The filenames for the logfiles will look like this::
/var/log/foo-2010-01-10.log
/var/log/foo-2010-01-11.log
...
By default it will keep all these files around, if you want to limit
them, you can specify a `backup_count`.
"""
def __init__(self, filename, mode='a', encoding='utf-8', level=NOTSET,
format_string=None, date_format='%Y-%m-%d',
backup_count=0, filter=None, bubble=False):
FileHandler.__init__(self, filename, mode, encoding, level,
format_string, True, filter, bubble)
self.date_format = date_format
self.backup_count = backup_count
self._fn_parts = os.path.splitext(os.path.abspath(filename))
self._filename = None
def _get_timed_filename(self, datetime):
return datetime.strftime('-' + self.date_format) \
.join(self._fn_parts)
def should_rollover(self, record):
fn = self._get_timed_filename(record.time)
rv = self._filename is not None and self._filename != fn
# remember the current filename. In case rv is True, the rollover
# performing function will already have the new filename
self._filename = fn
return rv
def files_to_delete(self):
"""Returns a list with the files that have to be deleted when
a rollover occours.
"""
directory = os.path.dirname(self._filename)
files = []
for filename in os.listdir(directory):
filename = os.path.join(directory, filename)
if filename.startswith(self._fn_parts[0] + '-') and \
filename.endswith(self._fn_parts[1]):
files.append((os.path.getmtime(filename), filename))
files.sort()
return files[:-self.backup_count + 1]
def perform_rollover(self):
self.stream.close()
if self.backup_count > 0:
for time, filename in self.files_to_delete():
os.remove(filename)
self._open('w')
def emit(self, record):
self.lock.acquire()
try:
if self.should_rollover(record):
self.perform_rollover()
self.write(self.format_and_encode(record))
self.flush()
finally:
self.lock.release()
class TestHandler(Handler, StringFormatterHandlerMixin):
"""Like a stream handler but keeps the values in memory. This
logger provides some ways to test for the records in memory.
Example usage::
def my_test():
with logbook.TestHandler() as handler:
logger.warn('A warning')
assert logger.has_warning('A warning')
...
"""
default_format_string = TEST_FORMAT_STRING
def __init__(self, level=NOTSET, format_string=None, filter=None,
bubble=False):
Handler.__init__(self, level, filter, bubble)
StringFormatterHandlerMixin.__init__(self, format_string)
#: captures the :class:`LogRecord`\s as instances
self.records = []
self._formatted_records = []
self._formatted_record_cache = []
def close(self):
"""Close all records down when the handler is closed."""
for record in self.records:
record.close()
def emit(self, record):
# keep records open because we will want to examine them after the
# call to the emit function. If we don't do that, the traceback
# attribute and other things will already be removed.
record.keep_open = True
self.records.append(record)
@property
def formatted_records(self):
"""Captures the formatted log records as unicode strings."""
if len(self._formatted_records) != self.records or \
any(r1 != r2 for r1, (r2, f) in
izip(self.records, self._formatted_records)):
self._formatted_records = map(self.format, self.records)
self._formatted_record_cache = list(self.records)
return self._formatted_records
@property
def has_criticals(self):
"""`True` if any :data:`CRITICAL` records were found."""
return any(r.level == CRITICAL for r in self.records)
@property
def has_errors(self):
"""`True` if any :data:`ERROR` records were found."""
return any(r.level == ERROR for r in self.records)
@property
def has_warnings(self):
"""`True` if any :data:`WARNING` records were found."""
return any(r.level == WARNING for r in self.records)
@property
def has_notices(self):
"""`True` if any :data:`NOTICE` records were found."""
return any(r.level == NOTICE for r in self.records)
@property
def has_infos(self):
"""`True` if any :data:`INFO` records were found."""
return any(r.level == INFO for r in self.records)
@property
def has_debugs(self):
"""`True` if any :data:`DEBUG` records were found."""
return any(r.level == DEBUG for r in self.records)
def has_critical(self, *args, **kwargs):
"""`True` if a specific :data:`CRITICAL` log record exists.
See :ref:`probe-log-records` for more information.
"""
kwargs['level'] = CRITICAL
return self._test_for(*args, **kwargs)
def has_error(self, *args, **kwargs):
"""`True` if a specific :data:`ERROR` log record exists.
See :ref:`probe-log-records` for more information.
"""
kwargs['level'] = ERROR
return self._test_for(*args, **kwargs)
def has_warning(self, *args, **kwargs):
"""`True` if a specific :data:`WARNING` log record exists.
See :ref:`probe-log-records` for more information.
"""
kwargs['level'] = WARNING
return self._test_for(*args, **kwargs)
def has_notice(self, *args, **kwargs):
"""`True` if a specific :data:`NOTICE` log record exists.
See :ref:`probe-log-records` for more information.
"""
kwargs['level'] = NOTICE
return self._test_for(*args, **kwargs)
def has_info(self, *args, **kwargs):
"""`True` if a specific :data:`INFO` log record exists.
See :ref:`probe-log-records` for more information.
"""
kwargs['level'] = INFO
return self._test_for(*args, **kwargs)
def has_debug(self, *args, **kwargs):
"""`True` if a specific :data:`DEBUG` log record exists.
See :ref:`probe-log-records` for more information.
"""
kwargs['level'] = DEBUG
return self._test_for(*args, **kwargs)
def _test_for(self, message=None, channel=None, level=None):
for record in self.records:
if level is not None and record.level != level:
continue
if channel is not None and record.channel != channel:
continue
if message is not None and record.message != message:
continue
return True
return False
class MailHandler(Handler, StringFormatterHandlerMixin,
LimitingHandlerMixin):
"""A handler that sends error mails. The format string used by this
handler are the contents of the mail plus the headers. This is handy
if you want to use a custom subject or ``X-`` header::
handler = MailHandler(format_string='''\
Subject: {record.level_name} on My Application
{record.message}
''')
This handler will always emit text-only mails for maximum portability and
best performance.
In the default setting it delivers all log records but it can be set up
to not send more than n mails for the same record each hour to not
overload an inbox and the network in case a message is triggered multiple
times a minute. The following example limits it to 60 mails an hour::
from datetime import timedelta
handler = MailHandler(record_limit=1,
record_delta=timedelta(minutes=1))
The default timedelta is 60 seconds (one minute).
The mail handler is sending mails in a blocking manner. If you are not
using some centralized system for logging these messages (with the help
of ZeroMQ or others) and the logging system slows you down you can
wrap the handler in a :class:`logbook.queues.ThreadedWrapperHandler`
that will then send the mails in a background thread.
"""
default_format_string = MAIL_FORMAT_STRING
default_subject = u'Server Error in Application'