debuggers.hg

view tools/python/logging/logging-0.4.9.2/logging/handlers.py @ 0:7d21f7218375

Exact replica of unstable on 051908 + README-this
author Mukesh Rathor
date Mon May 19 15:34:57 2008 -0700 (2008-05-19)
parents
children dae98734f12e
line source
1 # Copyright 2001-2004 by Vinay Sajip. All Rights Reserved.
2 #
3 # Permission to use, copy, modify, and distribute this software and its
4 # documentation for any purpose and without fee is hereby granted,
5 # provided that the above copyright notice appear in all copies and that
6 # both that copyright notice and this permission notice appear in
7 # supporting documentation, and that the name of Vinay Sajip
8 # not be used in advertising or publicity pertaining to distribution
9 # of the software without specific, written prior permission.
10 # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
11 # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
12 # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
13 # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
14 # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
15 # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 """
18 Additional handlers for the logging package for Python. The core package is
19 based on PEP 282 and comments thereto in comp.lang.python, and influenced by
20 Apache's log4j system.
22 Should work under Python versions >= 1.5.2, except that source line
23 information is not available unless 'sys._getframe()' is.
25 Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved.
27 To use, simply 'import logging' and log away!
28 """
30 import sys, logging, socket, types, os, string, cPickle, struct, time
32 from SocketServer import ThreadingTCPServer, StreamRequestHandler
34 #
35 # Some constants...
36 #
38 DEFAULT_TCP_LOGGING_PORT = 9020
39 DEFAULT_UDP_LOGGING_PORT = 9021
40 DEFAULT_HTTP_LOGGING_PORT = 9022
41 DEFAULT_SOAP_LOGGING_PORT = 9023
42 SYSLOG_UDP_PORT = 514
45 class RotatingFileHandler(logging.FileHandler):
46 def __init__(self, filename, mode="a", maxBytes=0, backupCount=0):
47 """
48 Open the specified file and use it as the stream for logging.
50 By default, the file grows indefinitely. You can specify particular
51 values of maxBytes and backupCount to allow the file to rollover at
52 a predetermined size.
54 Rollover occurs whenever the current log file is nearly maxBytes in
55 length. If backupCount is >= 1, the system will successively create
56 new files with the same pathname as the base file, but with extensions
57 ".1", ".2" etc. appended to it. For example, with a backupCount of 5
58 and a base file name of "app.log", you would get "app.log",
59 "app.log.1", "app.log.2", ... through to "app.log.5". The file being
60 written to is always "app.log" - when it gets filled up, it is closed
61 and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc.
62 exist, then they are renamed to "app.log.2", "app.log.3" etc.
63 respectively.
65 If maxBytes is zero, rollover never occurs.
66 """
67 logging.FileHandler.__init__(self, filename, mode)
68 self.maxBytes = maxBytes
69 self.backupCount = backupCount
70 if maxBytes > 0:
71 self.mode = "a"
73 def doRollover(self):
74 """
75 Do a rollover, as described in __init__().
76 """
78 self.stream.close()
79 if self.backupCount > 0:
80 for i in range(self.backupCount - 1, 0, -1):
81 sfn = "%s.%d" % (self.baseFilename, i)
82 dfn = "%s.%d" % (self.baseFilename, i + 1)
83 if os.path.exists(sfn):
84 #print "%s -> %s" % (sfn, dfn)
85 if os.path.exists(dfn):
86 os.remove(dfn)
87 os.rename(sfn, dfn)
88 dfn = self.baseFilename + ".1"
89 if os.path.exists(dfn):
90 os.remove(dfn)
91 os.rename(self.baseFilename, dfn)
92 #print "%s -> %s" % (self.baseFilename, dfn)
93 self.stream = open(self.baseFilename, "w")
95 def emit(self, record):
96 """
97 Emit a record.
99 Output the record to the file, catering for rollover as described
100 in doRollover().
101 """
102 if self.maxBytes > 0: # are we rolling over?
103 msg = "%s\n" % self.format(record)
104 self.stream.seek(0, 2) #due to non-posix-compliant Windows feature
105 if self.stream.tell() + len(msg) >= self.maxBytes:
106 self.doRollover()
107 logging.FileHandler.emit(self, record)
110 class SocketHandler(logging.Handler):
111 """
112 A handler class which writes logging records, in pickle format, to
113 a streaming socket. The socket is kept open across logging calls.
114 If the peer resets it, an attempt is made to reconnect on the next call.
115 The pickle which is sent is that of the LogRecord's attribute dictionary
116 (__dict__), so that the receiver does not need to have the logging module
117 installed in order to process the logging event.
119 To unpickle the record at the receiving end into a LogRecord, use the
120 makeLogRecord function.
121 """
123 def __init__(self, host, port):
124 """
125 Initializes the handler with a specific host address and port.
127 The attribute 'closeOnError' is set to 1 - which means that if
128 a socket error occurs, the socket is silently closed and then
129 reopened on the next logging call.
130 """
131 logging.Handler.__init__(self)
132 self.host = host
133 self.port = port
134 self.sock = None
135 self.closeOnError = 0
136 self.retryTime = None
137 #
138 # Exponential backoff parameters.
139 #
140 self.retryStart = 1.0
141 self.retryMax = 30.0
142 self.retryFactor = 2.0
144 def makeSocket(self):
145 """
146 A factory method which allows subclasses to define the precise
147 type of socket they want.
148 """
149 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
150 s.connect((self.host, self.port))
151 return s
153 def createSocket(self):
154 """
155 Try to create a socket, using an exponential backoff with
156 a max retry time. Thanks to Robert Olson for the original patch
157 (SF #815911) which has been slightly refactored.
158 """
159 now = time.time()
160 # Either retryTime is None, in which case this
161 # is the first time back after a disconnect, or
162 # we've waited long enough.
163 if self.retryTime is None:
164 attempt = 1
165 else:
166 attempt = (now >= self.retryTime)
167 if attempt:
168 try:
169 self.sock = self.makeSocket()
170 self.retryTime = None # next time, no delay before trying
171 except:
172 #Creation failed, so set the retry time and return.
173 if self.retryTime is None:
174 self.retryPeriod = self.retryStart
175 else:
176 self.retryPeriod = self.retryPeriod * self.retryFactor
177 if self.retryPeriod > self.retryMax:
178 self.retryPeriod = self.retryMax
179 self.retryTime = now + self.retryPeriod
181 def send(self, s):
182 """
183 Send a pickled string to the socket.
185 This function allows for partial sends which can happen when the
186 network is busy.
187 """
188 if self.sock is None:
189 self.createSocket()
190 #self.sock can be None either because we haven't reached the retry
191 #time yet, or because we have reached the retry time and retried,
192 #but are still unable to connect.
193 if self.sock:
194 try:
195 if hasattr(self.sock, "sendall"):
196 self.sock.sendall(s)
197 else:
198 sentsofar = 0
199 left = len(s)
200 while left > 0:
201 sent = self.sock.send(s[sentsofar:])
202 sentsofar = sentsofar + sent
203 left = left - sent
204 except socket.error:
205 self.sock.close()
206 self.sock = None # so we can call createSocket next time
208 def makePickle(self, record):
209 """
210 Pickles the record in binary format with a length prefix, and
211 returns it ready for transmission across the socket.
212 """
213 ei = record.exc_info
214 if ei:
215 dummy = self.format(record) # just to get traceback text into record.exc_text
216 record.exc_info = None # to avoid Unpickleable error
217 s = cPickle.dumps(record.__dict__, 1)
218 if ei:
219 record.exc_info = ei # for next handler
220 slen = struct.pack(">L", len(s))
221 return slen + s
223 def handleError(self, record):
224 """
225 Handle an error during logging.
227 An error has occurred during logging. Most likely cause -
228 connection lost. Close the socket so that we can retry on the
229 next event.
230 """
231 if self.closeOnError and self.sock:
232 self.sock.close()
233 self.sock = None #try to reconnect next time
234 else:
235 logging.Handler.handleError(self, record)
237 def emit(self, record):
238 """
239 Emit a record.
241 Pickles the record and writes it to the socket in binary format.
242 If there is an error with the socket, silently drop the packet.
243 If there was a problem with the socket, re-establishes the
244 socket.
245 """
246 try:
247 s = self.makePickle(record)
248 self.send(s)
249 except:
250 self.handleError(record)
252 def close(self):
253 """
254 Closes the socket.
255 """
256 if self.sock:
257 self.sock.close()
258 self.sock = None
259 logging.Handler.close(self)
261 class DatagramHandler(SocketHandler):
262 """
263 A handler class which writes logging records, in pickle format, to
264 a datagram socket. The pickle which is sent is that of the LogRecord's
265 attribute dictionary (__dict__), so that the receiver does not need to
266 have the logging module installed in order to process the logging event.
268 To unpickle the record at the receiving end into a LogRecord, use the
269 makeLogRecord function.
271 """
272 def __init__(self, host, port):
273 """
274 Initializes the handler with a specific host address and port.
275 """
276 SocketHandler.__init__(self, host, port)
277 self.closeOnError = 0
279 def makeSocket(self):
280 """
281 The factory method of SocketHandler is here overridden to create
282 a UDP socket (SOCK_DGRAM).
283 """
284 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
285 return s
287 def send(self, s):
288 """
289 Send a pickled string to a socket.
291 This function no longer allows for partial sends which can happen
292 when the network is busy - UDP does not guarantee delivery and
293 can deliver packets out of sequence.
294 """
295 self.sock.sendto(s, (self.host, self.port))
297 class SysLogHandler(logging.Handler):
298 """
299 A handler class which sends formatted logging records to a syslog
300 server. Based on Sam Rushing's syslog module:
301 http://www.nightmare.com/squirl/python-ext/misc/syslog.py
302 Contributed by Nicolas Untz (after which minor refactoring changes
303 have been made).
304 """
306 # from <linux/sys/syslog.h>:
307 # ======================================================================
308 # priorities/facilities are encoded into a single 32-bit quantity, where
309 # the bottom 3 bits are the priority (0-7) and the top 28 bits are the
310 # facility (0-big number). Both the priorities and the facilities map
311 # roughly one-to-one to strings in the syslogd(8) source code. This
312 # mapping is included in this file.
313 #
314 # priorities (these are ordered)
316 LOG_EMERG = 0 # system is unusable
317 LOG_ALERT = 1 # action must be taken immediately
318 LOG_CRIT = 2 # critical conditions
319 LOG_ERR = 3 # error conditions
320 LOG_WARNING = 4 # warning conditions
321 LOG_NOTICE = 5 # normal but significant condition
322 LOG_INFO = 6 # informational
323 LOG_DEBUG = 7 # debug-level messages
325 # facility codes
326 LOG_KERN = 0 # kernel messages
327 LOG_USER = 1 # random user-level messages
328 LOG_MAIL = 2 # mail system
329 LOG_DAEMON = 3 # system daemons
330 LOG_AUTH = 4 # security/authorization messages
331 LOG_SYSLOG = 5 # messages generated internally by syslogd
332 LOG_LPR = 6 # line printer subsystem
333 LOG_NEWS = 7 # network news subsystem
334 LOG_UUCP = 8 # UUCP subsystem
335 LOG_CRON = 9 # clock daemon
336 LOG_AUTHPRIV = 10 # security/authorization messages (private)
338 # other codes through 15 reserved for system use
339 LOG_LOCAL0 = 16 # reserved for local use
340 LOG_LOCAL1 = 17 # reserved for local use
341 LOG_LOCAL2 = 18 # reserved for local use
342 LOG_LOCAL3 = 19 # reserved for local use
343 LOG_LOCAL4 = 20 # reserved for local use
344 LOG_LOCAL5 = 21 # reserved for local use
345 LOG_LOCAL6 = 22 # reserved for local use
346 LOG_LOCAL7 = 23 # reserved for local use
348 priority_names = {
349 "alert": LOG_ALERT,
350 "crit": LOG_CRIT,
351 "critical": LOG_CRIT,
352 "debug": LOG_DEBUG,
353 "emerg": LOG_EMERG,
354 "err": LOG_ERR,
355 "error": LOG_ERR, # DEPRECATED
356 "info": LOG_INFO,
357 "notice": LOG_NOTICE,
358 "panic": LOG_EMERG, # DEPRECATED
359 "warn": LOG_WARNING, # DEPRECATED
360 "warning": LOG_WARNING,
361 }
363 facility_names = {
364 "auth": LOG_AUTH,
365 "authpriv": LOG_AUTHPRIV,
366 "cron": LOG_CRON,
367 "daemon": LOG_DAEMON,
368 "kern": LOG_KERN,
369 "lpr": LOG_LPR,
370 "mail": LOG_MAIL,
371 "news": LOG_NEWS,
372 "security": LOG_AUTH, # DEPRECATED
373 "syslog": LOG_SYSLOG,
374 "user": LOG_USER,
375 "uucp": LOG_UUCP,
376 "local0": LOG_LOCAL0,
377 "local1": LOG_LOCAL1,
378 "local2": LOG_LOCAL2,
379 "local3": LOG_LOCAL3,
380 "local4": LOG_LOCAL4,
381 "local5": LOG_LOCAL5,
382 "local6": LOG_LOCAL6,
383 "local7": LOG_LOCAL7,
384 }
386 def __init__(self, address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER):
387 """
388 Initialize a handler.
390 If address is specified as a string, UNIX socket is used.
391 If facility is not specified, LOG_USER is used.
392 """
393 logging.Handler.__init__(self)
395 self.address = address
396 self.facility = facility
397 if type(address) == types.StringType:
398 self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
399 # syslog may require either DGRAM or STREAM sockets
400 try:
401 self.socket.connect(address)
402 except socket.error:
403 self.socket.close()
404 self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
405 self.socket.connect(address)
406 self.unixsocket = 1
407 else:
408 self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
409 self.unixsocket = 0
411 self.formatter = None
413 # curious: when talking to the unix-domain '/dev/log' socket, a
414 # zero-terminator seems to be required. this string is placed
415 # into a class variable so that it can be overridden if
416 # necessary.
417 log_format_string = '<%d>%s\000'
419 def encodePriority (self, facility, priority):
420 """
421 Encode the facility and priority. You can pass in strings or
422 integers - if strings are passed, the facility_names and
423 priority_names mapping dictionaries are used to convert them to
424 integers.
425 """
426 if type(facility) == types.StringType:
427 facility = self.facility_names[facility]
428 if type(priority) == types.StringType:
429 priority = self.priority_names[priority]
430 return (facility << 3) | priority
432 def close (self):
433 """
434 Closes the socket.
435 """
436 if self.unixsocket:
437 self.socket.close()
438 logging.Handler.close(self)
440 def emit(self, record):
441 """
442 Emit a record.
444 The record is formatted, and then sent to the syslog server. If
445 exception information is present, it is NOT sent to the server.
446 """
447 msg = self.format(record)
448 """
449 We need to convert record level to lowercase, maybe this will
450 change in the future.
451 """
452 msg = self.log_format_string % (
453 self.encodePriority(self.facility,
454 string.lower(record.levelname)),
455 msg)
456 try:
457 if self.unixsocket:
458 self.socket.send(msg)
459 else:
460 self.socket.sendto(msg, self.address)
461 except:
462 self.handleError(record)
464 class SMTPHandler(logging.Handler):
465 """
466 A handler class which sends an SMTP email for each logging event.
467 """
468 def __init__(self, mailhost, fromaddr, toaddrs, subject):
469 """
470 Initialize the handler.
472 Initialize the instance with the from and to addresses and subject
473 line of the email. To specify a non-standard SMTP port, use the
474 (host, port) tuple format for the mailhost argument.
475 """
476 logging.Handler.__init__(self)
477 if type(mailhost) == types.TupleType:
478 host, port = mailhost
479 self.mailhost = host
480 self.mailport = port
481 else:
482 self.mailhost = mailhost
483 self.mailport = None
484 self.fromaddr = fromaddr
485 if type(toaddrs) == types.StringType:
486 toaddrs = [toaddrs]
487 self.toaddrs = toaddrs
488 self.subject = subject
490 def getSubject(self, record):
491 """
492 Determine the subject for the email.
494 If you want to specify a subject line which is record-dependent,
495 override this method.
496 """
497 return self.subject
499 weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
501 monthname = [None,
502 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
503 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
505 def date_time(self):
506 """Return the current date and time formatted for a MIME header."""
507 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(time.time())
508 s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
509 self.weekdayname[wd],
510 day, self.monthname[month], year,
511 hh, mm, ss)
512 return s
514 def emit(self, record):
515 """
516 Emit a record.
518 Format the record and send it to the specified addressees.
519 """
520 try:
521 import smtplib
522 port = self.mailport
523 if not port:
524 port = smtplib.SMTP_PORT
525 smtp = smtplib.SMTP(self.mailhost, port)
526 msg = self.format(record)
527 msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
528 self.fromaddr,
529 string.join(self.toaddrs, ","),
530 self.getSubject(record),
531 self.date_time(), msg)
532 smtp.sendmail(self.fromaddr, self.toaddrs, msg)
533 smtp.quit()
534 except:
535 self.handleError(record)
537 class NTEventLogHandler(logging.Handler):
538 """
539 A handler class which sends events to the NT Event Log. Adds a
540 registry entry for the specified application name. If no dllname is
541 provided, win32service.pyd (which contains some basic message
542 placeholders) is used. Note that use of these placeholders will make
543 your event logs big, as the entire message source is held in the log.
544 If you want slimmer logs, you have to pass in the name of your own DLL
545 which contains the message definitions you want to use in the event log.
546 """
547 def __init__(self, appname, dllname=None, logtype="Application"):
548 logging.Handler.__init__(self)
549 try:
550 import win32evtlogutil, win32evtlog
551 self.appname = appname
552 self._welu = win32evtlogutil
553 if not dllname:
554 dllname = os.path.split(self._welu.__file__)
555 dllname = os.path.split(dllname[0])
556 dllname = os.path.join(dllname[0], r'win32service.pyd')
557 self.dllname = dllname
558 self.logtype = logtype
559 self._welu.AddSourceToRegistry(appname, dllname, logtype)
560 self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE
561 self.typemap = {
562 logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE,
563 logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE,
564 logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE,
565 logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE,
566 logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE,
567 }
568 except ImportError:
569 print "The Python Win32 extensions for NT (service, event "\
570 "logging) appear not to be available."
571 self._welu = None
573 def getMessageID(self, record):
574 """
575 Return the message ID for the event record. If you are using your
576 own messages, you could do this by having the msg passed to the
577 logger being an ID rather than a formatting string. Then, in here,
578 you could use a dictionary lookup to get the message ID. This
579 version returns 1, which is the base message ID in win32service.pyd.
580 """
581 return 1
583 def getEventCategory(self, record):
584 """
585 Return the event category for the record.
587 Override this if you want to specify your own categories. This version
588 returns 0.
589 """
590 return 0
592 def getEventType(self, record):
593 """
594 Return the event type for the record.
596 Override this if you want to specify your own types. This version does
597 a mapping using the handler's typemap attribute, which is set up in
598 __init__() to a dictionary which contains mappings for DEBUG, INFO,
599 WARNING, ERROR and CRITICAL. If you are using your own levels you will
600 either need to override this method or place a suitable dictionary in
601 the handler's typemap attribute.
602 """
603 return self.typemap.get(record.levelno, self.deftype)
605 def emit(self, record):
606 """
607 Emit a record.
609 Determine the message ID, event category and event type. Then
610 log the message in the NT event log.
611 """
612 if self._welu:
613 try:
614 id = self.getMessageID(record)
615 cat = self.getEventCategory(record)
616 type = self.getEventType(record)
617 msg = self.format(record)
618 self._welu.ReportEvent(self.appname, id, cat, type, [msg])
619 except:
620 self.handleError(record)
622 def close(self):
623 """
624 Clean up this handler.
626 You can remove the application name from the registry as a
627 source of event log entries. However, if you do this, you will
628 not be able to see the events as you intended in the Event Log
629 Viewer - it needs to be able to access the registry to get the
630 DLL name.
631 """
632 #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype)
633 logging.Handler.close(self)
635 class HTTPHandler(logging.Handler):
636 """
637 A class which sends records to a Web server, using either GET or
638 POST semantics.
639 """
640 def __init__(self, host, url, method="GET"):
641 """
642 Initialize the instance with the host, the request URL, and the method
643 ("GET" or "POST")
644 """
645 logging.Handler.__init__(self)
646 method = string.upper(method)
647 if method not in ["GET", "POST"]:
648 raise ValueError, "method must be GET or POST"
649 self.host = host
650 self.url = url
651 self.method = method
653 def mapLogRecord(self, record):
654 """
655 Default implementation of mapping the log record into a dict
656 that is sent as the CGI data. Overwrite in your class.
657 Contributed by Franz Glasner.
658 """
659 return record.__dict__
661 def emit(self, record):
662 """
663 Emit a record.
665 Send the record to the Web server as an URL-encoded dictionary
666 """
667 try:
668 import httplib, urllib
669 h = httplib.HTTP(self.host)
670 url = self.url
671 data = urllib.urlencode(self.mapLogRecord(record))
672 if self.method == "GET":
673 if (string.find(url, '?') >= 0):
674 sep = '&'
675 else:
676 sep = '?'
677 url = url + "%c%s" % (sep, data)
678 h.putrequest(self.method, url)
679 if self.method == "POST":
680 h.putheader("Content-length", str(len(data)))
681 h.endheaders()
682 if self.method == "POST":
683 h.send(data)
684 h.getreply() #can't do anything with the result
685 except:
686 self.handleError(record)
688 class BufferingHandler(logging.Handler):
689 """
690 A handler class which buffers logging records in memory. Whenever each
691 record is added to the buffer, a check is made to see if the buffer should
692 be flushed. If it should, then flush() is expected to do what's needed.
693 """
694 def __init__(self, capacity):
695 """
696 Initialize the handler with the buffer size.
697 """
698 logging.Handler.__init__(self)
699 self.capacity = capacity
700 self.buffer = []
702 def shouldFlush(self, record):
703 """
704 Should the handler flush its buffer?
706 Returns true if the buffer is up to capacity. This method can be
707 overridden to implement custom flushing strategies.
708 """
709 return (len(self.buffer) >= self.capacity)
711 def emit(self, record):
712 """
713 Emit a record.
715 Append the record. If shouldFlush() tells us to, call flush() to process
716 the buffer.
717 """
718 self.buffer.append(record)
719 if self.shouldFlush(record):
720 self.flush()
722 def flush(self):
723 """
724 Override to implement custom flushing behaviour.
726 This version just zaps the buffer to empty.
727 """
728 self.buffer = []
730 def close(self):
731 """
732 Close the handler.
734 This version just flushes and chains to the parent class' close().
735 """
736 self.flush()
737 logging.Handler.close(self)
739 class MemoryHandler(BufferingHandler):
740 """
741 A handler class which buffers logging records in memory, periodically
742 flushing them to a target handler. Flushing occurs whenever the buffer
743 is full, or when an event of a certain severity or greater is seen.
744 """
745 def __init__(self, capacity, flushLevel=logging.ERROR, target=None):
746 """
747 Initialize the handler with the buffer size, the level at which
748 flushing should occur and an optional target.
750 Note that without a target being set either here or via setTarget(),
751 a MemoryHandler is no use to anyone!
752 """
753 BufferingHandler.__init__(self, capacity)
754 self.flushLevel = flushLevel
755 self.target = target
757 def shouldFlush(self, record):
758 """
759 Check for buffer full or a record at the flushLevel or higher.
760 """
761 return (len(self.buffer) >= self.capacity) or \
762 (record.levelno >= self.flushLevel)
764 def setTarget(self, target):
765 """
766 Set the target handler for this handler.
767 """
768 self.target = target
770 def flush(self):
771 """
772 For a MemoryHandler, flushing means just sending the buffered
773 records to the target, if there is one. Override if you want
774 different behaviour.
775 """
776 if self.target:
777 for record in self.buffer:
778 self.target.handle(record)
779 self.buffer = []
781 def close(self):
782 """
783 Flush, set the target to None and lose the buffer.
784 """
785 self.flush()
786 self.target = None
787 BufferingHandler.close(self)