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