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