blob: 70bd5d4faecfc44875020f44a9e68e3605783a55 [file] [log] [blame]
Vinay Sajip4600f112005-03-13 09:56:36 +00001# Copyright 2001-2005 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
Vinay Sajip17c52d82004-07-03 11:48:34 +000030import sys, logging, socket, types, os, string, cPickle, struct, time, glob
Guido van Rossum57102f82002-11-13 16:15:58 +000031
Vinay Sajip4600f112005-03-13 09:56:36 +000032try:
33 import codecs
34except ImportError:
35 codecs = None
36
Guido van Rossum57102f82002-11-13 16:15:58 +000037#
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
Vinay Sajip4b4a63e2006-05-02 08:35:36 +000047_MIDNIGHT = 24 * 60 * 60 # number of seconds in a day
48
Vinay Sajip17c52d82004-07-03 11:48:34 +000049class 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 """
Vinay Sajip4600f112005-03-13 09:56:36 +000055 def __init__(self, filename, mode, encoding=None):
Vinay Sajip17c52d82004-07-03 11:48:34 +000056 """
57 Use the specified filename for streamed logging
58 """
Vinay Sajip4600f112005-03-13 09:56:36 +000059 if codecs is None:
60 encoding = None
61 logging.FileHandler.__init__(self, filename, mode, encoding)
62 self.mode = mode
63 self.encoding = encoding
Guido van Rossum57102f82002-11-13 16:15:58 +000064
Vinay Sajip17c52d82004-07-03 11:48:34 +000065 def emit(self, record):
66 """
67 Emit a record.
68
69 Output the record to the file, catering for rollover as described
70 in doRollover().
71 """
Vinay Sajip3970c112004-07-08 10:24:04 +000072 try:
73 if self.shouldRollover(record):
74 self.doRollover()
75 logging.FileHandler.emit(self, record)
Vinay Sajip85c19092005-10-31 13:14:19 +000076 except (KeyboardInterrupt, SystemExit):
77 raise
Vinay Sajip3970c112004-07-08 10:24:04 +000078 except:
79 self.handleError(record)
Vinay Sajip17c52d82004-07-03 11:48:34 +000080
81class 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 """
Vinay Sajip4600f112005-03-13 09:56:36 +000086 def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None):
Guido van Rossum57102f82002-11-13 16:15:58 +000087 """
88 Open the specified file and use it as the stream for logging.
89
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.
93
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.
104
105 If maxBytes is zero, rollover never occurs.
106 """
Vinay Sajip17c52d82004-07-03 11:48:34 +0000107 if maxBytes > 0:
Vinay Sajip4600f112005-03-13 09:56:36 +0000108 mode = 'a' # doesn't make sense otherwise!
109 BaseRotatingHandler.__init__(self, filename, mode, encoding)
Guido van Rossum57102f82002-11-13 16:15:58 +0000110 self.maxBytes = maxBytes
111 self.backupCount = backupCount
Guido van Rossum57102f82002-11-13 16:15:58 +0000112
113 def doRollover(self):
114 """
115 Do a rollover, as described in __init__().
116 """
117
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)
Vinay Sajip6dd59f12006-06-27 07:34:37 +0000131 os.rename(self.baseFilename, dfn)
Guido van Rossum57102f82002-11-13 16:15:58 +0000132 #print "%s -> %s" % (self.baseFilename, dfn)
Vinay Sajip4600f112005-03-13 09:56:36 +0000133 if self.encoding:
134 self.stream = codecs.open(self.baseFilename, 'w', self.encoding)
135 else:
136 self.stream = open(self.baseFilename, 'w')
Guido van Rossum57102f82002-11-13 16:15:58 +0000137
Vinay Sajip17c52d82004-07-03 11:48:34 +0000138 def shouldRollover(self, record):
Guido van Rossum57102f82002-11-13 16:15:58 +0000139 """
Vinay Sajip17c52d82004-07-03 11:48:34 +0000140 Determine if rollover should occur.
Guido van Rossum57102f82002-11-13 16:15:58 +0000141
Vinay Sajip17c52d82004-07-03 11:48:34 +0000142 Basically, see if the supplied record would cause the file to exceed
143 the size limit we have.
Guido van Rossum57102f82002-11-13 16:15:58 +0000144 """
145 if self.maxBytes > 0: # are we rolling over?
146 msg = "%s\n" % self.format(record)
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000147 self.stream.seek(0, 2) #due to non-posix-compliant Windows feature
Guido van Rossum57102f82002-11-13 16:15:58 +0000148 if self.stream.tell() + len(msg) >= self.maxBytes:
Vinay Sajip17c52d82004-07-03 11:48:34 +0000149 return 1
150 return 0
Guido van Rossum57102f82002-11-13 16:15:58 +0000151
Vinay Sajip17c52d82004-07-03 11:48:34 +0000152class TimedRotatingFileHandler(BaseRotatingHandler):
153 """
154 Handler for logging to a file, rotating the log file at certain timed
155 intervals.
156
157 If backupCount is > 0, when rollover is done, no more than backupCount
158 files are kept - the oldest ones are deleted.
159 """
Vinay Sajip4600f112005-03-13 09:56:36 +0000160 def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None):
161 BaseRotatingHandler.__init__(self, filename, 'a', encoding)
Vinay Sajip17c52d82004-07-03 11:48:34 +0000162 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
173 #
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)
199
Vinay Sajipe7d40662004-10-03 19:12:07 +0000200 self.interval = self.interval * interval # multiply by units requested
Vinay Sajip17c52d82004-07-03 11:48:34 +0000201 self.rolloverAt = currentTime + self.interval
202
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
Vinay Sajip4b4a63e2006-05-02 08:35:36 +0000217 r = _MIDNIGHT - ((currentHour * 60 + currentMinute) * 60 +
218 currentSecond)
Vinay Sajip17c52d82004-07-03 11:48:34 +0000219 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
Vinay Sajipe7d40662004-10-03 19:12:07 +0000236 self.rolloverAt = self.rolloverAt + (daysToWait * (60 * 60 * 24))
Vinay Sajip17c52d82004-07-03 11:48:34 +0000237 if day < self.dayOfWeek:
238 daysToWait = (6 - self.dayOfWeek) + day
Vinay Sajipe7d40662004-10-03 19:12:07 +0000239 self.rolloverAt = self.rolloverAt + (daysToWait * (60 * 60 * 24))
Vinay Sajip17c52d82004-07-03 11:48:34 +0000240
Vinay Sajip5e9e9e12004-07-12 09:21:41 +0000241 #print "Will rollover at %d, %d seconds from now" % (self.rolloverAt, self.rolloverAt - currentTime)
Vinay Sajip17c52d82004-07-03 11:48:34 +0000242
243 def shouldRollover(self, record):
244 """
245 Determine if rollover should occur
246
247 record is not used, as we are just comparing times, but it is needed so
248 the method siguratures are the same
249 """
250 t = int(time.time())
251 if t >= self.rolloverAt:
252 return 1
Vinay Sajip5e9e9e12004-07-12 09:21:41 +0000253 #print "No need to rollover: %d, %d" % (t, self.rolloverAt)
Vinay Sajip17c52d82004-07-03 11:48:34 +0000254 return 0
255
256 def doRollover(self):
257 """
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.
263 """
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)
Vinay Sajip6dd59f12006-06-27 07:34:37 +0000271 os.rename(self.baseFilename, dfn)
Vinay Sajip17c52d82004-07-03 11:48:34 +0000272 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:
Vinay Sajip5e9e9e12004-07-12 09:21:41 +0000276 s.sort()
Vinay Sajip17c52d82004-07-03 11:48:34 +0000277 os.remove(s[0])
Vinay Sajip5e9e9e12004-07-12 09:21:41 +0000278 #print "%s -> %s" % (self.baseFilename, dfn)
Vinay Sajip4600f112005-03-13 09:56:36 +0000279 if self.encoding:
280 self.stream = codecs.open(self.baseFilename, 'w', self.encoding)
281 else:
282 self.stream = open(self.baseFilename, 'w')
Vinay Sajipd9520412006-01-16 09:13:58 +0000283 self.rolloverAt = self.rolloverAt + self.interval
Guido van Rossum57102f82002-11-13 16:15:58 +0000284
285class SocketHandler(logging.Handler):
286 """
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.
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000290 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.
293
294 To unpickle the record at the receiving end into a LogRecord, use the
295 makeLogRecord function.
Guido van Rossum57102f82002-11-13 16:15:58 +0000296 """
297
298 def __init__(self, host, port):
299 """
300 Initializes the handler with a specific host address and port.
301
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.
305 """
306 logging.Handler.__init__(self)
307 self.host = host
308 self.port = port
309 self.sock = None
310 self.closeOnError = 0
Vinay Sajip48cfe382004-02-20 13:17:27 +0000311 self.retryTime = None
312 #
313 # Exponential backoff parameters.
314 #
315 self.retryStart = 1.0
316 self.retryMax = 30.0
317 self.retryFactor = 2.0
Guido van Rossum57102f82002-11-13 16:15:58 +0000318
319 def makeSocket(self):
320 """
321 A factory method which allows subclasses to define the precise
322 type of socket they want.
323 """
324 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
325 s.connect((self.host, self.port))
326 return s
327
Vinay Sajip48cfe382004-02-20 13:17:27 +0000328 def createSocket(self):
329 """
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.
333 """
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:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000339 attempt = 1
Vinay Sajip48cfe382004-02-20 13:17:27 +0000340 else:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000341 attempt = (now >= self.retryTime)
Vinay Sajip48cfe382004-02-20 13:17:27 +0000342 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
355
Guido van Rossum57102f82002-11-13 16:15:58 +0000356 def send(self, s):
357 """
358 Send a pickled string to the socket.
359
360 This function allows for partial sends which can happen when the
361 network is busy.
362 """
Vinay Sajip48cfe382004-02-20 13:17:27 +0000363 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
Guido van Rossum57102f82002-11-13 16:15:58 +0000382
383 def makePickle(self, record):
384 """
385 Pickles the record in binary format with a length prefix, and
386 returns it ready for transmission across the socket.
387 """
Vinay Sajip48cfe382004-02-20 13:17:27 +0000388 ei = record.exc_info
389 if ei:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000390 dummy = self.format(record) # just to get traceback text into record.exc_text
391 record.exc_info = None # to avoid Unpickleable error
Guido van Rossum57102f82002-11-13 16:15:58 +0000392 s = cPickle.dumps(record.__dict__, 1)
Vinay Sajip48cfe382004-02-20 13:17:27 +0000393 if ei:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000394 record.exc_info = ei # for next handler
Guido van Rossum57102f82002-11-13 16:15:58 +0000395 slen = struct.pack(">L", len(s))
396 return slen + s
397
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000398 def handleError(self, record):
Guido van Rossum57102f82002-11-13 16:15:58 +0000399 """
400 Handle an error during logging.
401
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.
405 """
406 if self.closeOnError and self.sock:
407 self.sock.close()
408 self.sock = None #try to reconnect next time
409 else:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000410 logging.Handler.handleError(self, record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000411
412 def emit(self, record):
413 """
414 Emit a record.
415
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.
420 """
421 try:
422 s = self.makePickle(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000423 self.send(s)
Vinay Sajip85c19092005-10-31 13:14:19 +0000424 except (KeyboardInterrupt, SystemExit):
425 raise
Guido van Rossum57102f82002-11-13 16:15:58 +0000426 except:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000427 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000428
429 def close(self):
430 """
431 Closes the socket.
432 """
433 if self.sock:
434 self.sock.close()
435 self.sock = None
Vinay Sajip48cfe382004-02-20 13:17:27 +0000436 logging.Handler.close(self)
Guido van Rossum57102f82002-11-13 16:15:58 +0000437
438class DatagramHandler(SocketHandler):
439 """
440 A handler class which writes logging records, in pickle format, to
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000441 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.
444
445 To unpickle the record at the receiving end into a LogRecord, use the
446 makeLogRecord function.
Guido van Rossum57102f82002-11-13 16:15:58 +0000447
448 """
449 def __init__(self, host, port):
450 """
451 Initializes the handler with a specific host address and port.
452 """
453 SocketHandler.__init__(self, host, port)
454 self.closeOnError = 0
455
456 def makeSocket(self):
457 """
458 The factory method of SocketHandler is here overridden to create
459 a UDP socket (SOCK_DGRAM).
460 """
461 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
462 return s
463
464 def send(self, s):
465 """
466 Send a pickled string to a socket.
467
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.
471 """
Vinay Sajipfb154172004-08-24 09:36:23 +0000472 if self.sock is None:
473 self.createSocket()
Guido van Rossum57102f82002-11-13 16:15:58 +0000474 self.sock.sendto(s, (self.host, self.port))
475
476class SysLogHandler(logging.Handler):
477 """
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).
483 """
484
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.
492 #
493 # priorities (these are ordered)
494
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
503
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)
516
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
526
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,
540 }
541
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,
563 }
564
565 def __init__(self, address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER):
566 """
567 Initialize a handler.
568
569 If address is specified as a string, UNIX socket is used.
570 If facility is not specified, LOG_USER is used.
571 """
572 logging.Handler.__init__(self)
573
574 self.address = address
575 self.facility = facility
576 if type(address) == types.StringType:
Vinay Sajipa1974c12005-01-13 08:23:56 +0000577 self._connect_unixsocket(address)
Guido van Rossum57102f82002-11-13 16:15:58 +0000578 self.unixsocket = 1
579 else:
580 self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
581 self.unixsocket = 0
582
583 self.formatter = None
584
Vinay Sajipa1974c12005-01-13 08:23:56 +0000585 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)
Vinay Sajip8b6b53f2005-11-09 13:55:13 +0000593 self.socket.connect(address)
Vinay Sajipa1974c12005-01-13 08:23:56 +0000594
Guido van Rossum57102f82002-11-13 16:15:58 +0000595 # 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'
600
601 def encodePriority (self, facility, priority):
602 """
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.
607 """
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
613
614 def close (self):
615 """
616 Closes the socket.
617 """
618 if self.unixsocket:
619 self.socket.close()
Vinay Sajip48cfe382004-02-20 13:17:27 +0000620 logging.Handler.close(self)
Guido van Rossum57102f82002-11-13 16:15:58 +0000621
622 def emit(self, record):
623 """
624 Emit a record.
625
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.
628 """
629 msg = self.format(record)
630 """
631 We need to convert record level to lowercase, maybe this will
632 change in the future.
633 """
634 msg = self.log_format_string % (
635 self.encodePriority(self.facility,
636 string.lower(record.levelname)),
637 msg)
638 try:
639 if self.unixsocket:
Vinay Sajipa1974c12005-01-13 08:23:56 +0000640 try:
641 self.socket.send(msg)
642 except socket.error:
643 self._connect_unixsocket(self.address)
644 self.socket.send(msg)
Guido van Rossum57102f82002-11-13 16:15:58 +0000645 else:
646 self.socket.sendto(msg, self.address)
Vinay Sajip85c19092005-10-31 13:14:19 +0000647 except (KeyboardInterrupt, SystemExit):
648 raise
Guido van Rossum57102f82002-11-13 16:15:58 +0000649 except:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000650 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000651
652class SMTPHandler(logging.Handler):
653 """
654 A handler class which sends an SMTP email for each logging event.
655 """
656 def __init__(self, mailhost, fromaddr, toaddrs, subject):
657 """
658 Initialize the handler.
659
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.
663 """
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
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000673 if type(toaddrs) == types.StringType:
674 toaddrs = [toaddrs]
Guido van Rossum57102f82002-11-13 16:15:58 +0000675 self.toaddrs = toaddrs
676 self.subject = subject
677
678 def getSubject(self, record):
679 """
680 Determine the subject for the email.
681
682 If you want to specify a subject line which is record-dependent,
683 override this method.
684 """
685 return self.subject
686
Vinay Sajipe7d40662004-10-03 19:12:07 +0000687 weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
688
689 monthname = [None,
690 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
691 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
692
693 def date_time(self):
694 """
695 Return the current date and time formatted for a MIME header.
696 Needed for Python 1.5.2 (no email package available)
697 """
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
704
Guido van Rossum57102f82002-11-13 16:15:58 +0000705 def emit(self, record):
706 """
707 Emit a record.
708
709 Format the record and send it to the specified addressees.
710 """
711 try:
712 import smtplib
Vinay Sajipe7d40662004-10-03 19:12:07 +0000713 try:
714 from email.Utils import formatdate
715 except:
716 formatdate = self.date_time
Guido van Rossum57102f82002-11-13 16:15:58 +0000717 port = self.mailport
718 if not port:
719 port = smtplib.SMTP_PORT
720 smtp = smtplib.SMTP(self.mailhost, port)
721 msg = self.format(record)
Neal Norwitzf297bd12003-04-23 03:49:43 +0000722 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 +0000723 self.fromaddr,
724 string.join(self.toaddrs, ","),
Neal Norwitzf297bd12003-04-23 03:49:43 +0000725 self.getSubject(record),
Martin v. Löwis318a12e2004-08-18 12:27:40 +0000726 formatdate(), msg)
Guido van Rossum57102f82002-11-13 16:15:58 +0000727 smtp.sendmail(self.fromaddr, self.toaddrs, msg)
728 smtp.quit()
Vinay Sajip245a5ab2005-10-31 14:27:01 +0000729 except (KeyboardInterrupt, SystemExit):
730 raise
Guido van Rossum57102f82002-11-13 16:15:58 +0000731 except:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000732 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000733
734class NTEventLogHandler(logging.Handler):
735 """
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.
743 """
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,
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000761 logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE,
Guido van Rossum57102f82002-11-13 16:15:58 +0000762 logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE,
763 logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE,
764 }
765 except ImportError:
766 print "The Python Win32 extensions for NT (service, event "\
767 "logging) appear not to be available."
768 self._welu = None
769
770 def getMessageID(self, record):
771 """
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.
777 """
778 return 1
779
780 def getEventCategory(self, record):
781 """
782 Return the event category for the record.
783
784 Override this if you want to specify your own categories. This version
785 returns 0.
786 """
787 return 0
788
789 def getEventType(self, record):
790 """
791 Return the event type for the record.
792
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,
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000796 WARNING, ERROR and CRITICAL. If you are using your own levels you will
Guido van Rossum57102f82002-11-13 16:15:58 +0000797 either need to override this method or place a suitable dictionary in
798 the handler's typemap attribute.
799 """
800 return self.typemap.get(record.levelno, self.deftype)
801
802 def emit(self, record):
803 """
804 Emit a record.
805
806 Determine the message ID, event category and event type. Then
807 log the message in the NT event log.
808 """
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])
Vinay Sajip245a5ab2005-10-31 14:27:01 +0000816 except (KeyboardInterrupt, SystemExit):
817 raise
Guido van Rossum57102f82002-11-13 16:15:58 +0000818 except:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000819 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000820
821 def close(self):
822 """
823 Clean up this handler.
824
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.
830 """
831 #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype)
Vinay Sajip48cfe382004-02-20 13:17:27 +0000832 logging.Handler.close(self)
Guido van Rossum57102f82002-11-13 16:15:58 +0000833
834class HTTPHandler(logging.Handler):
835 """
836 A class which sends records to a Web server, using either GET or
837 POST semantics.
838 """
839 def __init__(self, host, url, method="GET"):
840 """
841 Initialize the instance with the host, the request URL, and the method
842 ("GET" or "POST")
843 """
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
851
Neal Norwitzf297bd12003-04-23 03:49:43 +0000852 def mapLogRecord(self, record):
853 """
854 Default implementation of mapping the log record into a dict
Vinay Sajip48cfe382004-02-20 13:17:27 +0000855 that is sent as the CGI data. Overwrite in your class.
Neal Norwitzf297bd12003-04-23 03:49:43 +0000856 Contributed by Franz Glasner.
857 """
858 return record.__dict__
859
Guido van Rossum57102f82002-11-13 16:15:58 +0000860 def emit(self, record):
861 """
862 Emit a record.
863
864 Send the record to the Web server as an URL-encoded dictionary
865 """
866 try:
867 import httplib, urllib
Vinay Sajipb7935062005-10-11 13:15:31 +0000868 host = self.host
869 h = httplib.HTTP(host)
Guido van Rossum57102f82002-11-13 16:15:58 +0000870 url = self.url
Neal Norwitzf297bd12003-04-23 03:49:43 +0000871 data = urllib.urlencode(self.mapLogRecord(record))
Guido van Rossum57102f82002-11-13 16:15:58 +0000872 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)
Vinay Sajipb7935062005-10-11 13:15:31 +0000879 # 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)
Guido van Rossum57102f82002-11-13 16:15:58 +0000885 if self.method == "POST":
Vinay Sajipb7935062005-10-11 13:15:31 +0000886 h.putheader("Content-type",
887 "application/x-www-form-urlencoded")
Guido van Rossum57102f82002-11-13 16:15:58 +0000888 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
Vinay Sajip245a5ab2005-10-31 14:27:01 +0000893 except (KeyboardInterrupt, SystemExit):
894 raise
Guido van Rossum57102f82002-11-13 16:15:58 +0000895 except:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000896 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000897
898class BufferingHandler(logging.Handler):
899 """
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.
903 """
904 def __init__(self, capacity):
905 """
906 Initialize the handler with the buffer size.
907 """
908 logging.Handler.__init__(self)
909 self.capacity = capacity
910 self.buffer = []
911
912 def shouldFlush(self, record):
913 """
914 Should the handler flush its buffer?
915
916 Returns true if the buffer is up to capacity. This method can be
917 overridden to implement custom flushing strategies.
918 """
919 return (len(self.buffer) >= self.capacity)
920
921 def emit(self, record):
922 """
923 Emit a record.
924
925 Append the record. If shouldFlush() tells us to, call flush() to process
926 the buffer.
927 """
928 self.buffer.append(record)
929 if self.shouldFlush(record):
930 self.flush()
931
932 def flush(self):
933 """
934 Override to implement custom flushing behaviour.
935
936 This version just zaps the buffer to empty.
937 """
938 self.buffer = []
939
Vinay Sajipf42d95e2004-02-21 22:14:34 +0000940 def close(self):
941 """
942 Close the handler.
943
944 This version just flushes and chains to the parent class' close().
945 """
946 self.flush()
947 logging.Handler.close(self)
948
Guido van Rossum57102f82002-11-13 16:15:58 +0000949class MemoryHandler(BufferingHandler):
950 """
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.
954 """
955 def __init__(self, capacity, flushLevel=logging.ERROR, target=None):
956 """
957 Initialize the handler with the buffer size, the level at which
958 flushing should occur and an optional target.
959
960 Note that without a target being set either here or via setTarget(),
961 a MemoryHandler is no use to anyone!
962 """
963 BufferingHandler.__init__(self, capacity)
964 self.flushLevel = flushLevel
965 self.target = target
966
967 def shouldFlush(self, record):
968 """
969 Check for buffer full or a record at the flushLevel or higher.
970 """
971 return (len(self.buffer) >= self.capacity) or \
972 (record.levelno >= self.flushLevel)
973
974 def setTarget(self, target):
975 """
976 Set the target handler for this handler.
977 """
978 self.target = target
979
980 def flush(self):
981 """
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.
985 """
986 if self.target:
987 for record in self.buffer:
988 self.target.handle(record)
989 self.buffer = []
990
991 def close(self):
992 """
993 Flush, set the target to None and lose the buffer.
994 """
995 self.flush()
996 self.target = None
Vinay Sajip48cfe382004-02-20 13:17:27 +0000997 BufferingHandler.close(self)