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