Removed buggy exception handling in doRollover of rotating file handlers. Exceptions...
[python.git] / Lib / logging / handlers.py
blob70bd5d4faecfc44875020f44a9e68e3605783a55
1 # Copyright 2001-2005 by Vinay Sajip. All Rights Reserved.
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, glob
32 try:
33 import codecs
34 except ImportError:
35 codecs = None
38 # Some constants...
41 DEFAULT_TCP_LOGGING_PORT = 9020
42 DEFAULT_UDP_LOGGING_PORT = 9021
43 DEFAULT_HTTP_LOGGING_PORT = 9022
44 DEFAULT_SOAP_LOGGING_PORT = 9023
45 SYSLOG_UDP_PORT = 514
47 _MIDNIGHT = 24 * 60 * 60 # number of seconds in a day
49 class BaseRotatingHandler(logging.FileHandler):
50 """
51 Base class for handlers that rotate log files at a certain point.
52 Not meant to be instantiated directly. Instead, use RotatingFileHandler
53 or TimedRotatingFileHandler.
54 """
55 def __init__(self, filename, mode, encoding=None):
56 """
57 Use the specified filename for streamed logging
58 """
59 if codecs is None:
60 encoding = None
61 logging.FileHandler.__init__(self, filename, mode, encoding)
62 self.mode = mode
63 self.encoding = encoding
65 def emit(self, record):
66 """
67 Emit a record.
69 Output the record to the file, catering for rollover as described
70 in doRollover().
71 """
72 try:
73 if self.shouldRollover(record):
74 self.doRollover()
75 logging.FileHandler.emit(self, record)
76 except (KeyboardInterrupt, SystemExit):
77 raise
78 except:
79 self.handleError(record)
81 class RotatingFileHandler(BaseRotatingHandler):
82 """
83 Handler for logging to a set of files, which switches from one file
84 to the next when the current file reaches a certain size.
85 """
86 def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None):
87 """
88 Open the specified file and use it as the stream for logging.
90 By default, the file grows indefinitely. You can specify particular
91 values of maxBytes and backupCount to allow the file to rollover at
92 a predetermined size.
94 Rollover occurs whenever the current log file is nearly maxBytes in
95 length. If backupCount is >= 1, the system will successively create
96 new files with the same pathname as the base file, but with extensions
97 ".1", ".2" etc. appended to it. For example, with a backupCount of 5
98 and a base file name of "app.log", you would get "app.log",
99 "app.log.1", "app.log.2", ... through to "app.log.5". The file being
100 written to is always "app.log" - when it gets filled up, it is closed
101 and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc.
102 exist, then they are renamed to "app.log.2", "app.log.3" etc.
103 respectively.
105 If maxBytes is zero, rollover never occurs.
107 if maxBytes > 0:
108 mode = 'a' # doesn't make sense otherwise!
109 BaseRotatingHandler.__init__(self, filename, mode, encoding)
110 self.maxBytes = maxBytes
111 self.backupCount = backupCount
113 def doRollover(self):
115 Do a rollover, as described in __init__().
118 self.stream.close()
119 if self.backupCount > 0:
120 for i in range(self.backupCount - 1, 0, -1):
121 sfn = "%s.%d" % (self.baseFilename, i)
122 dfn = "%s.%d" % (self.baseFilename, i + 1)
123 if os.path.exists(sfn):
124 #print "%s -> %s" % (sfn, dfn)
125 if os.path.exists(dfn):
126 os.remove(dfn)
127 os.rename(sfn, dfn)
128 dfn = self.baseFilename + ".1"
129 if os.path.exists(dfn):
130 os.remove(dfn)
131 os.rename(self.baseFilename, dfn)
132 #print "%s -> %s" % (self.baseFilename, dfn)
133 if self.encoding:
134 self.stream = codecs.open(self.baseFilename, 'w', self.encoding)
135 else:
136 self.stream = open(self.baseFilename, 'w')
138 def shouldRollover(self, record):
140 Determine if rollover should occur.
142 Basically, see if the supplied record would cause the file to exceed
143 the size limit we have.
145 if self.maxBytes > 0: # are we rolling over?
146 msg = "%s\n" % self.format(record)
147 self.stream.seek(0, 2) #due to non-posix-compliant Windows feature
148 if self.stream.tell() + len(msg) >= self.maxBytes:
149 return 1
150 return 0
152 class TimedRotatingFileHandler(BaseRotatingHandler):
154 Handler for logging to a file, rotating the log file at certain timed
155 intervals.
157 If backupCount is > 0, when rollover is done, no more than backupCount
158 files are kept - the oldest ones are deleted.
160 def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None):
161 BaseRotatingHandler.__init__(self, filename, 'a', encoding)
162 self.when = string.upper(when)
163 self.backupCount = backupCount
164 # Calculate the real rollover interval, which is just the number of
165 # seconds between rollovers. Also set the filename suffix used when
166 # a rollover occurs. Current 'when' events supported:
167 # S - Seconds
168 # M - Minutes
169 # H - Hours
170 # D - Days
171 # midnight - roll over at midnight
172 # W{0-6} - roll over on a certain day; 0 - Monday
174 # Case of the 'when' specifier is not important; lower or upper case
175 # will work.
176 currentTime = int(time.time())
177 if self.when == 'S':
178 self.interval = 1 # one second
179 self.suffix = "%Y-%m-%d_%H-%M-%S"
180 elif self.when == 'M':
181 self.interval = 60 # one minute
182 self.suffix = "%Y-%m-%d_%H-%M"
183 elif self.when == 'H':
184 self.interval = 60 * 60 # one hour
185 self.suffix = "%Y-%m-%d_%H"
186 elif self.when == 'D' or self.when == 'MIDNIGHT':
187 self.interval = 60 * 60 * 24 # one day
188 self.suffix = "%Y-%m-%d"
189 elif self.when.startswith('W'):
190 self.interval = 60 * 60 * 24 * 7 # one week
191 if len(self.when) != 2:
192 raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when)
193 if self.when[1] < '0' or self.when[1] > '6':
194 raise ValueError("Invalid day specified for weekly rollover: %s" % self.when)
195 self.dayOfWeek = int(self.when[1])
196 self.suffix = "%Y-%m-%d"
197 else:
198 raise ValueError("Invalid rollover interval specified: %s" % self.when)
200 self.interval = self.interval * interval # multiply by units requested
201 self.rolloverAt = currentTime + self.interval
203 # If we are rolling over at midnight or weekly, then the interval is already known.
204 # What we need to figure out is WHEN the next interval is. In other words,
205 # if you are rolling over at midnight, then your base interval is 1 day,
206 # but you want to start that one day clock at midnight, not now. So, we
207 # have to fudge the rolloverAt value in order to trigger the first rollover
208 # at the right time. After that, the regular interval will take care of
209 # the rest. Note that this code doesn't care about leap seconds. :)
210 if self.when == 'MIDNIGHT' or self.when.startswith('W'):
211 # This could be done with less code, but I wanted it to be clear
212 t = time.localtime(currentTime)
213 currentHour = t[3]
214 currentMinute = t[4]
215 currentSecond = t[5]
216 # r is the number of seconds left between now and midnight
217 r = _MIDNIGHT - ((currentHour * 60 + currentMinute) * 60 +
218 currentSecond)
219 self.rolloverAt = currentTime + r
220 # If we are rolling over on a certain day, add in the number of days until
221 # the next rollover, but offset by 1 since we just calculated the time
222 # until the next day starts. There are three cases:
223 # Case 1) The day to rollover is today; in this case, do nothing
224 # Case 2) The day to rollover is further in the interval (i.e., today is
225 # day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to
226 # next rollover is simply 6 - 2 - 1, or 3.
227 # Case 3) The day to rollover is behind us in the interval (i.e., today
228 # is day 5 (Saturday) and rollover is on day 3 (Thursday).
229 # Days to rollover is 6 - 5 + 3, or 4. In this case, it's the
230 # number of days left in the current week (1) plus the number
231 # of days in the next week until the rollover day (3).
232 if when.startswith('W'):
233 day = t[6] # 0 is Monday
234 if day > self.dayOfWeek:
235 daysToWait = (day - self.dayOfWeek) - 1
236 self.rolloverAt = self.rolloverAt + (daysToWait * (60 * 60 * 24))
237 if day < self.dayOfWeek:
238 daysToWait = (6 - self.dayOfWeek) + day
239 self.rolloverAt = self.rolloverAt + (daysToWait * (60 * 60 * 24))
241 #print "Will rollover at %d, %d seconds from now" % (self.rolloverAt, self.rolloverAt - currentTime)
243 def shouldRollover(self, record):
245 Determine if rollover should occur
247 record is not used, as we are just comparing times, but it is needed so
248 the method siguratures are the same
250 t = int(time.time())
251 if t >= self.rolloverAt:
252 return 1
253 #print "No need to rollover: %d, %d" % (t, self.rolloverAt)
254 return 0
256 def doRollover(self):
258 do a rollover; in this case, a date/time stamp is appended to the filename
259 when the rollover happens. However, you want the file to be named for the
260 start of the interval, not the current time. If there is a backup count,
261 then we have to get a list of matching filenames, sort them and remove
262 the one with the oldest suffix.
264 self.stream.close()
265 # get the time that this sequence started at and make it a TimeTuple
266 t = self.rolloverAt - self.interval
267 timeTuple = time.localtime(t)
268 dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple)
269 if os.path.exists(dfn):
270 os.remove(dfn)
271 os.rename(self.baseFilename, dfn)
272 if self.backupCount > 0:
273 # find the oldest log file and delete it
274 s = glob.glob(self.baseFilename + ".20*")
275 if len(s) > self.backupCount:
276 s.sort()
277 os.remove(s[0])
278 #print "%s -> %s" % (self.baseFilename, dfn)
279 if self.encoding:
280 self.stream = codecs.open(self.baseFilename, 'w', self.encoding)
281 else:
282 self.stream = open(self.baseFilename, 'w')
283 self.rolloverAt = self.rolloverAt + self.interval
285 class SocketHandler(logging.Handler):
287 A handler class which writes logging records, in pickle format, to
288 a streaming socket. The socket is kept open across logging calls.
289 If the peer resets it, an attempt is made to reconnect on the next call.
290 The pickle which is sent is that of the LogRecord's attribute dictionary
291 (__dict__), so that the receiver does not need to have the logging module
292 installed in order to process the logging event.
294 To unpickle the record at the receiving end into a LogRecord, use the
295 makeLogRecord function.
298 def __init__(self, host, port):
300 Initializes the handler with a specific host address and port.
302 The attribute 'closeOnError' is set to 1 - which means that if
303 a socket error occurs, the socket is silently closed and then
304 reopened on the next logging call.
306 logging.Handler.__init__(self)
307 self.host = host
308 self.port = port
309 self.sock = None
310 self.closeOnError = 0
311 self.retryTime = None
313 # Exponential backoff parameters.
315 self.retryStart = 1.0
316 self.retryMax = 30.0
317 self.retryFactor = 2.0
319 def makeSocket(self):
321 A factory method which allows subclasses to define the precise
322 type of socket they want.
324 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
325 s.connect((self.host, self.port))
326 return s
328 def createSocket(self):
330 Try to create a socket, using an exponential backoff with
331 a max retry time. Thanks to Robert Olson for the original patch
332 (SF #815911) which has been slightly refactored.
334 now = time.time()
335 # Either retryTime is None, in which case this
336 # is the first time back after a disconnect, or
337 # we've waited long enough.
338 if self.retryTime is None:
339 attempt = 1
340 else:
341 attempt = (now >= self.retryTime)
342 if attempt:
343 try:
344 self.sock = self.makeSocket()
345 self.retryTime = None # next time, no delay before trying
346 except:
347 #Creation failed, so set the retry time and return.
348 if self.retryTime is None:
349 self.retryPeriod = self.retryStart
350 else:
351 self.retryPeriod = self.retryPeriod * self.retryFactor
352 if self.retryPeriod > self.retryMax:
353 self.retryPeriod = self.retryMax
354 self.retryTime = now + self.retryPeriod
356 def send(self, s):
358 Send a pickled string to the socket.
360 This function allows for partial sends which can happen when the
361 network is busy.
363 if self.sock is None:
364 self.createSocket()
365 #self.sock can be None either because we haven't reached the retry
366 #time yet, or because we have reached the retry time and retried,
367 #but are still unable to connect.
368 if self.sock:
369 try:
370 if hasattr(self.sock, "sendall"):
371 self.sock.sendall(s)
372 else:
373 sentsofar = 0
374 left = len(s)
375 while left > 0:
376 sent = self.sock.send(s[sentsofar:])
377 sentsofar = sentsofar + sent
378 left = left - sent
379 except socket.error:
380 self.sock.close()
381 self.sock = None # so we can call createSocket next time
383 def makePickle(self, record):
385 Pickles the record in binary format with a length prefix, and
386 returns it ready for transmission across the socket.
388 ei = record.exc_info
389 if ei:
390 dummy = self.format(record) # just to get traceback text into record.exc_text
391 record.exc_info = None # to avoid Unpickleable error
392 s = cPickle.dumps(record.__dict__, 1)
393 if ei:
394 record.exc_info = ei # for next handler
395 slen = struct.pack(">L", len(s))
396 return slen + s
398 def handleError(self, record):
400 Handle an error during logging.
402 An error has occurred during logging. Most likely cause -
403 connection lost. Close the socket so that we can retry on the
404 next event.
406 if self.closeOnError and self.sock:
407 self.sock.close()
408 self.sock = None #try to reconnect next time
409 else:
410 logging.Handler.handleError(self, record)
412 def emit(self, record):
414 Emit a record.
416 Pickles the record and writes it to the socket in binary format.
417 If there is an error with the socket, silently drop the packet.
418 If there was a problem with the socket, re-establishes the
419 socket.
421 try:
422 s = self.makePickle(record)
423 self.send(s)
424 except (KeyboardInterrupt, SystemExit):
425 raise
426 except:
427 self.handleError(record)
429 def close(self):
431 Closes the socket.
433 if self.sock:
434 self.sock.close()
435 self.sock = None
436 logging.Handler.close(self)
438 class DatagramHandler(SocketHandler):
440 A handler class which writes logging records, in pickle format, to
441 a datagram socket. The pickle which is sent is that of the LogRecord's
442 attribute dictionary (__dict__), so that the receiver does not need to
443 have the logging module installed in order to process the logging event.
445 To unpickle the record at the receiving end into a LogRecord, use the
446 makeLogRecord function.
449 def __init__(self, host, port):
451 Initializes the handler with a specific host address and port.
453 SocketHandler.__init__(self, host, port)
454 self.closeOnError = 0
456 def makeSocket(self):
458 The factory method of SocketHandler is here overridden to create
459 a UDP socket (SOCK_DGRAM).
461 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
462 return s
464 def send(self, s):
466 Send a pickled string to a socket.
468 This function no longer allows for partial sends which can happen
469 when the network is busy - UDP does not guarantee delivery and
470 can deliver packets out of sequence.
472 if self.sock is None:
473 self.createSocket()
474 self.sock.sendto(s, (self.host, self.port))
476 class SysLogHandler(logging.Handler):
478 A handler class which sends formatted logging records to a syslog
479 server. Based on Sam Rushing's syslog module:
480 http://www.nightmare.com/squirl/python-ext/misc/syslog.py
481 Contributed by Nicolas Untz (after which minor refactoring changes
482 have been made).
485 # from <linux/sys/syslog.h>:
486 # ======================================================================
487 # priorities/facilities are encoded into a single 32-bit quantity, where
488 # the bottom 3 bits are the priority (0-7) and the top 28 bits are the
489 # facility (0-big number). Both the priorities and the facilities map
490 # roughly one-to-one to strings in the syslogd(8) source code. This
491 # mapping is included in this file.
493 # priorities (these are ordered)
495 LOG_EMERG = 0 # system is unusable
496 LOG_ALERT = 1 # action must be taken immediately
497 LOG_CRIT = 2 # critical conditions
498 LOG_ERR = 3 # error conditions
499 LOG_WARNING = 4 # warning conditions
500 LOG_NOTICE = 5 # normal but significant condition
501 LOG_INFO = 6 # informational
502 LOG_DEBUG = 7 # debug-level messages
504 # facility codes
505 LOG_KERN = 0 # kernel messages
506 LOG_USER = 1 # random user-level messages
507 LOG_MAIL = 2 # mail system
508 LOG_DAEMON = 3 # system daemons
509 LOG_AUTH = 4 # security/authorization messages
510 LOG_SYSLOG = 5 # messages generated internally by syslogd
511 LOG_LPR = 6 # line printer subsystem
512 LOG_NEWS = 7 # network news subsystem
513 LOG_UUCP = 8 # UUCP subsystem
514 LOG_CRON = 9 # clock daemon
515 LOG_AUTHPRIV = 10 # security/authorization messages (private)
517 # other codes through 15 reserved for system use
518 LOG_LOCAL0 = 16 # reserved for local use
519 LOG_LOCAL1 = 17 # reserved for local use
520 LOG_LOCAL2 = 18 # reserved for local use
521 LOG_LOCAL3 = 19 # reserved for local use
522 LOG_LOCAL4 = 20 # reserved for local use
523 LOG_LOCAL5 = 21 # reserved for local use
524 LOG_LOCAL6 = 22 # reserved for local use
525 LOG_LOCAL7 = 23 # reserved for local use
527 priority_names = {
528 "alert": LOG_ALERT,
529 "crit": LOG_CRIT,
530 "critical": LOG_CRIT,
531 "debug": LOG_DEBUG,
532 "emerg": LOG_EMERG,
533 "err": LOG_ERR,
534 "error": LOG_ERR, # DEPRECATED
535 "info": LOG_INFO,
536 "notice": LOG_NOTICE,
537 "panic": LOG_EMERG, # DEPRECATED
538 "warn": LOG_WARNING, # DEPRECATED
539 "warning": LOG_WARNING,
542 facility_names = {
543 "auth": LOG_AUTH,
544 "authpriv": LOG_AUTHPRIV,
545 "cron": LOG_CRON,
546 "daemon": LOG_DAEMON,
547 "kern": LOG_KERN,
548 "lpr": LOG_LPR,
549 "mail": LOG_MAIL,
550 "news": LOG_NEWS,
551 "security": LOG_AUTH, # DEPRECATED
552 "syslog": LOG_SYSLOG,
553 "user": LOG_USER,
554 "uucp": LOG_UUCP,
555 "local0": LOG_LOCAL0,
556 "local1": LOG_LOCAL1,
557 "local2": LOG_LOCAL2,
558 "local3": LOG_LOCAL3,
559 "local4": LOG_LOCAL4,
560 "local5": LOG_LOCAL5,
561 "local6": LOG_LOCAL6,
562 "local7": LOG_LOCAL7,
565 def __init__(self, address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER):
567 Initialize a handler.
569 If address is specified as a string, UNIX socket is used.
570 If facility is not specified, LOG_USER is used.
572 logging.Handler.__init__(self)
574 self.address = address
575 self.facility = facility
576 if type(address) == types.StringType:
577 self._connect_unixsocket(address)
578 self.unixsocket = 1
579 else:
580 self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
581 self.unixsocket = 0
583 self.formatter = None
585 def _connect_unixsocket(self, address):
586 self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
587 # syslog may require either DGRAM or STREAM sockets
588 try:
589 self.socket.connect(address)
590 except socket.error:
591 self.socket.close()
592 self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
593 self.socket.connect(address)
595 # curious: when talking to the unix-domain '/dev/log' socket, a
596 # zero-terminator seems to be required. this string is placed
597 # into a class variable so that it can be overridden if
598 # necessary.
599 log_format_string = '<%d>%s\000'
601 def encodePriority (self, facility, priority):
603 Encode the facility and priority. You can pass in strings or
604 integers - if strings are passed, the facility_names and
605 priority_names mapping dictionaries are used to convert them to
606 integers.
608 if type(facility) == types.StringType:
609 facility = self.facility_names[facility]
610 if type(priority) == types.StringType:
611 priority = self.priority_names[priority]
612 return (facility << 3) | priority
614 def close (self):
616 Closes the socket.
618 if self.unixsocket:
619 self.socket.close()
620 logging.Handler.close(self)
622 def emit(self, record):
624 Emit a record.
626 The record is formatted, and then sent to the syslog server. If
627 exception information is present, it is NOT sent to the server.
629 msg = self.format(record)
631 We need to convert record level to lowercase, maybe this will
632 change in the future.
634 msg = self.log_format_string % (
635 self.encodePriority(self.facility,
636 string.lower(record.levelname)),
637 msg)
638 try:
639 if self.unixsocket:
640 try:
641 self.socket.send(msg)
642 except socket.error:
643 self._connect_unixsocket(self.address)
644 self.socket.send(msg)
645 else:
646 self.socket.sendto(msg, self.address)
647 except (KeyboardInterrupt, SystemExit):
648 raise
649 except:
650 self.handleError(record)
652 class SMTPHandler(logging.Handler):
654 A handler class which sends an SMTP email for each logging event.
656 def __init__(self, mailhost, fromaddr, toaddrs, subject):
658 Initialize the handler.
660 Initialize the instance with the from and to addresses and subject
661 line of the email. To specify a non-standard SMTP port, use the
662 (host, port) tuple format for the mailhost argument.
664 logging.Handler.__init__(self)
665 if type(mailhost) == types.TupleType:
666 host, port = mailhost
667 self.mailhost = host
668 self.mailport = port
669 else:
670 self.mailhost = mailhost
671 self.mailport = None
672 self.fromaddr = fromaddr
673 if type(toaddrs) == types.StringType:
674 toaddrs = [toaddrs]
675 self.toaddrs = toaddrs
676 self.subject = subject
678 def getSubject(self, record):
680 Determine the subject for the email.
682 If you want to specify a subject line which is record-dependent,
683 override this method.
685 return self.subject
687 weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
689 monthname = [None,
690 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
691 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
693 def date_time(self):
695 Return the current date and time formatted for a MIME header.
696 Needed for Python 1.5.2 (no email package available)
698 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(time.time())
699 s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
700 self.weekdayname[wd],
701 day, self.monthname[month], year,
702 hh, mm, ss)
703 return s
705 def emit(self, record):
707 Emit a record.
709 Format the record and send it to the specified addressees.
711 try:
712 import smtplib
713 try:
714 from email.Utils import formatdate
715 except:
716 formatdate = self.date_time
717 port = self.mailport
718 if not port:
719 port = smtplib.SMTP_PORT
720 smtp = smtplib.SMTP(self.mailhost, port)
721 msg = self.format(record)
722 msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
723 self.fromaddr,
724 string.join(self.toaddrs, ","),
725 self.getSubject(record),
726 formatdate(), msg)
727 smtp.sendmail(self.fromaddr, self.toaddrs, msg)
728 smtp.quit()
729 except (KeyboardInterrupt, SystemExit):
730 raise
731 except:
732 self.handleError(record)
734 class NTEventLogHandler(logging.Handler):
736 A handler class which sends events to the NT Event Log. Adds a
737 registry entry for the specified application name. If no dllname is
738 provided, win32service.pyd (which contains some basic message
739 placeholders) is used. Note that use of these placeholders will make
740 your event logs big, as the entire message source is held in the log.
741 If you want slimmer logs, you have to pass in the name of your own DLL
742 which contains the message definitions you want to use in the event log.
744 def __init__(self, appname, dllname=None, logtype="Application"):
745 logging.Handler.__init__(self)
746 try:
747 import win32evtlogutil, win32evtlog
748 self.appname = appname
749 self._welu = win32evtlogutil
750 if not dllname:
751 dllname = os.path.split(self._welu.__file__)
752 dllname = os.path.split(dllname[0])
753 dllname = os.path.join(dllname[0], r'win32service.pyd')
754 self.dllname = dllname
755 self.logtype = logtype
756 self._welu.AddSourceToRegistry(appname, dllname, logtype)
757 self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE
758 self.typemap = {
759 logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE,
760 logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE,
761 logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE,
762 logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE,
763 logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE,
765 except ImportError:
766 print "The Python Win32 extensions for NT (service, event "\
767 "logging) appear not to be available."
768 self._welu = None
770 def getMessageID(self, record):
772 Return the message ID for the event record. If you are using your
773 own messages, you could do this by having the msg passed to the
774 logger being an ID rather than a formatting string. Then, in here,
775 you could use a dictionary lookup to get the message ID. This
776 version returns 1, which is the base message ID in win32service.pyd.
778 return 1
780 def getEventCategory(self, record):
782 Return the event category for the record.
784 Override this if you want to specify your own categories. This version
785 returns 0.
787 return 0
789 def getEventType(self, record):
791 Return the event type for the record.
793 Override this if you want to specify your own types. This version does
794 a mapping using the handler's typemap attribute, which is set up in
795 __init__() to a dictionary which contains mappings for DEBUG, INFO,
796 WARNING, ERROR and CRITICAL. If you are using your own levels you will
797 either need to override this method or place a suitable dictionary in
798 the handler's typemap attribute.
800 return self.typemap.get(record.levelno, self.deftype)
802 def emit(self, record):
804 Emit a record.
806 Determine the message ID, event category and event type. Then
807 log the message in the NT event log.
809 if self._welu:
810 try:
811 id = self.getMessageID(record)
812 cat = self.getEventCategory(record)
813 type = self.getEventType(record)
814 msg = self.format(record)
815 self._welu.ReportEvent(self.appname, id, cat, type, [msg])
816 except (KeyboardInterrupt, SystemExit):
817 raise
818 except:
819 self.handleError(record)
821 def close(self):
823 Clean up this handler.
825 You can remove the application name from the registry as a
826 source of event log entries. However, if you do this, you will
827 not be able to see the events as you intended in the Event Log
828 Viewer - it needs to be able to access the registry to get the
829 DLL name.
831 #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype)
832 logging.Handler.close(self)
834 class HTTPHandler(logging.Handler):
836 A class which sends records to a Web server, using either GET or
837 POST semantics.
839 def __init__(self, host, url, method="GET"):
841 Initialize the instance with the host, the request URL, and the method
842 ("GET" or "POST")
844 logging.Handler.__init__(self)
845 method = string.upper(method)
846 if method not in ["GET", "POST"]:
847 raise ValueError, "method must be GET or POST"
848 self.host = host
849 self.url = url
850 self.method = method
852 def mapLogRecord(self, record):
854 Default implementation of mapping the log record into a dict
855 that is sent as the CGI data. Overwrite in your class.
856 Contributed by Franz Glasner.
858 return record.__dict__
860 def emit(self, record):
862 Emit a record.
864 Send the record to the Web server as an URL-encoded dictionary
866 try:
867 import httplib, urllib
868 host = self.host
869 h = httplib.HTTP(host)
870 url = self.url
871 data = urllib.urlencode(self.mapLogRecord(record))
872 if self.method == "GET":
873 if (string.find(url, '?') >= 0):
874 sep = '&'
875 else:
876 sep = '?'
877 url = url + "%c%s" % (sep, data)
878 h.putrequest(self.method, url)
879 # support multiple hosts on one IP address...
880 # need to strip optional :port from host, if present
881 i = string.find(host, ":")
882 if i >= 0:
883 host = host[:i]
884 h.putheader("Host", host)
885 if self.method == "POST":
886 h.putheader("Content-type",
887 "application/x-www-form-urlencoded")
888 h.putheader("Content-length", str(len(data)))
889 h.endheaders()
890 if self.method == "POST":
891 h.send(data)
892 h.getreply() #can't do anything with the result
893 except (KeyboardInterrupt, SystemExit):
894 raise
895 except:
896 self.handleError(record)
898 class BufferingHandler(logging.Handler):
900 A handler class which buffers logging records in memory. Whenever each
901 record is added to the buffer, a check is made to see if the buffer should
902 be flushed. If it should, then flush() is expected to do what's needed.
904 def __init__(self, capacity):
906 Initialize the handler with the buffer size.
908 logging.Handler.__init__(self)
909 self.capacity = capacity
910 self.buffer = []
912 def shouldFlush(self, record):
914 Should the handler flush its buffer?
916 Returns true if the buffer is up to capacity. This method can be
917 overridden to implement custom flushing strategies.
919 return (len(self.buffer) >= self.capacity)
921 def emit(self, record):
923 Emit a record.
925 Append the record. If shouldFlush() tells us to, call flush() to process
926 the buffer.
928 self.buffer.append(record)
929 if self.shouldFlush(record):
930 self.flush()
932 def flush(self):
934 Override to implement custom flushing behaviour.
936 This version just zaps the buffer to empty.
938 self.buffer = []
940 def close(self):
942 Close the handler.
944 This version just flushes and chains to the parent class' close().
946 self.flush()
947 logging.Handler.close(self)
949 class MemoryHandler(BufferingHandler):
951 A handler class which buffers logging records in memory, periodically
952 flushing them to a target handler. Flushing occurs whenever the buffer
953 is full, or when an event of a certain severity or greater is seen.
955 def __init__(self, capacity, flushLevel=logging.ERROR, target=None):
957 Initialize the handler with the buffer size, the level at which
958 flushing should occur and an optional target.
960 Note that without a target being set either here or via setTarget(),
961 a MemoryHandler is no use to anyone!
963 BufferingHandler.__init__(self, capacity)
964 self.flushLevel = flushLevel
965 self.target = target
967 def shouldFlush(self, record):
969 Check for buffer full or a record at the flushLevel or higher.
971 return (len(self.buffer) >= self.capacity) or \
972 (record.levelno >= self.flushLevel)
974 def setTarget(self, target):
976 Set the target handler for this handler.
978 self.target = target
980 def flush(self):
982 For a MemoryHandler, flushing means just sending the buffered
983 records to the target, if there is one. Override if you want
984 different behaviour.
986 if self.target:
987 for record in self.buffer:
988 self.target.handle(record)
989 self.buffer = []
991 def close(self):
993 Flush, set the target to None and lose the buffer.
995 self.flush()
996 self.target = None
997 BufferingHandler.close(self)