blob: 99a543e5db836ed7a1a639e836c22fed209e293f [file] [log] [blame]
Vinay Sajipf42d95e2004-02-21 22:14:34 +00001# Copyright 2001-2004 by Vinay Sajip. All Rights Reserved.
Guido van Rossum57102f82002-11-13 16:15:58 +00002#
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.
Guido van Rossum57102f82002-11-13 16:15:58 +000016
17"""
Vinay Sajip3f742842004-02-28 16:07:46 +000018Additional 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.
Guido van Rossum57102f82002-11-13 16:15:58 +000021
22Should work under Python versions >= 1.5.2, except that source line
Vinay Sajip48cfe382004-02-20 13:17:27 +000023information is not available unless 'sys._getframe()' is.
Guido van Rossum57102f82002-11-13 16:15:58 +000024
Vinay Sajip48cfe382004-02-20 13:17:27 +000025Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved.
Guido van Rossum57102f82002-11-13 16:15:58 +000026
27To use, simply 'import logging' and log away!
28"""
29
Neal Norwitzf297bd12003-04-23 03:49:43 +000030import sys, logging, socket, types, os, string, cPickle, struct, time
Guido van Rossum57102f82002-11-13 16:15:58 +000031
32from SocketServer import ThreadingTCPServer, StreamRequestHandler
33
34#
35# Some constants...
36#
37
38DEFAULT_TCP_LOGGING_PORT = 9020
39DEFAULT_UDP_LOGGING_PORT = 9021
40DEFAULT_HTTP_LOGGING_PORT = 9022
41DEFAULT_SOAP_LOGGING_PORT = 9023
42SYSLOG_UDP_PORT = 514
43
44
45class 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.
49
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.
53
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.
64
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"
72
73 def doRollover(self):
74 """
75 Do a rollover, as described in __init__().
76 """
77
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")
94
95 def emit(self, record):
96 """
97 Emit a record.
98
99 Output the record to the file, catering for rollover as described
Raymond Hettingere21f6062003-11-08 11:40:03 +0000100 in doRollover().
Guido van Rossum57102f82002-11-13 16:15:58 +0000101 """
102 if self.maxBytes > 0: # are we rolling over?
103 msg = "%s\n" % self.format(record)
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000104 self.stream.seek(0, 2) #due to non-posix-compliant Windows feature
Guido van Rossum57102f82002-11-13 16:15:58 +0000105 if self.stream.tell() + len(msg) >= self.maxBytes:
106 self.doRollover()
107 logging.FileHandler.emit(self, record)
108
109
110class 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.
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000115 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.
118
119 To unpickle the record at the receiving end into a LogRecord, use the
120 makeLogRecord function.
Guido van Rossum57102f82002-11-13 16:15:58 +0000121 """
122
123 def __init__(self, host, port):
124 """
125 Initializes the handler with a specific host address and port.
126
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
Vinay Sajip48cfe382004-02-20 13:17:27 +0000136 self.retryTime = None
137 #
138 # Exponential backoff parameters.
139 #
140 self.retryStart = 1.0
141 self.retryMax = 30.0
142 self.retryFactor = 2.0
Guido van Rossum57102f82002-11-13 16:15:58 +0000143
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
152
Vinay Sajip48cfe382004-02-20 13:17:27 +0000153 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
180
Guido van Rossum57102f82002-11-13 16:15:58 +0000181 def send(self, s):
182 """
183 Send a pickled string to the socket.
184
185 This function allows for partial sends which can happen when the
186 network is busy.
187 """
Vinay Sajip48cfe382004-02-20 13:17:27 +0000188 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
Guido van Rossum57102f82002-11-13 16:15:58 +0000207
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 """
Vinay Sajip48cfe382004-02-20 13:17:27 +0000213 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
Guido van Rossum57102f82002-11-13 16:15:58 +0000217 s = cPickle.dumps(record.__dict__, 1)
Vinay Sajip48cfe382004-02-20 13:17:27 +0000218 if ei:
219 record.exc_info = ei # for next handler
Guido van Rossum57102f82002-11-13 16:15:58 +0000220 slen = struct.pack(">L", len(s))
221 return slen + s
222
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000223 def handleError(self, record):
Guido van Rossum57102f82002-11-13 16:15:58 +0000224 """
225 Handle an error during logging.
226
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:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000235 logging.Handler.handleError(self, record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000236
237 def emit(self, record):
238 """
239 Emit a record.
240
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)
Guido van Rossum57102f82002-11-13 16:15:58 +0000248 self.send(s)
249 except:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000250 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000251
252 def close(self):
253 """
254 Closes the socket.
255 """
256 if self.sock:
257 self.sock.close()
258 self.sock = None
Vinay Sajip48cfe382004-02-20 13:17:27 +0000259 logging.Handler.close(self)
Guido van Rossum57102f82002-11-13 16:15:58 +0000260
261class DatagramHandler(SocketHandler):
262 """
263 A handler class which writes logging records, in pickle format, to
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000264 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.
267
268 To unpickle the record at the receiving end into a LogRecord, use the
269 makeLogRecord function.
Guido van Rossum57102f82002-11-13 16:15:58 +0000270
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
278
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
286
287 def send(self, s):
288 """
289 Send a pickled string to a socket.
290
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 """
Guido van Rossum57102f82002-11-13 16:15:58 +0000295 self.sock.sendto(s, (self.host, self.port))
296
297class 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 """
305
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)
315
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
324
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)
337
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
347
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 }
362
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 }
385
386 def __init__(self, address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER):
387 """
388 Initialize a handler.
389
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)
394
395 self.address = address
396 self.facility = facility
397 if type(address) == types.StringType:
Neal Norwitzd89c4062003-01-26 02:14:23 +0000398 self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
Neal Norwitzf4cdb472003-01-26 16:15:24 +0000399 # 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)
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000405 self.socket.connect(address)
Guido van Rossum57102f82002-11-13 16:15:58 +0000406 self.unixsocket = 1
407 else:
408 self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
409 self.unixsocket = 0
410
411 self.formatter = None
412
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'
418
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
431
432 def close (self):
433 """
434 Closes the socket.
435 """
436 if self.unixsocket:
437 self.socket.close()
Vinay Sajip48cfe382004-02-20 13:17:27 +0000438 logging.Handler.close(self)
Guido van Rossum57102f82002-11-13 16:15:58 +0000439
440 def emit(self, record):
441 """
442 Emit a record.
443
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:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000462 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000463
464class 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.
471
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
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000485 if type(toaddrs) == types.StringType:
486 toaddrs = [toaddrs]
Guido van Rossum57102f82002-11-13 16:15:58 +0000487 self.toaddrs = toaddrs
488 self.subject = subject
489
490 def getSubject(self, record):
491 """
492 Determine the subject for the email.
493
494 If you want to specify a subject line which is record-dependent,
495 override this method.
496 """
497 return self.subject
498
Neal Norwitzf297bd12003-04-23 03:49:43 +0000499 weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
500
501 monthname = [None,
502 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
503 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
504
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
513
Guido van Rossum57102f82002-11-13 16:15:58 +0000514 def emit(self, record):
515 """
516 Emit a record.
517
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)
Neal Norwitzf297bd12003-04-23 03:49:43 +0000527 msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
Guido van Rossum57102f82002-11-13 16:15:58 +0000528 self.fromaddr,
529 string.join(self.toaddrs, ","),
Neal Norwitzf297bd12003-04-23 03:49:43 +0000530 self.getSubject(record),
531 self.date_time(), msg)
Guido van Rossum57102f82002-11-13 16:15:58 +0000532 smtp.sendmail(self.fromaddr, self.toaddrs, msg)
533 smtp.quit()
534 except:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000535 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000536
537class 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,
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000564 logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE,
Guido van Rossum57102f82002-11-13 16:15:58 +0000565 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
572
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
582
583 def getEventCategory(self, record):
584 """
585 Return the event category for the record.
586
587 Override this if you want to specify your own categories. This version
588 returns 0.
589 """
590 return 0
591
592 def getEventType(self, record):
593 """
594 Return the event type for the record.
595
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,
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000599 WARNING, ERROR and CRITICAL. If you are using your own levels you will
Guido van Rossum57102f82002-11-13 16:15:58 +0000600 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)
604
605 def emit(self, record):
606 """
607 Emit a record.
608
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:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000620 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000621
622 def close(self):
623 """
624 Clean up this handler.
625
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)
Vinay Sajip48cfe382004-02-20 13:17:27 +0000633 logging.Handler.close(self)
Guido van Rossum57102f82002-11-13 16:15:58 +0000634
635class 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
652
Neal Norwitzf297bd12003-04-23 03:49:43 +0000653 def mapLogRecord(self, record):
654 """
655 Default implementation of mapping the log record into a dict
Vinay Sajip48cfe382004-02-20 13:17:27 +0000656 that is sent as the CGI data. Overwrite in your class.
Neal Norwitzf297bd12003-04-23 03:49:43 +0000657 Contributed by Franz Glasner.
658 """
659 return record.__dict__
660
Guido van Rossum57102f82002-11-13 16:15:58 +0000661 def emit(self, record):
662 """
663 Emit a record.
664
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
Neal Norwitzf297bd12003-04-23 03:49:43 +0000671 data = urllib.urlencode(self.mapLogRecord(record))
Guido van Rossum57102f82002-11-13 16:15:58 +0000672 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:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000686 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000687
688class 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 = []
701
702 def shouldFlush(self, record):
703 """
704 Should the handler flush its buffer?
705
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)
710
711 def emit(self, record):
712 """
713 Emit a record.
714
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()
721
722 def flush(self):
723 """
724 Override to implement custom flushing behaviour.
725
726 This version just zaps the buffer to empty.
727 """
728 self.buffer = []
729
Vinay Sajipf42d95e2004-02-21 22:14:34 +0000730 def close(self):
731 """
732 Close the handler.
733
734 This version just flushes and chains to the parent class' close().
735 """
736 self.flush()
737 logging.Handler.close(self)
738
Guido van Rossum57102f82002-11-13 16:15:58 +0000739class 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.
749
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
756
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)
763
764 def setTarget(self, target):
765 """
766 Set the target handler for this handler.
767 """
768 self.target = target
769
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 = []
780
781 def close(self):
782 """
783 Flush, set the target to None and lose the buffer.
784 """
785 self.flush()
786 self.target = None
Vinay Sajip48cfe382004-02-20 13:17:27 +0000787 BufferingHandler.close(self)