blob: 949d393015ce3c803ef6c440591d6e1862036b9f [file] [log] [blame]
Vinay Sajipb3d8a062007-01-16 09:50:07 +00001# Copyright 2001-2007 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 Sajipe5aefa02008-04-02 21:09:27 +000025Copyright (C) 2001-2008 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 Sajipe5aefa02008-04-02 21:09:27 +000030import logging, socket, types, os, string, cPickle, struct, time, re
Vinay Sajip73306b02007-01-14 21:49:59 +000031from stat import ST_DEV, ST_INO
Guido van Rossum57102f82002-11-13 16:15:58 +000032
Vinay Sajip4600f112005-03-13 09:56:36 +000033try:
34 import codecs
35except ImportError:
36 codecs = None
37
Guido van Rossum57102f82002-11-13 16:15:58 +000038#
39# Some constants...
40#
41
42DEFAULT_TCP_LOGGING_PORT = 9020
43DEFAULT_UDP_LOGGING_PORT = 9021
44DEFAULT_HTTP_LOGGING_PORT = 9022
45DEFAULT_SOAP_LOGGING_PORT = 9023
46SYSLOG_UDP_PORT = 514
47
Vinay Sajip4b4a63e2006-05-02 08:35:36 +000048_MIDNIGHT = 24 * 60 * 60 # number of seconds in a day
49
Vinay Sajip17c52d82004-07-03 11:48:34 +000050class BaseRotatingHandler(logging.FileHandler):
51 """
52 Base class for handlers that rotate log files at a certain point.
53 Not meant to be instantiated directly. Instead, use RotatingFileHandler
54 or TimedRotatingFileHandler.
55 """
Vinay Sajip92aa2f82008-01-24 12:37:33 +000056 def __init__(self, filename, mode, encoding=None, delay=0):
Vinay Sajip17c52d82004-07-03 11:48:34 +000057 """
58 Use the specified filename for streamed logging
59 """
Vinay Sajip4600f112005-03-13 09:56:36 +000060 if codecs is None:
61 encoding = None
Vinay Sajip92aa2f82008-01-24 12:37:33 +000062 logging.FileHandler.__init__(self, filename, mode, encoding, delay)
Vinay Sajip4600f112005-03-13 09:56:36 +000063 self.mode = mode
64 self.encoding = encoding
Guido van Rossum57102f82002-11-13 16:15:58 +000065
Vinay Sajip17c52d82004-07-03 11:48:34 +000066 def emit(self, record):
67 """
68 Emit a record.
69
70 Output the record to the file, catering for rollover as described
71 in doRollover().
72 """
Vinay Sajip3970c112004-07-08 10:24:04 +000073 try:
74 if self.shouldRollover(record):
75 self.doRollover()
76 logging.FileHandler.emit(self, record)
Vinay Sajip85c19092005-10-31 13:14:19 +000077 except (KeyboardInterrupt, SystemExit):
78 raise
Vinay Sajip3970c112004-07-08 10:24:04 +000079 except:
80 self.handleError(record)
Vinay Sajip17c52d82004-07-03 11:48:34 +000081
82class RotatingFileHandler(BaseRotatingHandler):
83 """
84 Handler for logging to a set of files, which switches from one file
85 to the next when the current file reaches a certain size.
86 """
Vinay Sajip92aa2f82008-01-24 12:37:33 +000087 def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0):
Guido van Rossum57102f82002-11-13 16:15:58 +000088 """
89 Open the specified file and use it as the stream for logging.
90
91 By default, the file grows indefinitely. You can specify particular
92 values of maxBytes and backupCount to allow the file to rollover at
93 a predetermined size.
94
95 Rollover occurs whenever the current log file is nearly maxBytes in
96 length. If backupCount is >= 1, the system will successively create
97 new files with the same pathname as the base file, but with extensions
98 ".1", ".2" etc. appended to it. For example, with a backupCount of 5
99 and a base file name of "app.log", you would get "app.log",
100 "app.log.1", "app.log.2", ... through to "app.log.5". The file being
101 written to is always "app.log" - when it gets filled up, it is closed
102 and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc.
103 exist, then they are renamed to "app.log.2", "app.log.3" etc.
104 respectively.
105
106 If maxBytes is zero, rollover never occurs.
107 """
Vinay Sajip17c52d82004-07-03 11:48:34 +0000108 if maxBytes > 0:
Vinay Sajip4600f112005-03-13 09:56:36 +0000109 mode = 'a' # doesn't make sense otherwise!
Vinay Sajip92aa2f82008-01-24 12:37:33 +0000110 BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
Guido van Rossum57102f82002-11-13 16:15:58 +0000111 self.maxBytes = maxBytes
112 self.backupCount = backupCount
Guido van Rossum57102f82002-11-13 16:15:58 +0000113
114 def doRollover(self):
115 """
116 Do a rollover, as described in __init__().
117 """
118
119 self.stream.close()
120 if self.backupCount > 0:
121 for i in range(self.backupCount - 1, 0, -1):
122 sfn = "%s.%d" % (self.baseFilename, i)
123 dfn = "%s.%d" % (self.baseFilename, i + 1)
124 if os.path.exists(sfn):
125 #print "%s -> %s" % (sfn, dfn)
126 if os.path.exists(dfn):
127 os.remove(dfn)
128 os.rename(sfn, dfn)
129 dfn = self.baseFilename + ".1"
130 if os.path.exists(dfn):
131 os.remove(dfn)
Vinay Sajip6dd59f12006-06-27 07:34:37 +0000132 os.rename(self.baseFilename, dfn)
Guido van Rossum57102f82002-11-13 16:15:58 +0000133 #print "%s -> %s" % (self.baseFilename, dfn)
Vinay Sajipb3d8a062007-01-16 09:50:07 +0000134 self.mode = 'w'
135 self.stream = self._open()
Guido van Rossum57102f82002-11-13 16:15:58 +0000136
Vinay Sajip17c52d82004-07-03 11:48:34 +0000137 def shouldRollover(self, record):
Guido van Rossum57102f82002-11-13 16:15:58 +0000138 """
Vinay Sajip17c52d82004-07-03 11:48:34 +0000139 Determine if rollover should occur.
Guido van Rossum57102f82002-11-13 16:15:58 +0000140
Vinay Sajip17c52d82004-07-03 11:48:34 +0000141 Basically, see if the supplied record would cause the file to exceed
142 the size limit we have.
Guido van Rossum57102f82002-11-13 16:15:58 +0000143 """
144 if self.maxBytes > 0: # are we rolling over?
145 msg = "%s\n" % self.format(record)
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000146 self.stream.seek(0, 2) #due to non-posix-compliant Windows feature
Guido van Rossum57102f82002-11-13 16:15:58 +0000147 if self.stream.tell() + len(msg) >= self.maxBytes:
Vinay Sajip17c52d82004-07-03 11:48:34 +0000148 return 1
149 return 0
Guido van Rossum57102f82002-11-13 16:15:58 +0000150
Vinay Sajip17c52d82004-07-03 11:48:34 +0000151class TimedRotatingFileHandler(BaseRotatingHandler):
152 """
153 Handler for logging to a file, rotating the log file at certain timed
154 intervals.
155
156 If backupCount is > 0, when rollover is done, no more than backupCount
157 files are kept - the oldest ones are deleted.
158 """
Vinay Sajip92aa2f82008-01-24 12:37:33 +0000159 def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=0):
160 BaseRotatingHandler.__init__(self, filename, 'a', encoding, delay)
Vinay Sajip17c52d82004-07-03 11:48:34 +0000161 self.when = string.upper(when)
162 self.backupCount = backupCount
163 # Calculate the real rollover interval, which is just the number of
164 # seconds between rollovers. Also set the filename suffix used when
165 # a rollover occurs. Current 'when' events supported:
166 # S - Seconds
167 # M - Minutes
168 # H - Hours
169 # D - Days
170 # midnight - roll over at midnight
171 # W{0-6} - roll over on a certain day; 0 - Monday
172 #
173 # Case of the 'when' specifier is not important; lower or upper case
174 # will work.
175 currentTime = int(time.time())
176 if self.when == 'S':
177 self.interval = 1 # one second
178 self.suffix = "%Y-%m-%d_%H-%M-%S"
Vinay Sajipe5aefa02008-04-02 21:09:27 +0000179 self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$"
Vinay Sajip17c52d82004-07-03 11:48:34 +0000180 elif self.when == 'M':
181 self.interval = 60 # one minute
182 self.suffix = "%Y-%m-%d_%H-%M"
Vinay Sajipe5aefa02008-04-02 21:09:27 +0000183 self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}$"
Vinay Sajip17c52d82004-07-03 11:48:34 +0000184 elif self.when == 'H':
185 self.interval = 60 * 60 # one hour
186 self.suffix = "%Y-%m-%d_%H"
Vinay Sajipe5aefa02008-04-02 21:09:27 +0000187 self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}$"
Vinay Sajip17c52d82004-07-03 11:48:34 +0000188 elif self.when == 'D' or self.when == 'MIDNIGHT':
189 self.interval = 60 * 60 * 24 # one day
190 self.suffix = "%Y-%m-%d"
Vinay Sajipe5aefa02008-04-02 21:09:27 +0000191 self.extMatch = r"^\d{4}-\d{2}-\d{2}$"
Vinay Sajip17c52d82004-07-03 11:48:34 +0000192 elif self.when.startswith('W'):
193 self.interval = 60 * 60 * 24 * 7 # one week
194 if len(self.when) != 2:
195 raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when)
196 if self.when[1] < '0' or self.when[1] > '6':
197 raise ValueError("Invalid day specified for weekly rollover: %s" % self.when)
198 self.dayOfWeek = int(self.when[1])
199 self.suffix = "%Y-%m-%d"
Vinay Sajipe5aefa02008-04-02 21:09:27 +0000200 self.extMatch = r"^\d{4}-\d{2}-\d{2}$"
Vinay Sajip17c52d82004-07-03 11:48:34 +0000201 else:
202 raise ValueError("Invalid rollover interval specified: %s" % self.when)
203
Vinay Sajipe5aefa02008-04-02 21:09:27 +0000204 self.extMatch = re.compile(self.extMatch)
Vinay Sajipe7d40662004-10-03 19:12:07 +0000205 self.interval = self.interval * interval # multiply by units requested
Vinay Sajip17c52d82004-07-03 11:48:34 +0000206 self.rolloverAt = currentTime + self.interval
207
208 # If we are rolling over at midnight or weekly, then the interval is already known.
209 # What we need to figure out is WHEN the next interval is. In other words,
210 # if you are rolling over at midnight, then your base interval is 1 day,
211 # but you want to start that one day clock at midnight, not now. So, we
212 # have to fudge the rolloverAt value in order to trigger the first rollover
213 # at the right time. After that, the regular interval will take care of
214 # the rest. Note that this code doesn't care about leap seconds. :)
215 if self.when == 'MIDNIGHT' or self.when.startswith('W'):
216 # This could be done with less code, but I wanted it to be clear
217 t = time.localtime(currentTime)
218 currentHour = t[3]
219 currentMinute = t[4]
220 currentSecond = t[5]
221 # r is the number of seconds left between now and midnight
Vinay Sajip4b4a63e2006-05-02 08:35:36 +0000222 r = _MIDNIGHT - ((currentHour * 60 + currentMinute) * 60 +
223 currentSecond)
Vinay Sajip17c52d82004-07-03 11:48:34 +0000224 self.rolloverAt = currentTime + r
225 # If we are rolling over on a certain day, add in the number of days until
226 # the next rollover, but offset by 1 since we just calculated the time
227 # until the next day starts. There are three cases:
228 # Case 1) The day to rollover is today; in this case, do nothing
229 # Case 2) The day to rollover is further in the interval (i.e., today is
230 # day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to
231 # next rollover is simply 6 - 2 - 1, or 3.
232 # Case 3) The day to rollover is behind us in the interval (i.e., today
233 # is day 5 (Saturday) and rollover is on day 3 (Thursday).
234 # Days to rollover is 6 - 5 + 3, or 4. In this case, it's the
235 # number of days left in the current week (1) plus the number
236 # of days in the next week until the rollover day (3).
Vinay Sajipae747dc2008-01-21 17:02:26 +0000237 # The calculations described in 2) and 3) above need to have a day added.
238 # This is because the above time calculation takes us to midnight on this
239 # day, i.e. the start of the next day.
Vinay Sajip17c52d82004-07-03 11:48:34 +0000240 if when.startswith('W'):
241 day = t[6] # 0 is Monday
Vinay Sajipbababa32007-10-24 10:47:06 +0000242 if day != self.dayOfWeek:
243 if day < self.dayOfWeek:
Vinay Sajipae747dc2008-01-21 17:02:26 +0000244 daysToWait = self.dayOfWeek - day
Vinay Sajipbababa32007-10-24 10:47:06 +0000245 else:
Vinay Sajipae747dc2008-01-21 17:02:26 +0000246 daysToWait = 6 - day + self.dayOfWeek + 1
Vinay Sajipe5aefa02008-04-02 21:09:27 +0000247 newRolloverAt = self.rolloverAt + (daysToWait * (60 * 60 * 24))
248 dstNow = t[-1]
249 dstAtRollover = time.localtime(newRolloverAt)[-1]
250 if dstNow != dstAtRollover:
251 if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
252 newRolloverAt = newRolloverAt - 3600
253 else: # DST bows out before next rollover, so we need to add an hour
254 newRolloverAt = newRolloverAt + 3600
255 self.rolloverAt = newRolloverAt
Vinay Sajip17c52d82004-07-03 11:48:34 +0000256
Vinay Sajip5e9e9e12004-07-12 09:21:41 +0000257 #print "Will rollover at %d, %d seconds from now" % (self.rolloverAt, self.rolloverAt - currentTime)
Vinay Sajip17c52d82004-07-03 11:48:34 +0000258
259 def shouldRollover(self, record):
260 """
Vinay Sajipe5aefa02008-04-02 21:09:27 +0000261 Determine if rollover should occur.
Vinay Sajip17c52d82004-07-03 11:48:34 +0000262
263 record is not used, as we are just comparing times, but it is needed so
Vinay Sajipe5aefa02008-04-02 21:09:27 +0000264 the method signatures are the same
Vinay Sajip17c52d82004-07-03 11:48:34 +0000265 """
266 t = int(time.time())
267 if t >= self.rolloverAt:
268 return 1
Vinay Sajip5e9e9e12004-07-12 09:21:41 +0000269 #print "No need to rollover: %d, %d" % (t, self.rolloverAt)
Vinay Sajip17c52d82004-07-03 11:48:34 +0000270 return 0
271
Vinay Sajipe5aefa02008-04-02 21:09:27 +0000272 def getFilesToDelete(self):
273 """
274 Determine the files to delete when rolling over.
275
276 More specific than the earlier method, which just used glob.glob().
277 """
278 dirName, baseName = os.path.split(self.baseFilename)
279 fileNames = os.listdir(dirName)
280 result = []
281 prefix = baseName + "."
282 plen = len(prefix)
283 for fileName in fileNames:
284 if fileName[:plen] == prefix:
285 suffix = fileName[plen:]
286 if self.extMatch.match(suffix):
287 result.append(fileName)
288 result.sort()
289 if len(result) < self.backupCount:
290 result = []
291 else:
292 result = result[:len(result) - self.backupCount]
293 return result
294
Vinay Sajip17c52d82004-07-03 11:48:34 +0000295 def doRollover(self):
296 """
297 do a rollover; in this case, a date/time stamp is appended to the filename
298 when the rollover happens. However, you want the file to be named for the
299 start of the interval, not the current time. If there is a backup count,
300 then we have to get a list of matching filenames, sort them and remove
301 the one with the oldest suffix.
302 """
303 self.stream.close()
304 # get the time that this sequence started at and make it a TimeTuple
305 t = self.rolloverAt - self.interval
306 timeTuple = time.localtime(t)
307 dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple)
308 if os.path.exists(dfn):
309 os.remove(dfn)
Vinay Sajip6dd59f12006-06-27 07:34:37 +0000310 os.rename(self.baseFilename, dfn)
Vinay Sajip17c52d82004-07-03 11:48:34 +0000311 if self.backupCount > 0:
312 # find the oldest log file and delete it
Vinay Sajipe5aefa02008-04-02 21:09:27 +0000313 #s = glob.glob(self.baseFilename + ".20*")
314 #if len(s) > self.backupCount:
315 # s.sort()
316 # os.remove(s[0])
317 for s in self.getFilesToDelete():
318 os.remove(s)
Vinay Sajip5e9e9e12004-07-12 09:21:41 +0000319 #print "%s -> %s" % (self.baseFilename, dfn)
Vinay Sajipb3d8a062007-01-16 09:50:07 +0000320 self.mode = 'w'
321 self.stream = self._open()
Vinay Sajipe5aefa02008-04-02 21:09:27 +0000322 newRolloverAt = self.rolloverAt + self.interval
323 currentTime = int(time.time())
324 while newRolloverAt <= currentTime:
325 newRolloverAt = newRolloverAt + self.interval
326 #If DST changes and midnight or weekly rollover, adjust for this.
327 if self.when == 'MIDNIGHT' or self.when.startswith('W'):
328 dstNow = time.localtime(currentTime)[-1]
329 dstAtRollover = time.localtime(newRolloverAt)[-1]
330 if dstNow != dstAtRollover:
331 if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
332 newRolloverAt = newRolloverAt - 3600
333 else: # DST bows out before next rollover, so we need to add an hour
334 newRolloverAt = newRolloverAt + 3600
335 self.rolloverAt = newRolloverAt
Guido van Rossum57102f82002-11-13 16:15:58 +0000336
Vinay Sajip73306b02007-01-14 21:49:59 +0000337class WatchedFileHandler(logging.FileHandler):
338 """
339 A handler for logging to a file, which watches the file
340 to see if it has changed while in use. This can happen because of
341 usage of programs such as newsyslog and logrotate which perform
342 log file rotation. This handler, intended for use under Unix,
343 watches the file to see if it has changed since the last emit.
344 (A file has changed if its device or inode have changed.)
345 If it has changed, the old file stream is closed, and the file
346 opened to get a new stream.
347
348 This handler is not appropriate for use under Windows, because
349 under Windows open files cannot be moved or renamed - logging
350 opens the files with exclusive locks - and so there is no need
351 for such a handler. Furthermore, ST_INO is not supported under
352 Windows; stat always returns zero for this value.
353
354 This handler is based on a suggestion and patch by Chad J.
355 Schroeder.
356 """
Vinay Sajip92aa2f82008-01-24 12:37:33 +0000357 def __init__(self, filename, mode='a', encoding=None, delay=0):
358 logging.FileHandler.__init__(self, filename, mode, encoding, delay)
359 if not os.path.exists(self.baseFilename):
360 self.dev, self.ino = -1, -1
361 else:
362 stat = os.stat(self.baseFilename)
363 self.dev, self.ino = stat[ST_DEV], stat[ST_INO]
Vinay Sajip73306b02007-01-14 21:49:59 +0000364
365 def emit(self, record):
366 """
367 Emit a record.
368
369 First check if the underlying file has changed, and if it
370 has, close the old stream and reopen the file to get the
371 current stream.
372 """
373 if not os.path.exists(self.baseFilename):
374 stat = None
375 changed = 1
376 else:
377 stat = os.stat(self.baseFilename)
378 changed = (stat[ST_DEV] != self.dev) or (stat[ST_INO] != self.ino)
Vinay Sajip92aa2f82008-01-24 12:37:33 +0000379 if changed and self.stream is not None:
Vinay Sajip73306b02007-01-14 21:49:59 +0000380 self.stream.flush()
381 self.stream.close()
382 self.stream = self._open()
383 if stat is None:
384 stat = os.stat(self.baseFilename)
385 self.dev, self.ino = stat[ST_DEV], stat[ST_INO]
386 logging.FileHandler.emit(self, record)
387
Guido van Rossum57102f82002-11-13 16:15:58 +0000388class SocketHandler(logging.Handler):
389 """
390 A handler class which writes logging records, in pickle format, to
391 a streaming socket. The socket is kept open across logging calls.
392 If the peer resets it, an attempt is made to reconnect on the next call.
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000393 The pickle which is sent is that of the LogRecord's attribute dictionary
394 (__dict__), so that the receiver does not need to have the logging module
395 installed in order to process the logging event.
396
397 To unpickle the record at the receiving end into a LogRecord, use the
398 makeLogRecord function.
Guido van Rossum57102f82002-11-13 16:15:58 +0000399 """
400
401 def __init__(self, host, port):
402 """
403 Initializes the handler with a specific host address and port.
404
405 The attribute 'closeOnError' is set to 1 - which means that if
406 a socket error occurs, the socket is silently closed and then
407 reopened on the next logging call.
408 """
409 logging.Handler.__init__(self)
410 self.host = host
411 self.port = port
412 self.sock = None
413 self.closeOnError = 0
Vinay Sajip48cfe382004-02-20 13:17:27 +0000414 self.retryTime = None
415 #
416 # Exponential backoff parameters.
417 #
418 self.retryStart = 1.0
419 self.retryMax = 30.0
420 self.retryFactor = 2.0
Guido van Rossum57102f82002-11-13 16:15:58 +0000421
Vinay Sajipaa7b16a2007-04-09 16:16:10 +0000422 def makeSocket(self, timeout=1):
Guido van Rossum57102f82002-11-13 16:15:58 +0000423 """
424 A factory method which allows subclasses to define the precise
425 type of socket they want.
426 """
427 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Vinay Sajipaa7b16a2007-04-09 16:16:10 +0000428 if hasattr(s, 'settimeout'):
429 s.settimeout(timeout)
Guido van Rossum57102f82002-11-13 16:15:58 +0000430 s.connect((self.host, self.port))
431 return s
432
Vinay Sajip48cfe382004-02-20 13:17:27 +0000433 def createSocket(self):
434 """
435 Try to create a socket, using an exponential backoff with
436 a max retry time. Thanks to Robert Olson for the original patch
437 (SF #815911) which has been slightly refactored.
438 """
439 now = time.time()
440 # Either retryTime is None, in which case this
441 # is the first time back after a disconnect, or
442 # we've waited long enough.
443 if self.retryTime is None:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000444 attempt = 1
Vinay Sajip48cfe382004-02-20 13:17:27 +0000445 else:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000446 attempt = (now >= self.retryTime)
Vinay Sajip48cfe382004-02-20 13:17:27 +0000447 if attempt:
448 try:
449 self.sock = self.makeSocket()
450 self.retryTime = None # next time, no delay before trying
Vinay Sajipc683a872007-01-08 18:50:32 +0000451 except socket.error:
Vinay Sajip48cfe382004-02-20 13:17:27 +0000452 #Creation failed, so set the retry time and return.
453 if self.retryTime is None:
454 self.retryPeriod = self.retryStart
455 else:
456 self.retryPeriod = self.retryPeriod * self.retryFactor
457 if self.retryPeriod > self.retryMax:
458 self.retryPeriod = self.retryMax
459 self.retryTime = now + self.retryPeriod
460
Guido van Rossum57102f82002-11-13 16:15:58 +0000461 def send(self, s):
462 """
463 Send a pickled string to the socket.
464
465 This function allows for partial sends which can happen when the
466 network is busy.
467 """
Vinay Sajip48cfe382004-02-20 13:17:27 +0000468 if self.sock is None:
469 self.createSocket()
470 #self.sock can be None either because we haven't reached the retry
471 #time yet, or because we have reached the retry time and retried,
472 #but are still unable to connect.
473 if self.sock:
474 try:
475 if hasattr(self.sock, "sendall"):
476 self.sock.sendall(s)
477 else:
478 sentsofar = 0
479 left = len(s)
480 while left > 0:
481 sent = self.sock.send(s[sentsofar:])
482 sentsofar = sentsofar + sent
483 left = left - sent
484 except socket.error:
485 self.sock.close()
486 self.sock = None # so we can call createSocket next time
Guido van Rossum57102f82002-11-13 16:15:58 +0000487
488 def makePickle(self, record):
489 """
490 Pickles the record in binary format with a length prefix, and
491 returns it ready for transmission across the socket.
492 """
Vinay Sajip48cfe382004-02-20 13:17:27 +0000493 ei = record.exc_info
494 if ei:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000495 dummy = self.format(record) # just to get traceback text into record.exc_text
496 record.exc_info = None # to avoid Unpickleable error
Guido van Rossum57102f82002-11-13 16:15:58 +0000497 s = cPickle.dumps(record.__dict__, 1)
Vinay Sajip48cfe382004-02-20 13:17:27 +0000498 if ei:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000499 record.exc_info = ei # for next handler
Guido van Rossum57102f82002-11-13 16:15:58 +0000500 slen = struct.pack(">L", len(s))
501 return slen + s
502
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000503 def handleError(self, record):
Guido van Rossum57102f82002-11-13 16:15:58 +0000504 """
505 Handle an error during logging.
506
507 An error has occurred during logging. Most likely cause -
508 connection lost. Close the socket so that we can retry on the
509 next event.
510 """
511 if self.closeOnError and self.sock:
512 self.sock.close()
513 self.sock = None #try to reconnect next time
514 else:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000515 logging.Handler.handleError(self, record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000516
517 def emit(self, record):
518 """
519 Emit a record.
520
521 Pickles the record and writes it to the socket in binary format.
522 If there is an error with the socket, silently drop the packet.
523 If there was a problem with the socket, re-establishes the
524 socket.
525 """
526 try:
527 s = self.makePickle(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000528 self.send(s)
Vinay Sajip85c19092005-10-31 13:14:19 +0000529 except (KeyboardInterrupt, SystemExit):
530 raise
Guido van Rossum57102f82002-11-13 16:15:58 +0000531 except:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000532 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000533
534 def close(self):
535 """
536 Closes the socket.
537 """
538 if self.sock:
539 self.sock.close()
540 self.sock = None
Vinay Sajip48cfe382004-02-20 13:17:27 +0000541 logging.Handler.close(self)
Guido van Rossum57102f82002-11-13 16:15:58 +0000542
543class DatagramHandler(SocketHandler):
544 """
545 A handler class which writes logging records, in pickle format, to
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000546 a datagram socket. The pickle which is sent is that of the LogRecord's
547 attribute dictionary (__dict__), so that the receiver does not need to
548 have the logging module installed in order to process the logging event.
549
550 To unpickle the record at the receiving end into a LogRecord, use the
551 makeLogRecord function.
Guido van Rossum57102f82002-11-13 16:15:58 +0000552
553 """
554 def __init__(self, host, port):
555 """
556 Initializes the handler with a specific host address and port.
557 """
558 SocketHandler.__init__(self, host, port)
559 self.closeOnError = 0
560
561 def makeSocket(self):
562 """
563 The factory method of SocketHandler is here overridden to create
564 a UDP socket (SOCK_DGRAM).
565 """
566 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
567 return s
568
569 def send(self, s):
570 """
571 Send a pickled string to a socket.
572
573 This function no longer allows for partial sends which can happen
574 when the network is busy - UDP does not guarantee delivery and
575 can deliver packets out of sequence.
576 """
Vinay Sajipfb154172004-08-24 09:36:23 +0000577 if self.sock is None:
578 self.createSocket()
Guido van Rossum57102f82002-11-13 16:15:58 +0000579 self.sock.sendto(s, (self.host, self.port))
580
581class SysLogHandler(logging.Handler):
582 """
583 A handler class which sends formatted logging records to a syslog
584 server. Based on Sam Rushing's syslog module:
585 http://www.nightmare.com/squirl/python-ext/misc/syslog.py
586 Contributed by Nicolas Untz (after which minor refactoring changes
587 have been made).
588 """
589
590 # from <linux/sys/syslog.h>:
591 # ======================================================================
592 # priorities/facilities are encoded into a single 32-bit quantity, where
593 # the bottom 3 bits are the priority (0-7) and the top 28 bits are the
594 # facility (0-big number). Both the priorities and the facilities map
595 # roughly one-to-one to strings in the syslogd(8) source code. This
596 # mapping is included in this file.
597 #
598 # priorities (these are ordered)
599
600 LOG_EMERG = 0 # system is unusable
601 LOG_ALERT = 1 # action must be taken immediately
602 LOG_CRIT = 2 # critical conditions
603 LOG_ERR = 3 # error conditions
604 LOG_WARNING = 4 # warning conditions
605 LOG_NOTICE = 5 # normal but significant condition
606 LOG_INFO = 6 # informational
607 LOG_DEBUG = 7 # debug-level messages
608
609 # facility codes
610 LOG_KERN = 0 # kernel messages
611 LOG_USER = 1 # random user-level messages
612 LOG_MAIL = 2 # mail system
613 LOG_DAEMON = 3 # system daemons
614 LOG_AUTH = 4 # security/authorization messages
615 LOG_SYSLOG = 5 # messages generated internally by syslogd
616 LOG_LPR = 6 # line printer subsystem
617 LOG_NEWS = 7 # network news subsystem
618 LOG_UUCP = 8 # UUCP subsystem
619 LOG_CRON = 9 # clock daemon
620 LOG_AUTHPRIV = 10 # security/authorization messages (private)
621
622 # other codes through 15 reserved for system use
623 LOG_LOCAL0 = 16 # reserved for local use
624 LOG_LOCAL1 = 17 # reserved for local use
625 LOG_LOCAL2 = 18 # reserved for local use
626 LOG_LOCAL3 = 19 # reserved for local use
627 LOG_LOCAL4 = 20 # reserved for local use
628 LOG_LOCAL5 = 21 # reserved for local use
629 LOG_LOCAL6 = 22 # reserved for local use
630 LOG_LOCAL7 = 23 # reserved for local use
631
632 priority_names = {
633 "alert": LOG_ALERT,
634 "crit": LOG_CRIT,
635 "critical": LOG_CRIT,
636 "debug": LOG_DEBUG,
637 "emerg": LOG_EMERG,
638 "err": LOG_ERR,
639 "error": LOG_ERR, # DEPRECATED
640 "info": LOG_INFO,
641 "notice": LOG_NOTICE,
642 "panic": LOG_EMERG, # DEPRECATED
643 "warn": LOG_WARNING, # DEPRECATED
644 "warning": LOG_WARNING,
645 }
646
647 facility_names = {
648 "auth": LOG_AUTH,
649 "authpriv": LOG_AUTHPRIV,
650 "cron": LOG_CRON,
651 "daemon": LOG_DAEMON,
652 "kern": LOG_KERN,
653 "lpr": LOG_LPR,
654 "mail": LOG_MAIL,
655 "news": LOG_NEWS,
656 "security": LOG_AUTH, # DEPRECATED
657 "syslog": LOG_SYSLOG,
658 "user": LOG_USER,
659 "uucp": LOG_UUCP,
660 "local0": LOG_LOCAL0,
661 "local1": LOG_LOCAL1,
662 "local2": LOG_LOCAL2,
663 "local3": LOG_LOCAL3,
664 "local4": LOG_LOCAL4,
665 "local5": LOG_LOCAL5,
666 "local6": LOG_LOCAL6,
667 "local7": LOG_LOCAL7,
668 }
669
Vinay Sajipdc579362006-07-20 23:20:12 +0000670 #The map below appears to be trivially lowercasing the key. However,
671 #there's more to it than meets the eye - in some locales, lowercasing
672 #gives unexpected results. See SF #1524081: in the Turkish locale,
673 #"INFO".lower() != "info"
674 priority_map = {
675 "DEBUG" : "debug",
676 "INFO" : "info",
677 "WARNING" : "warning",
678 "ERROR" : "error",
679 "CRITICAL" : "critical"
680 }
681
Guido van Rossum57102f82002-11-13 16:15:58 +0000682 def __init__(self, address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER):
683 """
684 Initialize a handler.
685
Vinay Sajip754a5fb2007-05-25 07:05:59 +0000686 If address is specified as a string, a UNIX socket is used. To log to a
687 local syslogd, "SysLogHandler(address="/dev/log")" can be used.
Guido van Rossum57102f82002-11-13 16:15:58 +0000688 If facility is not specified, LOG_USER is used.
689 """
690 logging.Handler.__init__(self)
691
692 self.address = address
693 self.facility = facility
694 if type(address) == types.StringType:
Guido van Rossum57102f82002-11-13 16:15:58 +0000695 self.unixsocket = 1
Vinay Sajip5492e172006-12-11 14:07:16 +0000696 self._connect_unixsocket(address)
Guido van Rossum57102f82002-11-13 16:15:58 +0000697 else:
Guido van Rossum57102f82002-11-13 16:15:58 +0000698 self.unixsocket = 0
Vinay Sajip5492e172006-12-11 14:07:16 +0000699 self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Guido van Rossum57102f82002-11-13 16:15:58 +0000700
701 self.formatter = None
702
Vinay Sajipa1974c12005-01-13 08:23:56 +0000703 def _connect_unixsocket(self, address):
704 self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
705 # syslog may require either DGRAM or STREAM sockets
706 try:
707 self.socket.connect(address)
708 except socket.error:
709 self.socket.close()
710 self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
Vinay Sajip8b6b53f2005-11-09 13:55:13 +0000711 self.socket.connect(address)
Vinay Sajipa1974c12005-01-13 08:23:56 +0000712
Guido van Rossum57102f82002-11-13 16:15:58 +0000713 # curious: when talking to the unix-domain '/dev/log' socket, a
714 # zero-terminator seems to be required. this string is placed
715 # into a class variable so that it can be overridden if
716 # necessary.
717 log_format_string = '<%d>%s\000'
718
Vinay Sajipdc579362006-07-20 23:20:12 +0000719 def encodePriority(self, facility, priority):
Guido van Rossum57102f82002-11-13 16:15:58 +0000720 """
721 Encode the facility and priority. You can pass in strings or
722 integers - if strings are passed, the facility_names and
723 priority_names mapping dictionaries are used to convert them to
724 integers.
725 """
726 if type(facility) == types.StringType:
727 facility = self.facility_names[facility]
728 if type(priority) == types.StringType:
729 priority = self.priority_names[priority]
730 return (facility << 3) | priority
731
732 def close (self):
733 """
734 Closes the socket.
735 """
736 if self.unixsocket:
737 self.socket.close()
Vinay Sajip48cfe382004-02-20 13:17:27 +0000738 logging.Handler.close(self)
Guido van Rossum57102f82002-11-13 16:15:58 +0000739
Vinay Sajipdc579362006-07-20 23:20:12 +0000740 def mapPriority(self, levelName):
741 """
742 Map a logging level name to a key in the priority_names map.
743 This is useful in two scenarios: when custom levels are being
744 used, and in the case where you can't do a straightforward
745 mapping by lowercasing the logging level name because of locale-
746 specific issues (see SF #1524081).
747 """
748 return self.priority_map.get(levelName, "warning")
749
Guido van Rossum57102f82002-11-13 16:15:58 +0000750 def emit(self, record):
751 """
752 Emit a record.
753
754 The record is formatted, and then sent to the syslog server. If
755 exception information is present, it is NOT sent to the server.
756 """
757 msg = self.format(record)
758 """
759 We need to convert record level to lowercase, maybe this will
760 change in the future.
761 """
762 msg = self.log_format_string % (
763 self.encodePriority(self.facility,
Vinay Sajipdc579362006-07-20 23:20:12 +0000764 self.mapPriority(record.levelname)),
765 msg)
Guido van Rossum57102f82002-11-13 16:15:58 +0000766 try:
767 if self.unixsocket:
Vinay Sajipa1974c12005-01-13 08:23:56 +0000768 try:
769 self.socket.send(msg)
770 except socket.error:
771 self._connect_unixsocket(self.address)
772 self.socket.send(msg)
Guido van Rossum57102f82002-11-13 16:15:58 +0000773 else:
774 self.socket.sendto(msg, self.address)
Vinay Sajip85c19092005-10-31 13:14:19 +0000775 except (KeyboardInterrupt, SystemExit):
776 raise
Guido van Rossum57102f82002-11-13 16:15:58 +0000777 except:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000778 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000779
780class SMTPHandler(logging.Handler):
781 """
782 A handler class which sends an SMTP email for each logging event.
783 """
Vinay Sajip70c8e8b2007-05-01 10:20:03 +0000784 def __init__(self, mailhost, fromaddr, toaddrs, subject, credentials=None):
Guido van Rossum57102f82002-11-13 16:15:58 +0000785 """
786 Initialize the handler.
787
788 Initialize the instance with the from and to addresses and subject
789 line of the email. To specify a non-standard SMTP port, use the
Vinay Sajip70c8e8b2007-05-01 10:20:03 +0000790 (host, port) tuple format for the mailhost argument. To specify
791 authentication credentials, supply a (username, password) tuple
792 for the credentials argument.
Guido van Rossum57102f82002-11-13 16:15:58 +0000793 """
794 logging.Handler.__init__(self)
795 if type(mailhost) == types.TupleType:
Vinay Sajip70c8e8b2007-05-01 10:20:03 +0000796 self.mailhost, self.mailport = mailhost
Guido van Rossum57102f82002-11-13 16:15:58 +0000797 else:
Vinay Sajip70c8e8b2007-05-01 10:20:03 +0000798 self.mailhost, self.mailport = mailhost, None
799 if type(credentials) == types.TupleType:
800 self.username, self.password = credentials
801 else:
802 self.username = None
Guido van Rossum57102f82002-11-13 16:15:58 +0000803 self.fromaddr = fromaddr
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000804 if type(toaddrs) == types.StringType:
805 toaddrs = [toaddrs]
Guido van Rossum57102f82002-11-13 16:15:58 +0000806 self.toaddrs = toaddrs
807 self.subject = subject
808
809 def getSubject(self, record):
810 """
811 Determine the subject for the email.
812
813 If you want to specify a subject line which is record-dependent,
814 override this method.
815 """
816 return self.subject
817
Vinay Sajipe7d40662004-10-03 19:12:07 +0000818 weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
819
820 monthname = [None,
821 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
822 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
823
824 def date_time(self):
825 """
826 Return the current date and time formatted for a MIME header.
827 Needed for Python 1.5.2 (no email package available)
828 """
829 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(time.time())
830 s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
831 self.weekdayname[wd],
832 day, self.monthname[month], year,
833 hh, mm, ss)
834 return s
835
Guido van Rossum57102f82002-11-13 16:15:58 +0000836 def emit(self, record):
837 """
838 Emit a record.
839
840 Format the record and send it to the specified addressees.
841 """
842 try:
843 import smtplib
Vinay Sajipe7d40662004-10-03 19:12:07 +0000844 try:
Georg Brandl5a096e12007-01-22 19:40:21 +0000845 from email.utils import formatdate
Vinay Sajipc683a872007-01-08 18:50:32 +0000846 except ImportError:
Vinay Sajipe7d40662004-10-03 19:12:07 +0000847 formatdate = self.date_time
Guido van Rossum57102f82002-11-13 16:15:58 +0000848 port = self.mailport
849 if not port:
850 port = smtplib.SMTP_PORT
851 smtp = smtplib.SMTP(self.mailhost, port)
852 msg = self.format(record)
Neal Norwitzf297bd12003-04-23 03:49:43 +0000853 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 +0000854 self.fromaddr,
855 string.join(self.toaddrs, ","),
Neal Norwitzf297bd12003-04-23 03:49:43 +0000856 self.getSubject(record),
Martin v. Löwis318a12e2004-08-18 12:27:40 +0000857 formatdate(), msg)
Vinay Sajip70c8e8b2007-05-01 10:20:03 +0000858 if self.username:
859 smtp.login(self.username, self.password)
Guido van Rossum57102f82002-11-13 16:15:58 +0000860 smtp.sendmail(self.fromaddr, self.toaddrs, msg)
861 smtp.quit()
Vinay Sajip245a5ab2005-10-31 14:27:01 +0000862 except (KeyboardInterrupt, SystemExit):
863 raise
Guido van Rossum57102f82002-11-13 16:15:58 +0000864 except:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000865 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000866
867class NTEventLogHandler(logging.Handler):
868 """
869 A handler class which sends events to the NT Event Log. Adds a
870 registry entry for the specified application name. If no dllname is
871 provided, win32service.pyd (which contains some basic message
872 placeholders) is used. Note that use of these placeholders will make
873 your event logs big, as the entire message source is held in the log.
874 If you want slimmer logs, you have to pass in the name of your own DLL
875 which contains the message definitions you want to use in the event log.
876 """
877 def __init__(self, appname, dllname=None, logtype="Application"):
878 logging.Handler.__init__(self)
879 try:
880 import win32evtlogutil, win32evtlog
881 self.appname = appname
882 self._welu = win32evtlogutil
883 if not dllname:
884 dllname = os.path.split(self._welu.__file__)
885 dllname = os.path.split(dllname[0])
886 dllname = os.path.join(dllname[0], r'win32service.pyd')
887 self.dllname = dllname
888 self.logtype = logtype
889 self._welu.AddSourceToRegistry(appname, dllname, logtype)
890 self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE
891 self.typemap = {
892 logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE,
893 logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE,
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000894 logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE,
Guido van Rossum57102f82002-11-13 16:15:58 +0000895 logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE,
896 logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE,
897 }
898 except ImportError:
899 print "The Python Win32 extensions for NT (service, event "\
900 "logging) appear not to be available."
901 self._welu = None
902
903 def getMessageID(self, record):
904 """
905 Return the message ID for the event record. If you are using your
906 own messages, you could do this by having the msg passed to the
907 logger being an ID rather than a formatting string. Then, in here,
908 you could use a dictionary lookup to get the message ID. This
909 version returns 1, which is the base message ID in win32service.pyd.
910 """
911 return 1
912
913 def getEventCategory(self, record):
914 """
915 Return the event category for the record.
916
917 Override this if you want to specify your own categories. This version
918 returns 0.
919 """
920 return 0
921
922 def getEventType(self, record):
923 """
924 Return the event type for the record.
925
926 Override this if you want to specify your own types. This version does
927 a mapping using the handler's typemap attribute, which is set up in
928 __init__() to a dictionary which contains mappings for DEBUG, INFO,
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000929 WARNING, ERROR and CRITICAL. If you are using your own levels you will
Guido van Rossum57102f82002-11-13 16:15:58 +0000930 either need to override this method or place a suitable dictionary in
931 the handler's typemap attribute.
932 """
933 return self.typemap.get(record.levelno, self.deftype)
934
935 def emit(self, record):
936 """
937 Emit a record.
938
939 Determine the message ID, event category and event type. Then
940 log the message in the NT event log.
941 """
942 if self._welu:
943 try:
944 id = self.getMessageID(record)
945 cat = self.getEventCategory(record)
946 type = self.getEventType(record)
947 msg = self.format(record)
948 self._welu.ReportEvent(self.appname, id, cat, type, [msg])
Vinay Sajip245a5ab2005-10-31 14:27:01 +0000949 except (KeyboardInterrupt, SystemExit):
950 raise
Guido van Rossum57102f82002-11-13 16:15:58 +0000951 except:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000952 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000953
954 def close(self):
955 """
956 Clean up this handler.
957
958 You can remove the application name from the registry as a
959 source of event log entries. However, if you do this, you will
960 not be able to see the events as you intended in the Event Log
961 Viewer - it needs to be able to access the registry to get the
962 DLL name.
963 """
964 #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype)
Vinay Sajip48cfe382004-02-20 13:17:27 +0000965 logging.Handler.close(self)
Guido van Rossum57102f82002-11-13 16:15:58 +0000966
967class HTTPHandler(logging.Handler):
968 """
969 A class which sends records to a Web server, using either GET or
970 POST semantics.
971 """
972 def __init__(self, host, url, method="GET"):
973 """
974 Initialize the instance with the host, the request URL, and the method
975 ("GET" or "POST")
976 """
977 logging.Handler.__init__(self)
978 method = string.upper(method)
979 if method not in ["GET", "POST"]:
980 raise ValueError, "method must be GET or POST"
981 self.host = host
982 self.url = url
983 self.method = method
984
Neal Norwitzf297bd12003-04-23 03:49:43 +0000985 def mapLogRecord(self, record):
986 """
987 Default implementation of mapping the log record into a dict
Vinay Sajip48cfe382004-02-20 13:17:27 +0000988 that is sent as the CGI data. Overwrite in your class.
Neal Norwitzf297bd12003-04-23 03:49:43 +0000989 Contributed by Franz Glasner.
990 """
991 return record.__dict__
992
Guido van Rossum57102f82002-11-13 16:15:58 +0000993 def emit(self, record):
994 """
995 Emit a record.
996
997 Send the record to the Web server as an URL-encoded dictionary
998 """
999 try:
1000 import httplib, urllib
Vinay Sajipb7935062005-10-11 13:15:31 +00001001 host = self.host
1002 h = httplib.HTTP(host)
Guido van Rossum57102f82002-11-13 16:15:58 +00001003 url = self.url
Neal Norwitzf297bd12003-04-23 03:49:43 +00001004 data = urllib.urlencode(self.mapLogRecord(record))
Guido van Rossum57102f82002-11-13 16:15:58 +00001005 if self.method == "GET":
1006 if (string.find(url, '?') >= 0):
1007 sep = '&'
1008 else:
1009 sep = '?'
1010 url = url + "%c%s" % (sep, data)
1011 h.putrequest(self.method, url)
Vinay Sajipb7935062005-10-11 13:15:31 +00001012 # support multiple hosts on one IP address...
1013 # need to strip optional :port from host, if present
1014 i = string.find(host, ":")
1015 if i >= 0:
1016 host = host[:i]
1017 h.putheader("Host", host)
Guido van Rossum57102f82002-11-13 16:15:58 +00001018 if self.method == "POST":
Vinay Sajipb7935062005-10-11 13:15:31 +00001019 h.putheader("Content-type",
1020 "application/x-www-form-urlencoded")
Guido van Rossum57102f82002-11-13 16:15:58 +00001021 h.putheader("Content-length", str(len(data)))
1022 h.endheaders()
1023 if self.method == "POST":
1024 h.send(data)
1025 h.getreply() #can't do anything with the result
Vinay Sajip245a5ab2005-10-31 14:27:01 +00001026 except (KeyboardInterrupt, SystemExit):
1027 raise
Guido van Rossum57102f82002-11-13 16:15:58 +00001028 except:
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001029 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +00001030
1031class BufferingHandler(logging.Handler):
1032 """
1033 A handler class which buffers logging records in memory. Whenever each
1034 record is added to the buffer, a check is made to see if the buffer should
1035 be flushed. If it should, then flush() is expected to do what's needed.
1036 """
1037 def __init__(self, capacity):
1038 """
1039 Initialize the handler with the buffer size.
1040 """
1041 logging.Handler.__init__(self)
1042 self.capacity = capacity
1043 self.buffer = []
1044
1045 def shouldFlush(self, record):
1046 """
1047 Should the handler flush its buffer?
1048
1049 Returns true if the buffer is up to capacity. This method can be
1050 overridden to implement custom flushing strategies.
1051 """
1052 return (len(self.buffer) >= self.capacity)
1053
1054 def emit(self, record):
1055 """
1056 Emit a record.
1057
1058 Append the record. If shouldFlush() tells us to, call flush() to process
1059 the buffer.
1060 """
1061 self.buffer.append(record)
1062 if self.shouldFlush(record):
1063 self.flush()
1064
1065 def flush(self):
1066 """
1067 Override to implement custom flushing behaviour.
1068
1069 This version just zaps the buffer to empty.
1070 """
1071 self.buffer = []
1072
Vinay Sajipf42d95e2004-02-21 22:14:34 +00001073 def close(self):
1074 """
1075 Close the handler.
1076
1077 This version just flushes and chains to the parent class' close().
1078 """
1079 self.flush()
1080 logging.Handler.close(self)
1081
Guido van Rossum57102f82002-11-13 16:15:58 +00001082class MemoryHandler(BufferingHandler):
1083 """
1084 A handler class which buffers logging records in memory, periodically
1085 flushing them to a target handler. Flushing occurs whenever the buffer
1086 is full, or when an event of a certain severity or greater is seen.
1087 """
1088 def __init__(self, capacity, flushLevel=logging.ERROR, target=None):
1089 """
1090 Initialize the handler with the buffer size, the level at which
1091 flushing should occur and an optional target.
1092
1093 Note that without a target being set either here or via setTarget(),
1094 a MemoryHandler is no use to anyone!
1095 """
1096 BufferingHandler.__init__(self, capacity)
1097 self.flushLevel = flushLevel
1098 self.target = target
1099
1100 def shouldFlush(self, record):
1101 """
1102 Check for buffer full or a record at the flushLevel or higher.
1103 """
1104 return (len(self.buffer) >= self.capacity) or \
1105 (record.levelno >= self.flushLevel)
1106
1107 def setTarget(self, target):
1108 """
1109 Set the target handler for this handler.
1110 """
1111 self.target = target
1112
1113 def flush(self):
1114 """
1115 For a MemoryHandler, flushing means just sending the buffered
1116 records to the target, if there is one. Override if you want
1117 different behaviour.
1118 """
1119 if self.target:
1120 for record in self.buffer:
1121 self.target.handle(record)
1122 self.buffer = []
1123
1124 def close(self):
1125 """
1126 Flush, set the target to None and lose the buffer.
1127 """
1128 self.flush()
1129 self.target = None
Vinay Sajip48cfe382004-02-20 13:17:27 +00001130 BufferingHandler.close(self)