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