blob: 1923d9347917120c4854926f7ac85df647c8fd31 [file] [log] [blame]
Vinay Sajipdb81c4c2010-02-25 23:13:06 +00001# Copyright 2001-2010 by Vinay Sajip. All Rights Reserved.
Guido van Rossum57102f82002-11-13 16:15:58 +00002#
3# Permission to use, copy, modify, and distribute this software and its
4# documentation for any purpose and without fee is hereby granted,
5# provided that the above copyright notice appear in all copies and that
6# both that copyright notice and this permission notice appear in
7# supporting documentation, and that the name of Vinay Sajip
8# not be used in advertising or publicity pertaining to distribution
9# of the software without specific, written prior permission.
10# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
11# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
12# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
13# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
14# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
15# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Guido van Rossum57102f82002-11-13 16:15:58 +000016
17"""
Vinay Sajip3f742842004-02-28 16:07:46 +000018Additional handlers for the logging package for Python. The core package is
19based on PEP 282 and comments thereto in comp.lang.python, and influenced by
20Apache's log4j system.
Guido van Rossum57102f82002-11-13 16:15:58 +000021
Vinay Sajipdb81c4c2010-02-25 23:13:06 +000022Copyright (C) 2001-2010 Vinay Sajip. All Rights Reserved.
Guido van Rossum57102f82002-11-13 16:15:58 +000023
Vinay Sajip6268cbc2009-01-21 00:19:28 +000024To use, simply 'import logging.handlers' and log away!
Guido van Rossum57102f82002-11-13 16:15:58 +000025"""
26
Benjamin Petersonad9d48d2008-04-02 21:49:44 +000027import logging, socket, os, pickle, struct, time, re
Benjamin Peterson9451a1c2010-03-13 22:30:34 +000028from stat import ST_DEV, ST_INO, ST_MTIME
Vinay Sajipe723e962011-04-15 22:27:17 +010029import queue
30import threading
Guido van Rossum57102f82002-11-13 16:15:58 +000031
Vinay Sajip4600f112005-03-13 09:56:36 +000032try:
33 import codecs
Vinay Sajip985ef872011-04-26 19:34:04 +010034except ImportError: #pragma: no cover
Vinay Sajip4600f112005-03-13 09:56:36 +000035 codecs = None
36
Guido van Rossum57102f82002-11-13 16:15:58 +000037#
38# Some constants...
39#
40
41DEFAULT_TCP_LOGGING_PORT = 9020
42DEFAULT_UDP_LOGGING_PORT = 9021
43DEFAULT_HTTP_LOGGING_PORT = 9022
44DEFAULT_SOAP_LOGGING_PORT = 9023
45SYSLOG_UDP_PORT = 514
Vinay Sajipcbabd7e2009-10-10 20:32:36 +000046SYSLOG_TCP_PORT = 514
Guido van Rossum57102f82002-11-13 16:15:58 +000047
Thomas Wouters477c8d52006-05-27 19:21:47 +000048_MIDNIGHT = 24 * 60 * 60 # number of seconds in a day
49
Vinay Sajip17c52d82004-07-03 11:48:34 +000050class BaseRotatingHandler(logging.FileHandler):
51 """
52 Base class for handlers that rotate log files at a certain point.
53 Not meant to be instantiated directly. Instead, use RotatingFileHandler
54 or TimedRotatingFileHandler.
55 """
Christian Heimese7a15bb2008-01-24 16:21:45 +000056 def __init__(self, filename, mode, encoding=None, delay=0):
Vinay Sajip17c52d82004-07-03 11:48:34 +000057 """
58 Use the specified filename for streamed logging
59 """
Vinay Sajip985ef872011-04-26 19:34:04 +010060 if codecs is None: #pragma: no cover
Vinay Sajip4600f112005-03-13 09:56:36 +000061 encoding = None
Christian Heimese7a15bb2008-01-24 16:21:45 +000062 logging.FileHandler.__init__(self, filename, mode, encoding, delay)
Vinay Sajip4600f112005-03-13 09:56:36 +000063 self.mode = mode
64 self.encoding = encoding
Guido van Rossum57102f82002-11-13 16:15:58 +000065
Vinay Sajip17c52d82004-07-03 11:48:34 +000066 def emit(self, record):
67 """
68 Emit a record.
69
70 Output the record to the file, catering for rollover as described
71 in doRollover().
72 """
Vinay Sajip3970c112004-07-08 10:24:04 +000073 try:
74 if self.shouldRollover(record):
75 self.doRollover()
76 logging.FileHandler.emit(self, record)
Vinay Sajip985ef872011-04-26 19:34:04 +010077 except (KeyboardInterrupt, SystemExit): #pragma: no cover
Vinay Sajip85c19092005-10-31 13:14:19 +000078 raise
Vinay Sajip3970c112004-07-08 10:24:04 +000079 except:
80 self.handleError(record)
Vinay Sajip17c52d82004-07-03 11:48:34 +000081
82class RotatingFileHandler(BaseRotatingHandler):
83 """
84 Handler for logging to a set of files, which switches from one file
85 to the next when the current file reaches a certain size.
86 """
Christian Heimese7a15bb2008-01-24 16:21:45 +000087 def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0):
Guido van Rossum57102f82002-11-13 16:15:58 +000088 """
89 Open the specified file and use it as the stream for logging.
90
91 By default, the file grows indefinitely. You can specify particular
92 values of maxBytes and backupCount to allow the file to rollover at
93 a predetermined size.
94
95 Rollover occurs whenever the current log file is nearly maxBytes in
96 length. If backupCount is >= 1, the system will successively create
97 new files with the same pathname as the base file, but with extensions
98 ".1", ".2" etc. appended to it. For example, with a backupCount of 5
99 and a base file name of "app.log", you would get "app.log",
100 "app.log.1", "app.log.2", ... through to "app.log.5". The file being
101 written to is always "app.log" - when it gets filled up, it is closed
102 and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc.
103 exist, then they are renamed to "app.log.2", "app.log.3" etc.
104 respectively.
105
106 If maxBytes is zero, rollover never occurs.
107 """
Vinay Sajip89994b22010-08-22 18:11:02 +0000108 # If rotation/rollover is wanted, it doesn't make sense to use another
109 # mode. If for example 'w' were specified, then if there were multiple
110 # runs of the calling application, the logs from previous runs would be
111 # lost if the 'w' is respected, because the log file would be truncated
112 # on each run.
Vinay Sajip17c52d82004-07-03 11:48:34 +0000113 if maxBytes > 0:
Vinay Sajip89994b22010-08-22 18:11:02 +0000114 mode = 'a'
Christian Heimese7a15bb2008-01-24 16:21:45 +0000115 BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
Guido van Rossum57102f82002-11-13 16:15:58 +0000116 self.maxBytes = maxBytes
117 self.backupCount = backupCount
Guido van Rossum57102f82002-11-13 16:15:58 +0000118
119 def doRollover(self):
120 """
121 Do a rollover, as described in __init__().
122 """
Vinay Sajip6268cbc2009-01-21 00:19:28 +0000123 if self.stream:
124 self.stream.close()
Vinay Sajip01241d62011-01-21 23:35:57 +0000125 self.stream = None
Guido van Rossum57102f82002-11-13 16:15:58 +0000126 if self.backupCount > 0:
127 for i in range(self.backupCount - 1, 0, -1):
128 sfn = "%s.%d" % (self.baseFilename, i)
129 dfn = "%s.%d" % (self.baseFilename, i + 1)
130 if os.path.exists(sfn):
Guido van Rossum57102f82002-11-13 16:15:58 +0000131 if os.path.exists(dfn):
132 os.remove(dfn)
133 os.rename(sfn, dfn)
134 dfn = self.baseFilename + ".1"
135 if os.path.exists(dfn):
136 os.remove(dfn)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000137 os.rename(self.baseFilename, dfn)
Thomas Woutersb2137042007-02-01 18:02:27 +0000138 self.mode = 'w'
139 self.stream = self._open()
Guido van Rossum57102f82002-11-13 16:15:58 +0000140
Vinay Sajip17c52d82004-07-03 11:48:34 +0000141 def shouldRollover(self, record):
Guido van Rossum57102f82002-11-13 16:15:58 +0000142 """
Vinay Sajip17c52d82004-07-03 11:48:34 +0000143 Determine if rollover should occur.
Guido van Rossum57102f82002-11-13 16:15:58 +0000144
Vinay Sajip17c52d82004-07-03 11:48:34 +0000145 Basically, see if the supplied record would cause the file to exceed
146 the size limit we have.
Guido van Rossum57102f82002-11-13 16:15:58 +0000147 """
Vinay Sajip6268cbc2009-01-21 00:19:28 +0000148 if self.stream is None: # delay was set...
149 self.stream = self._open()
Guido van Rossum57102f82002-11-13 16:15:58 +0000150 if self.maxBytes > 0: # are we rolling over?
151 msg = "%s\n" % self.format(record)
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000152 self.stream.seek(0, 2) #due to non-posix-compliant Windows feature
Guido van Rossum57102f82002-11-13 16:15:58 +0000153 if self.stream.tell() + len(msg) >= self.maxBytes:
Vinay Sajip17c52d82004-07-03 11:48:34 +0000154 return 1
155 return 0
Guido van Rossum57102f82002-11-13 16:15:58 +0000156
Vinay Sajip17c52d82004-07-03 11:48:34 +0000157class TimedRotatingFileHandler(BaseRotatingHandler):
158 """
159 Handler for logging to a file, rotating the log file at certain timed
160 intervals.
161
162 If backupCount is > 0, when rollover is done, no more than backupCount
163 files are kept - the oldest ones are deleted.
164 """
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000165 def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False):
Christian Heimese7a15bb2008-01-24 16:21:45 +0000166 BaseRotatingHandler.__init__(self, filename, 'a', encoding, delay)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000167 self.when = when.upper()
Vinay Sajip17c52d82004-07-03 11:48:34 +0000168 self.backupCount = backupCount
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000169 self.utc = utc
Vinay Sajip17c52d82004-07-03 11:48:34 +0000170 # Calculate the real rollover interval, which is just the number of
171 # seconds between rollovers. Also set the filename suffix used when
172 # a rollover occurs. Current 'when' events supported:
173 # S - Seconds
174 # M - Minutes
175 # H - Hours
176 # D - Days
177 # midnight - roll over at midnight
178 # W{0-6} - roll over on a certain day; 0 - Monday
179 #
180 # Case of the 'when' specifier is not important; lower or upper case
181 # will work.
Vinay Sajip17c52d82004-07-03 11:48:34 +0000182 if self.when == 'S':
183 self.interval = 1 # one second
184 self.suffix = "%Y-%m-%d_%H-%M-%S"
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000185 self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$"
Vinay Sajip17c52d82004-07-03 11:48:34 +0000186 elif self.when == 'M':
187 self.interval = 60 # one minute
188 self.suffix = "%Y-%m-%d_%H-%M"
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000189 self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}$"
Vinay Sajip17c52d82004-07-03 11:48:34 +0000190 elif self.when == 'H':
191 self.interval = 60 * 60 # one hour
192 self.suffix = "%Y-%m-%d_%H"
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000193 self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}$"
Vinay Sajip17c52d82004-07-03 11:48:34 +0000194 elif self.when == 'D' or self.when == 'MIDNIGHT':
195 self.interval = 60 * 60 * 24 # one day
196 self.suffix = "%Y-%m-%d"
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000197 self.extMatch = r"^\d{4}-\d{2}-\d{2}$"
Vinay Sajip17c52d82004-07-03 11:48:34 +0000198 elif self.when.startswith('W'):
199 self.interval = 60 * 60 * 24 * 7 # one week
200 if len(self.when) != 2:
201 raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when)
202 if self.when[1] < '0' or self.when[1] > '6':
203 raise ValueError("Invalid day specified for weekly rollover: %s" % self.when)
204 self.dayOfWeek = int(self.when[1])
205 self.suffix = "%Y-%m-%d"
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000206 self.extMatch = r"^\d{4}-\d{2}-\d{2}$"
Vinay Sajip17c52d82004-07-03 11:48:34 +0000207 else:
208 raise ValueError("Invalid rollover interval specified: %s" % self.when)
209
Antoine Pitroufd036452008-08-19 17:56:33 +0000210 self.extMatch = re.compile(self.extMatch, re.ASCII)
Vinay Sajipe7d40662004-10-03 19:12:07 +0000211 self.interval = self.interval * interval # multiply by units requested
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000212 if os.path.exists(filename):
213 t = os.stat(filename)[ST_MTIME]
214 else:
215 t = int(time.time())
216 self.rolloverAt = self.computeRollover(t)
Vinay Sajip17c52d82004-07-03 11:48:34 +0000217
Vinay Sajipaffbd872009-06-11 10:11:47 +0000218 def computeRollover(self, currentTime):
219 """
220 Work out the rollover time based on the specified time.
221 """
222 result = currentTime + self.interval
Vinay Sajip17c52d82004-07-03 11:48:34 +0000223 # If we are rolling over at midnight or weekly, then the interval is already known.
224 # What we need to figure out is WHEN the next interval is. In other words,
225 # if you are rolling over at midnight, then your base interval is 1 day,
226 # but you want to start that one day clock at midnight, not now. So, we
227 # have to fudge the rolloverAt value in order to trigger the first rollover
228 # at the right time. After that, the regular interval will take care of
229 # the rest. Note that this code doesn't care about leap seconds. :)
230 if self.when == 'MIDNIGHT' or self.when.startswith('W'):
231 # This could be done with less code, but I wanted it to be clear
Vinay Sajipaffbd872009-06-11 10:11:47 +0000232 if self.utc:
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000233 t = time.gmtime(currentTime)
234 else:
235 t = time.localtime(currentTime)
Vinay Sajip17c52d82004-07-03 11:48:34 +0000236 currentHour = t[3]
237 currentMinute = t[4]
238 currentSecond = t[5]
239 # r is the number of seconds left between now and midnight
Thomas Wouters477c8d52006-05-27 19:21:47 +0000240 r = _MIDNIGHT - ((currentHour * 60 + currentMinute) * 60 +
241 currentSecond)
Vinay Sajipaffbd872009-06-11 10:11:47 +0000242 result = currentTime + r
Vinay Sajip17c52d82004-07-03 11:48:34 +0000243 # If we are rolling over on a certain day, add in the number of days until
244 # the next rollover, but offset by 1 since we just calculated the time
245 # until the next day starts. There are three cases:
246 # Case 1) The day to rollover is today; in this case, do nothing
247 # Case 2) The day to rollover is further in the interval (i.e., today is
248 # day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to
249 # next rollover is simply 6 - 2 - 1, or 3.
250 # Case 3) The day to rollover is behind us in the interval (i.e., today
251 # is day 5 (Saturday) and rollover is on day 3 (Thursday).
252 # Days to rollover is 6 - 5 + 3, or 4. In this case, it's the
253 # number of days left in the current week (1) plus the number
254 # of days in the next week until the rollover day (3).
Georg Brandl86def6c2008-01-21 20:36:10 +0000255 # The calculations described in 2) and 3) above need to have a day added.
256 # This is because the above time calculation takes us to midnight on this
257 # day, i.e. the start of the next day.
Vinay Sajipaffbd872009-06-11 10:11:47 +0000258 if self.when.startswith('W'):
Vinay Sajip17c52d82004-07-03 11:48:34 +0000259 day = t[6] # 0 is Monday
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000260 if day != self.dayOfWeek:
261 if day < self.dayOfWeek:
Georg Brandl86def6c2008-01-21 20:36:10 +0000262 daysToWait = self.dayOfWeek - day
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000263 else:
Georg Brandl86def6c2008-01-21 20:36:10 +0000264 daysToWait = 6 - day + self.dayOfWeek + 1
Vinay Sajipaffbd872009-06-11 10:11:47 +0000265 newRolloverAt = result + (daysToWait * (60 * 60 * 24))
266 if not self.utc:
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000267 dstNow = t[-1]
268 dstAtRollover = time.localtime(newRolloverAt)[-1]
269 if dstNow != dstAtRollover:
270 if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
271 newRolloverAt = newRolloverAt - 3600
272 else: # DST bows out before next rollover, so we need to add an hour
273 newRolloverAt = newRolloverAt + 3600
Vinay Sajipaffbd872009-06-11 10:11:47 +0000274 result = newRolloverAt
275 return result
Vinay Sajip17c52d82004-07-03 11:48:34 +0000276
277 def shouldRollover(self, record):
278 """
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000279 Determine if rollover should occur.
Vinay Sajip17c52d82004-07-03 11:48:34 +0000280
281 record is not used, as we are just comparing times, but it is needed so
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000282 the method signatures are the same
Vinay Sajip17c52d82004-07-03 11:48:34 +0000283 """
284 t = int(time.time())
285 if t >= self.rolloverAt:
286 return 1
Vinay Sajip17c52d82004-07-03 11:48:34 +0000287 return 0
288
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000289 def getFilesToDelete(self):
290 """
291 Determine the files to delete when rolling over.
292
293 More specific than the earlier method, which just used glob.glob().
294 """
295 dirName, baseName = os.path.split(self.baseFilename)
296 fileNames = os.listdir(dirName)
297 result = []
298 prefix = baseName + "."
299 plen = len(prefix)
300 for fileName in fileNames:
301 if fileName[:plen] == prefix:
302 suffix = fileName[plen:]
303 if self.extMatch.match(suffix):
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000304 result.append(os.path.join(dirName, fileName))
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000305 result.sort()
306 if len(result) < self.backupCount:
307 result = []
308 else:
309 result = result[:len(result) - self.backupCount]
310 return result
311
Vinay Sajip17c52d82004-07-03 11:48:34 +0000312 def doRollover(self):
313 """
314 do a rollover; in this case, a date/time stamp is appended to the filename
315 when the rollover happens. However, you want the file to be named for the
316 start of the interval, not the current time. If there is a backup count,
317 then we have to get a list of matching filenames, sort them and remove
318 the one with the oldest suffix.
319 """
Vinay Sajip6268cbc2009-01-21 00:19:28 +0000320 if self.stream:
321 self.stream.close()
Vinay Sajip01241d62011-01-21 23:35:57 +0000322 self.stream = None
Vinay Sajip17c52d82004-07-03 11:48:34 +0000323 # get the time that this sequence started at and make it a TimeTuple
324 t = self.rolloverAt - self.interval
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000325 if self.utc:
326 timeTuple = time.gmtime(t)
327 else:
328 timeTuple = time.localtime(t)
Vinay Sajip17c52d82004-07-03 11:48:34 +0000329 dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple)
330 if os.path.exists(dfn):
331 os.remove(dfn)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000332 os.rename(self.baseFilename, dfn)
Vinay Sajip17c52d82004-07-03 11:48:34 +0000333 if self.backupCount > 0:
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000334 for s in self.getFilesToDelete():
335 os.remove(s)
Thomas Woutersb2137042007-02-01 18:02:27 +0000336 self.mode = 'w'
337 self.stream = self._open()
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000338 currentTime = int(time.time())
Vinay Sajipaffbd872009-06-11 10:11:47 +0000339 newRolloverAt = self.computeRollover(currentTime)
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000340 while newRolloverAt <= currentTime:
341 newRolloverAt = newRolloverAt + self.interval
342 #If DST changes and midnight or weekly rollover, adjust for this.
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000343 if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc:
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000344 dstNow = time.localtime(currentTime)[-1]
345 dstAtRollover = time.localtime(newRolloverAt)[-1]
346 if dstNow != dstAtRollover:
347 if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
348 newRolloverAt = newRolloverAt - 3600
349 else: # DST bows out before next rollover, so we need to add an hour
350 newRolloverAt = newRolloverAt + 3600
351 self.rolloverAt = newRolloverAt
Guido van Rossum57102f82002-11-13 16:15:58 +0000352
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000353class WatchedFileHandler(logging.FileHandler):
354 """
355 A handler for logging to a file, which watches the file
356 to see if it has changed while in use. This can happen because of
357 usage of programs such as newsyslog and logrotate which perform
358 log file rotation. This handler, intended for use under Unix,
359 watches the file to see if it has changed since the last emit.
360 (A file has changed if its device or inode have changed.)
361 If it has changed, the old file stream is closed, and the file
362 opened to get a new stream.
363
364 This handler is not appropriate for use under Windows, because
365 under Windows open files cannot be moved or renamed - logging
366 opens the files with exclusive locks - and so there is no need
367 for such a handler. Furthermore, ST_INO is not supported under
368 Windows; stat always returns zero for this value.
369
370 This handler is based on a suggestion and patch by Chad J.
371 Schroeder.
372 """
Christian Heimese7a15bb2008-01-24 16:21:45 +0000373 def __init__(self, filename, mode='a', encoding=None, delay=0):
374 logging.FileHandler.__init__(self, filename, mode, encoding, delay)
375 if not os.path.exists(self.baseFilename):
376 self.dev, self.ino = -1, -1
377 else:
378 stat = os.stat(self.baseFilename)
379 self.dev, self.ino = stat[ST_DEV], stat[ST_INO]
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000380
381 def emit(self, record):
382 """
383 Emit a record.
384
385 First check if the underlying file has changed, and if it
386 has, close the old stream and reopen the file to get the
387 current stream.
388 """
389 if not os.path.exists(self.baseFilename):
390 stat = None
391 changed = 1
392 else:
393 stat = os.stat(self.baseFilename)
394 changed = (stat[ST_DEV] != self.dev) or (stat[ST_INO] != self.ino)
Christian Heimese7a15bb2008-01-24 16:21:45 +0000395 if changed and self.stream is not None:
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000396 self.stream.flush()
397 self.stream.close()
398 self.stream = self._open()
399 if stat is None:
400 stat = os.stat(self.baseFilename)
401 self.dev, self.ino = stat[ST_DEV], stat[ST_INO]
402 logging.FileHandler.emit(self, record)
403
Guido van Rossum57102f82002-11-13 16:15:58 +0000404class SocketHandler(logging.Handler):
405 """
406 A handler class which writes logging records, in pickle format, to
407 a streaming socket. The socket is kept open across logging calls.
408 If the peer resets it, an attempt is made to reconnect on the next call.
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000409 The pickle which is sent is that of the LogRecord's attribute dictionary
410 (__dict__), so that the receiver does not need to have the logging module
411 installed in order to process the logging event.
412
413 To unpickle the record at the receiving end into a LogRecord, use the
414 makeLogRecord function.
Guido van Rossum57102f82002-11-13 16:15:58 +0000415 """
416
417 def __init__(self, host, port):
418 """
419 Initializes the handler with a specific host address and port.
420
421 The attribute 'closeOnError' is set to 1 - which means that if
422 a socket error occurs, the socket is silently closed and then
423 reopened on the next logging call.
424 """
425 logging.Handler.__init__(self)
426 self.host = host
427 self.port = port
428 self.sock = None
429 self.closeOnError = 0
Vinay Sajip48cfe382004-02-20 13:17:27 +0000430 self.retryTime = None
431 #
432 # Exponential backoff parameters.
433 #
434 self.retryStart = 1.0
435 self.retryMax = 30.0
436 self.retryFactor = 2.0
Guido van Rossum57102f82002-11-13 16:15:58 +0000437
Guido van Rossumd8faa362007-04-27 19:54:29 +0000438 def makeSocket(self, timeout=1):
Guido van Rossum57102f82002-11-13 16:15:58 +0000439 """
440 A factory method which allows subclasses to define the precise
441 type of socket they want.
442 """
443 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000444 if hasattr(s, 'settimeout'):
445 s.settimeout(timeout)
Guido van Rossum57102f82002-11-13 16:15:58 +0000446 s.connect((self.host, self.port))
447 return s
448
Vinay Sajip48cfe382004-02-20 13:17:27 +0000449 def createSocket(self):
450 """
451 Try to create a socket, using an exponential backoff with
452 a max retry time. Thanks to Robert Olson for the original patch
453 (SF #815911) which has been slightly refactored.
454 """
455 now = time.time()
456 # Either retryTime is None, in which case this
457 # is the first time back after a disconnect, or
458 # we've waited long enough.
459 if self.retryTime is None:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000460 attempt = 1
Vinay Sajip48cfe382004-02-20 13:17:27 +0000461 else:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000462 attempt = (now >= self.retryTime)
Vinay Sajip48cfe382004-02-20 13:17:27 +0000463 if attempt:
464 try:
465 self.sock = self.makeSocket()
466 self.retryTime = None # next time, no delay before trying
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000467 except socket.error:
Vinay Sajip48cfe382004-02-20 13:17:27 +0000468 #Creation failed, so set the retry time and return.
469 if self.retryTime is None:
470 self.retryPeriod = self.retryStart
471 else:
472 self.retryPeriod = self.retryPeriod * self.retryFactor
473 if self.retryPeriod > self.retryMax:
474 self.retryPeriod = self.retryMax
475 self.retryTime = now + self.retryPeriod
476
Guido van Rossum57102f82002-11-13 16:15:58 +0000477 def send(self, s):
478 """
479 Send a pickled string to the socket.
480
481 This function allows for partial sends which can happen when the
482 network is busy.
483 """
Vinay Sajip48cfe382004-02-20 13:17:27 +0000484 if self.sock is None:
485 self.createSocket()
486 #self.sock can be None either because we haven't reached the retry
487 #time yet, or because we have reached the retry time and retried,
488 #but are still unable to connect.
489 if self.sock:
490 try:
491 if hasattr(self.sock, "sendall"):
492 self.sock.sendall(s)
Vinay Sajip7fe1d512011-04-28 12:04:58 +0100493 else: #pragma: no cover
Vinay Sajip48cfe382004-02-20 13:17:27 +0000494 sentsofar = 0
495 left = len(s)
496 while left > 0:
497 sent = self.sock.send(s[sentsofar:])
498 sentsofar = sentsofar + sent
499 left = left - sent
Vinay Sajip7fe1d512011-04-28 12:04:58 +0100500 except socket.error: #pragma: no cover
Vinay Sajip48cfe382004-02-20 13:17:27 +0000501 self.sock.close()
502 self.sock = None # so we can call createSocket next time
Guido van Rossum57102f82002-11-13 16:15:58 +0000503
504 def makePickle(self, record):
505 """
506 Pickles the record in binary format with a length prefix, and
507 returns it ready for transmission across the socket.
508 """
Vinay Sajip48cfe382004-02-20 13:17:27 +0000509 ei = record.exc_info
510 if ei:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000511 dummy = self.format(record) # just to get traceback text into record.exc_text
512 record.exc_info = None # to avoid Unpickleable error
Guido van Rossumba205d62006-08-17 08:57:26 +0000513 s = pickle.dumps(record.__dict__, 1)
Vinay Sajip48cfe382004-02-20 13:17:27 +0000514 if ei:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000515 record.exc_info = ei # for next handler
Guido van Rossum57102f82002-11-13 16:15:58 +0000516 slen = struct.pack(">L", len(s))
517 return slen + s
518
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000519 def handleError(self, record):
Guido van Rossum57102f82002-11-13 16:15:58 +0000520 """
521 Handle an error during logging.
522
523 An error has occurred during logging. Most likely cause -
524 connection lost. Close the socket so that we can retry on the
525 next event.
526 """
527 if self.closeOnError and self.sock:
528 self.sock.close()
529 self.sock = None #try to reconnect next time
530 else:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000531 logging.Handler.handleError(self, record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000532
533 def emit(self, record):
534 """
535 Emit a record.
536
537 Pickles the record and writes it to the socket in binary format.
538 If there is an error with the socket, silently drop the packet.
539 If there was a problem with the socket, re-establishes the
540 socket.
541 """
542 try:
543 s = self.makePickle(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000544 self.send(s)
Vinay Sajip985ef872011-04-26 19:34:04 +0100545 except (KeyboardInterrupt, SystemExit): #pragma: no cover
Vinay Sajip85c19092005-10-31 13:14:19 +0000546 raise
Guido van Rossum57102f82002-11-13 16:15:58 +0000547 except:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000548 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000549
550 def close(self):
551 """
552 Closes the socket.
553 """
554 if self.sock:
555 self.sock.close()
556 self.sock = None
Vinay Sajip48cfe382004-02-20 13:17:27 +0000557 logging.Handler.close(self)
Guido van Rossum57102f82002-11-13 16:15:58 +0000558
559class DatagramHandler(SocketHandler):
560 """
561 A handler class which writes logging records, in pickle format, to
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000562 a datagram socket. The pickle which is sent is that of the LogRecord's
563 attribute dictionary (__dict__), so that the receiver does not need to
564 have the logging module installed in order to process the logging event.
565
566 To unpickle the record at the receiving end into a LogRecord, use the
567 makeLogRecord function.
Guido van Rossum57102f82002-11-13 16:15:58 +0000568
569 """
570 def __init__(self, host, port):
571 """
572 Initializes the handler with a specific host address and port.
573 """
574 SocketHandler.__init__(self, host, port)
575 self.closeOnError = 0
576
577 def makeSocket(self):
578 """
579 The factory method of SocketHandler is here overridden to create
580 a UDP socket (SOCK_DGRAM).
581 """
582 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
583 return s
584
585 def send(self, s):
586 """
587 Send a pickled string to a socket.
588
589 This function no longer allows for partial sends which can happen
590 when the network is busy - UDP does not guarantee delivery and
591 can deliver packets out of sequence.
592 """
Vinay Sajipfb154172004-08-24 09:36:23 +0000593 if self.sock is None:
594 self.createSocket()
Guido van Rossum57102f82002-11-13 16:15:58 +0000595 self.sock.sendto(s, (self.host, self.port))
596
597class SysLogHandler(logging.Handler):
598 """
599 A handler class which sends formatted logging records to a syslog
600 server. Based on Sam Rushing's syslog module:
601 http://www.nightmare.com/squirl/python-ext/misc/syslog.py
602 Contributed by Nicolas Untz (after which minor refactoring changes
603 have been made).
604 """
605
606 # from <linux/sys/syslog.h>:
607 # ======================================================================
608 # priorities/facilities are encoded into a single 32-bit quantity, where
609 # the bottom 3 bits are the priority (0-7) and the top 28 bits are the
610 # facility (0-big number). Both the priorities and the facilities map
611 # roughly one-to-one to strings in the syslogd(8) source code. This
612 # mapping is included in this file.
613 #
614 # priorities (these are ordered)
615
616 LOG_EMERG = 0 # system is unusable
617 LOG_ALERT = 1 # action must be taken immediately
618 LOG_CRIT = 2 # critical conditions
619 LOG_ERR = 3 # error conditions
620 LOG_WARNING = 4 # warning conditions
621 LOG_NOTICE = 5 # normal but significant condition
622 LOG_INFO = 6 # informational
623 LOG_DEBUG = 7 # debug-level messages
624
625 # facility codes
626 LOG_KERN = 0 # kernel messages
627 LOG_USER = 1 # random user-level messages
628 LOG_MAIL = 2 # mail system
629 LOG_DAEMON = 3 # system daemons
630 LOG_AUTH = 4 # security/authorization messages
631 LOG_SYSLOG = 5 # messages generated internally by syslogd
632 LOG_LPR = 6 # line printer subsystem
633 LOG_NEWS = 7 # network news subsystem
634 LOG_UUCP = 8 # UUCP subsystem
635 LOG_CRON = 9 # clock daemon
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000636 LOG_AUTHPRIV = 10 # security/authorization messages (private)
637 LOG_FTP = 11 # FTP daemon
Guido van Rossum57102f82002-11-13 16:15:58 +0000638
639 # other codes through 15 reserved for system use
640 LOG_LOCAL0 = 16 # reserved for local use
641 LOG_LOCAL1 = 17 # reserved for local use
642 LOG_LOCAL2 = 18 # reserved for local use
643 LOG_LOCAL3 = 19 # reserved for local use
644 LOG_LOCAL4 = 20 # reserved for local use
645 LOG_LOCAL5 = 21 # reserved for local use
646 LOG_LOCAL6 = 22 # reserved for local use
647 LOG_LOCAL7 = 23 # reserved for local use
648
649 priority_names = {
650 "alert": LOG_ALERT,
651 "crit": LOG_CRIT,
652 "critical": LOG_CRIT,
653 "debug": LOG_DEBUG,
654 "emerg": LOG_EMERG,
655 "err": LOG_ERR,
656 "error": LOG_ERR, # DEPRECATED
657 "info": LOG_INFO,
658 "notice": LOG_NOTICE,
659 "panic": LOG_EMERG, # DEPRECATED
660 "warn": LOG_WARNING, # DEPRECATED
661 "warning": LOG_WARNING,
662 }
663
664 facility_names = {
665 "auth": LOG_AUTH,
666 "authpriv": LOG_AUTHPRIV,
667 "cron": LOG_CRON,
668 "daemon": LOG_DAEMON,
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000669 "ftp": LOG_FTP,
Guido van Rossum57102f82002-11-13 16:15:58 +0000670 "kern": LOG_KERN,
671 "lpr": LOG_LPR,
672 "mail": LOG_MAIL,
673 "news": LOG_NEWS,
674 "security": LOG_AUTH, # DEPRECATED
675 "syslog": LOG_SYSLOG,
676 "user": LOG_USER,
677 "uucp": LOG_UUCP,
678 "local0": LOG_LOCAL0,
679 "local1": LOG_LOCAL1,
680 "local2": LOG_LOCAL2,
681 "local3": LOG_LOCAL3,
682 "local4": LOG_LOCAL4,
683 "local5": LOG_LOCAL5,
684 "local6": LOG_LOCAL6,
685 "local7": LOG_LOCAL7,
686 }
687
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000688 #The map below appears to be trivially lowercasing the key. However,
689 #there's more to it than meets the eye - in some locales, lowercasing
690 #gives unexpected results. See SF #1524081: in the Turkish locale,
691 #"INFO".lower() != "info"
692 priority_map = {
693 "DEBUG" : "debug",
694 "INFO" : "info",
695 "WARNING" : "warning",
696 "ERROR" : "error",
697 "CRITICAL" : "critical"
698 }
699
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000700 def __init__(self, address=('localhost', SYSLOG_UDP_PORT),
701 facility=LOG_USER, socktype=socket.SOCK_DGRAM):
Guido van Rossum57102f82002-11-13 16:15:58 +0000702 """
703 Initialize a handler.
704
Guido van Rossume7ba4952007-06-06 23:52:48 +0000705 If address is specified as a string, a UNIX socket is used. To log to a
706 local syslogd, "SysLogHandler(address="/dev/log")" can be used.
Guido van Rossum57102f82002-11-13 16:15:58 +0000707 If facility is not specified, LOG_USER is used.
708 """
709 logging.Handler.__init__(self)
710
711 self.address = address
712 self.facility = facility
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000713 self.socktype = socktype
714
Guido van Rossum13257902007-06-07 23:15:56 +0000715 if isinstance(address, str):
Vinay Sajip5a35b062011-04-27 11:31:14 +0100716 self.unixsocket = True
Thomas Wouters89f507f2006-12-13 04:49:30 +0000717 self._connect_unixsocket(address)
Guido van Rossum57102f82002-11-13 16:15:58 +0000718 else:
Vinay Sajip5a35b062011-04-27 11:31:14 +0100719 self.unixsocket = False
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000720 self.socket = socket.socket(socket.AF_INET, socktype)
721 if socktype == socket.SOCK_STREAM:
722 self.socket.connect(address)
Guido van Rossum57102f82002-11-13 16:15:58 +0000723 self.formatter = None
724
Vinay Sajipa1974c12005-01-13 08:23:56 +0000725 def _connect_unixsocket(self, address):
726 self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
727 # syslog may require either DGRAM or STREAM sockets
728 try:
729 self.socket.connect(address)
730 except socket.error:
731 self.socket.close()
732 self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
Vinay Sajip8b6b53f2005-11-09 13:55:13 +0000733 self.socket.connect(address)
Vinay Sajipa1974c12005-01-13 08:23:56 +0000734
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000735 def encodePriority(self, facility, priority):
Guido van Rossum57102f82002-11-13 16:15:58 +0000736 """
737 Encode the facility and priority. You can pass in strings or
738 integers - if strings are passed, the facility_names and
739 priority_names mapping dictionaries are used to convert them to
740 integers.
741 """
Guido van Rossum13257902007-06-07 23:15:56 +0000742 if isinstance(facility, str):
Guido van Rossum57102f82002-11-13 16:15:58 +0000743 facility = self.facility_names[facility]
Guido van Rossum13257902007-06-07 23:15:56 +0000744 if isinstance(priority, str):
Guido van Rossum57102f82002-11-13 16:15:58 +0000745 priority = self.priority_names[priority]
746 return (facility << 3) | priority
747
748 def close (self):
749 """
750 Closes the socket.
751 """
752 if self.unixsocket:
753 self.socket.close()
Vinay Sajip48cfe382004-02-20 13:17:27 +0000754 logging.Handler.close(self)
Guido van Rossum57102f82002-11-13 16:15:58 +0000755
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000756 def mapPriority(self, levelName):
757 """
758 Map a logging level name to a key in the priority_names map.
759 This is useful in two scenarios: when custom levels are being
760 used, and in the case where you can't do a straightforward
761 mapping by lowercasing the logging level name because of locale-
762 specific issues (see SF #1524081).
763 """
764 return self.priority_map.get(levelName, "warning")
765
Guido van Rossum57102f82002-11-13 16:15:58 +0000766 def emit(self, record):
767 """
768 Emit a record.
769
770 The record is formatted, and then sent to the syslog server. If
771 exception information is present, it is NOT sent to the server.
772 """
Vinay Sajip89d8f822010-08-20 08:43:22 +0000773 msg = self.format(record) + '\000'
Guido van Rossum57102f82002-11-13 16:15:58 +0000774 """
775 We need to convert record level to lowercase, maybe this will
776 change in the future.
777 """
Vinay Sajip467d12f2010-08-19 22:20:22 +0000778 prio = '<%d>' % self.encodePriority(self.facility,
779 self.mapPriority(record.levelname))
780 prio = prio.encode('utf-8')
Vinay Sajip609364a2010-08-30 18:31:13 +0000781 # Message is a string. Convert to bytes as required by RFC 5424
Vinay Sajip42ead482009-10-21 20:22:14 +0000782 msg = msg.encode('utf-8')
783 if codecs:
784 msg = codecs.BOM_UTF8 + msg
Vinay Sajip467d12f2010-08-19 22:20:22 +0000785 msg = prio + msg
Guido van Rossum57102f82002-11-13 16:15:58 +0000786 try:
787 if self.unixsocket:
Vinay Sajipa1974c12005-01-13 08:23:56 +0000788 try:
789 self.socket.send(msg)
790 except socket.error:
791 self._connect_unixsocket(self.address)
792 self.socket.send(msg)
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000793 elif self.socktype == socket.SOCK_DGRAM:
Guido van Rossum57102f82002-11-13 16:15:58 +0000794 self.socket.sendto(msg, self.address)
Vinay Sajipcbabd7e2009-10-10 20:32:36 +0000795 else:
796 self.socket.sendall(msg)
Vinay Sajip985ef872011-04-26 19:34:04 +0100797 except (KeyboardInterrupt, SystemExit): #pragma: no cover
Vinay Sajip85c19092005-10-31 13:14:19 +0000798 raise
Guido van Rossum57102f82002-11-13 16:15:58 +0000799 except:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000800 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000801
802class SMTPHandler(logging.Handler):
803 """
804 A handler class which sends an SMTP email for each logging event.
805 """
Vinay Sajip540f2152009-12-06 17:57:11 +0000806 def __init__(self, mailhost, fromaddr, toaddrs, subject,
Vinay Sajip25fcd222009-12-06 18:05:04 +0000807 credentials=None, secure=None):
Guido van Rossum57102f82002-11-13 16:15:58 +0000808 """
809 Initialize the handler.
810
811 Initialize the instance with the from and to addresses and subject
812 line of the email. To specify a non-standard SMTP port, use the
Guido van Rossum360e4b82007-05-14 22:51:27 +0000813 (host, port) tuple format for the mailhost argument. To specify
814 authentication credentials, supply a (username, password) tuple
Vinay Sajip25fcd222009-12-06 18:05:04 +0000815 for the credentials argument. To specify the use of a secure
816 protocol (TLS), pass in a tuple for the secure argument. This will
817 only be used when authentication credentials are supplied. The tuple
818 will be either an empty tuple, or a single-value tuple with the name
819 of a keyfile, or a 2-value tuple with the names of the keyfile and
820 certificate file. (This tuple is passed to the `starttls` method).
Guido van Rossum57102f82002-11-13 16:15:58 +0000821 """
822 logging.Handler.__init__(self)
Guido van Rossum13257902007-06-07 23:15:56 +0000823 if isinstance(mailhost, tuple):
Guido van Rossum360e4b82007-05-14 22:51:27 +0000824 self.mailhost, self.mailport = mailhost
Guido van Rossum57102f82002-11-13 16:15:58 +0000825 else:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000826 self.mailhost, self.mailport = mailhost, None
Guido van Rossum13257902007-06-07 23:15:56 +0000827 if isinstance(credentials, tuple):
Guido van Rossum360e4b82007-05-14 22:51:27 +0000828 self.username, self.password = credentials
829 else:
830 self.username = None
Guido van Rossum57102f82002-11-13 16:15:58 +0000831 self.fromaddr = fromaddr
Guido van Rossum13257902007-06-07 23:15:56 +0000832 if isinstance(toaddrs, str):
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000833 toaddrs = [toaddrs]
Guido van Rossum57102f82002-11-13 16:15:58 +0000834 self.toaddrs = toaddrs
835 self.subject = subject
Vinay Sajip540f2152009-12-06 17:57:11 +0000836 self.secure = secure
Guido van Rossum57102f82002-11-13 16:15:58 +0000837
838 def getSubject(self, record):
839 """
840 Determine the subject for the email.
841
842 If you want to specify a subject line which is record-dependent,
843 override this method.
844 """
845 return self.subject
846
847 def emit(self, record):
848 """
849 Emit a record.
850
851 Format the record and send it to the specified addressees.
852 """
853 try:
854 import smtplib
Vinay Sajipdb81c4c2010-02-25 23:13:06 +0000855 from email.utils import formatdate
Guido van Rossum57102f82002-11-13 16:15:58 +0000856 port = self.mailport
857 if not port:
858 port = smtplib.SMTP_PORT
859 smtp = smtplib.SMTP(self.mailhost, port)
860 msg = self.format(record)
Neal Norwitzf297bd12003-04-23 03:49:43 +0000861 msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
Guido van Rossum57102f82002-11-13 16:15:58 +0000862 self.fromaddr,
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000863 ",".join(self.toaddrs),
Neal Norwitzf297bd12003-04-23 03:49:43 +0000864 self.getSubject(record),
Martin v. Löwis318a12e2004-08-18 12:27:40 +0000865 formatdate(), msg)
Guido van Rossum360e4b82007-05-14 22:51:27 +0000866 if self.username:
Vinay Sajip25fcd222009-12-06 18:05:04 +0000867 if self.secure is not None:
Vinay Sajip540f2152009-12-06 17:57:11 +0000868 smtp.ehlo()
Vinay Sajip25fcd222009-12-06 18:05:04 +0000869 smtp.starttls(*self.secure)
Vinay Sajip540f2152009-12-06 17:57:11 +0000870 smtp.ehlo()
Guido van Rossum360e4b82007-05-14 22:51:27 +0000871 smtp.login(self.username, self.password)
Guido van Rossum57102f82002-11-13 16:15:58 +0000872 smtp.sendmail(self.fromaddr, self.toaddrs, msg)
873 smtp.quit()
Vinay Sajip985ef872011-04-26 19:34:04 +0100874 except (KeyboardInterrupt, SystemExit): #pragma: no cover
Vinay Sajip245a5ab2005-10-31 14:27:01 +0000875 raise
Guido van Rossum57102f82002-11-13 16:15:58 +0000876 except:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000877 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000878
879class NTEventLogHandler(logging.Handler):
880 """
881 A handler class which sends events to the NT Event Log. Adds a
882 registry entry for the specified application name. If no dllname is
883 provided, win32service.pyd (which contains some basic message
884 placeholders) is used. Note that use of these placeholders will make
885 your event logs big, as the entire message source is held in the log.
886 If you want slimmer logs, you have to pass in the name of your own DLL
887 which contains the message definitions you want to use in the event log.
888 """
889 def __init__(self, appname, dllname=None, logtype="Application"):
890 logging.Handler.__init__(self)
891 try:
892 import win32evtlogutil, win32evtlog
893 self.appname = appname
894 self._welu = win32evtlogutil
895 if not dllname:
896 dllname = os.path.split(self._welu.__file__)
897 dllname = os.path.split(dllname[0])
898 dllname = os.path.join(dllname[0], r'win32service.pyd')
899 self.dllname = dllname
900 self.logtype = logtype
901 self._welu.AddSourceToRegistry(appname, dllname, logtype)
902 self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE
903 self.typemap = {
904 logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE,
905 logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE,
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000906 logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE,
Guido van Rossum57102f82002-11-13 16:15:58 +0000907 logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE,
908 logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE,
909 }
910 except ImportError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000911 print("The Python Win32 extensions for NT (service, event "\
912 "logging) appear not to be available.")
Guido van Rossum57102f82002-11-13 16:15:58 +0000913 self._welu = None
914
915 def getMessageID(self, record):
916 """
917 Return the message ID for the event record. If you are using your
918 own messages, you could do this by having the msg passed to the
919 logger being an ID rather than a formatting string. Then, in here,
920 you could use a dictionary lookup to get the message ID. This
921 version returns 1, which is the base message ID in win32service.pyd.
922 """
923 return 1
924
925 def getEventCategory(self, record):
926 """
927 Return the event category for the record.
928
929 Override this if you want to specify your own categories. This version
930 returns 0.
931 """
932 return 0
933
934 def getEventType(self, record):
935 """
936 Return the event type for the record.
937
938 Override this if you want to specify your own types. This version does
939 a mapping using the handler's typemap attribute, which is set up in
940 __init__() to a dictionary which contains mappings for DEBUG, INFO,
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000941 WARNING, ERROR and CRITICAL. If you are using your own levels you will
Guido van Rossum57102f82002-11-13 16:15:58 +0000942 either need to override this method or place a suitable dictionary in
943 the handler's typemap attribute.
944 """
945 return self.typemap.get(record.levelno, self.deftype)
946
947 def emit(self, record):
948 """
949 Emit a record.
950
951 Determine the message ID, event category and event type. Then
952 log the message in the NT event log.
953 """
954 if self._welu:
955 try:
956 id = self.getMessageID(record)
957 cat = self.getEventCategory(record)
958 type = self.getEventType(record)
959 msg = self.format(record)
960 self._welu.ReportEvent(self.appname, id, cat, type, [msg])
Vinay Sajip985ef872011-04-26 19:34:04 +0100961 except (KeyboardInterrupt, SystemExit): #pragma: no cover
Vinay Sajip245a5ab2005-10-31 14:27:01 +0000962 raise
Guido van Rossum57102f82002-11-13 16:15:58 +0000963 except:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000964 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000965
966 def close(self):
967 """
968 Clean up this handler.
969
970 You can remove the application name from the registry as a
971 source of event log entries. However, if you do this, you will
972 not be able to see the events as you intended in the Event Log
973 Viewer - it needs to be able to access the registry to get the
974 DLL name.
975 """
976 #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype)
Vinay Sajip48cfe382004-02-20 13:17:27 +0000977 logging.Handler.close(self)
Guido van Rossum57102f82002-11-13 16:15:58 +0000978
979class HTTPHandler(logging.Handler):
980 """
981 A class which sends records to a Web server, using either GET or
982 POST semantics.
983 """
Vinay Sajipaf9d10a2010-09-13 20:40:30 +0000984 def __init__(self, host, url, method="GET", secure=False, credentials=None):
Guido van Rossum57102f82002-11-13 16:15:58 +0000985 """
986 Initialize the instance with the host, the request URL, and the method
987 ("GET" or "POST")
988 """
989 logging.Handler.__init__(self)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000990 method = method.upper()
Guido van Rossum57102f82002-11-13 16:15:58 +0000991 if method not in ["GET", "POST"]:
Collin Winterce36ad82007-08-30 01:19:48 +0000992 raise ValueError("method must be GET or POST")
Guido van Rossum57102f82002-11-13 16:15:58 +0000993 self.host = host
994 self.url = url
995 self.method = method
Vinay Sajipaf9d10a2010-09-13 20:40:30 +0000996 self.secure = secure
997 self.credentials = credentials
Guido van Rossum57102f82002-11-13 16:15:58 +0000998
Neal Norwitzf297bd12003-04-23 03:49:43 +0000999 def mapLogRecord(self, record):
1000 """
1001 Default implementation of mapping the log record into a dict
Vinay Sajip48cfe382004-02-20 13:17:27 +00001002 that is sent as the CGI data. Overwrite in your class.
Vinay Sajipaf9d10a2010-09-13 20:40:30 +00001003 Contributed by Franz Glasner.
Neal Norwitzf297bd12003-04-23 03:49:43 +00001004 """
1005 return record.__dict__
1006
Guido van Rossum57102f82002-11-13 16:15:58 +00001007 def emit(self, record):
1008 """
1009 Emit a record.
1010
Senthil Kumaran30e86a42010-08-09 20:01:35 +00001011 Send the record to the Web server as a percent-encoded dictionary
Guido van Rossum57102f82002-11-13 16:15:58 +00001012 """
1013 try:
Georg Brandl029986a2008-06-23 11:44:14 +00001014 import http.client, urllib.parse
Vinay Sajipb7935062005-10-11 13:15:31 +00001015 host = self.host
Vinay Sajipaf9d10a2010-09-13 20:40:30 +00001016 if self.secure:
1017 h = http.client.HTTPSConnection(host)
1018 else:
1019 h = http.client.HTTPConnection(host)
Guido van Rossum57102f82002-11-13 16:15:58 +00001020 url = self.url
Georg Brandl029986a2008-06-23 11:44:14 +00001021 data = urllib.parse.urlencode(self.mapLogRecord(record))
Guido van Rossum57102f82002-11-13 16:15:58 +00001022 if self.method == "GET":
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001023 if (url.find('?') >= 0):
Guido van Rossum57102f82002-11-13 16:15:58 +00001024 sep = '&'
1025 else:
1026 sep = '?'
1027 url = url + "%c%s" % (sep, data)
1028 h.putrequest(self.method, url)
Vinay Sajipb7935062005-10-11 13:15:31 +00001029 # support multiple hosts on one IP address...
1030 # need to strip optional :port from host, if present
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001031 i = host.find(":")
Vinay Sajipb7935062005-10-11 13:15:31 +00001032 if i >= 0:
1033 host = host[:i]
1034 h.putheader("Host", host)
Guido van Rossum57102f82002-11-13 16:15:58 +00001035 if self.method == "POST":
Vinay Sajipb7935062005-10-11 13:15:31 +00001036 h.putheader("Content-type",
1037 "application/x-www-form-urlencoded")
Guido van Rossum57102f82002-11-13 16:15:58 +00001038 h.putheader("Content-length", str(len(data)))
Vinay Sajipaf9d10a2010-09-13 20:40:30 +00001039 if self.credentials:
1040 import base64
1041 s = ('u%s:%s' % self.credentials).encode('utf-8')
1042 s = 'Basic ' + base64.b64encode(s).strip()
1043 h.putheader('Authorization', s)
Benjamin Peterson458ad472009-01-18 00:08:45 +00001044 h.endheaders(data if self.method == "POST" else None)
Vinay Sajipaf9d10a2010-09-13 20:40:30 +00001045 h.getresponse() #can't do anything with the result
Vinay Sajip985ef872011-04-26 19:34:04 +01001046 except (KeyboardInterrupt, SystemExit): #pragma: no cover
Vinay Sajip245a5ab2005-10-31 14:27:01 +00001047 raise
Guido van Rossum57102f82002-11-13 16:15:58 +00001048 except:
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001049 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +00001050
1051class BufferingHandler(logging.Handler):
1052 """
1053 A handler class which buffers logging records in memory. Whenever each
1054 record is added to the buffer, a check is made to see if the buffer should
1055 be flushed. If it should, then flush() is expected to do what's needed.
1056 """
1057 def __init__(self, capacity):
1058 """
1059 Initialize the handler with the buffer size.
1060 """
1061 logging.Handler.__init__(self)
1062 self.capacity = capacity
1063 self.buffer = []
1064
1065 def shouldFlush(self, record):
1066 """
1067 Should the handler flush its buffer?
1068
1069 Returns true if the buffer is up to capacity. This method can be
1070 overridden to implement custom flushing strategies.
1071 """
1072 return (len(self.buffer) >= self.capacity)
1073
1074 def emit(self, record):
1075 """
1076 Emit a record.
1077
1078 Append the record. If shouldFlush() tells us to, call flush() to process
1079 the buffer.
1080 """
1081 self.buffer.append(record)
1082 if self.shouldFlush(record):
1083 self.flush()
1084
1085 def flush(self):
1086 """
1087 Override to implement custom flushing behaviour.
1088
1089 This version just zaps the buffer to empty.
1090 """
1091 self.buffer = []
1092
Vinay Sajipf42d95e2004-02-21 22:14:34 +00001093 def close(self):
1094 """
1095 Close the handler.
1096
1097 This version just flushes and chains to the parent class' close().
1098 """
1099 self.flush()
1100 logging.Handler.close(self)
1101
Guido van Rossum57102f82002-11-13 16:15:58 +00001102class MemoryHandler(BufferingHandler):
1103 """
1104 A handler class which buffers logging records in memory, periodically
1105 flushing them to a target handler. Flushing occurs whenever the buffer
1106 is full, or when an event of a certain severity or greater is seen.
1107 """
1108 def __init__(self, capacity, flushLevel=logging.ERROR, target=None):
1109 """
1110 Initialize the handler with the buffer size, the level at which
1111 flushing should occur and an optional target.
1112
1113 Note that without a target being set either here or via setTarget(),
1114 a MemoryHandler is no use to anyone!
1115 """
1116 BufferingHandler.__init__(self, capacity)
1117 self.flushLevel = flushLevel
1118 self.target = target
1119
1120 def shouldFlush(self, record):
1121 """
1122 Check for buffer full or a record at the flushLevel or higher.
1123 """
1124 return (len(self.buffer) >= self.capacity) or \
1125 (record.levelno >= self.flushLevel)
1126
1127 def setTarget(self, target):
1128 """
1129 Set the target handler for this handler.
1130 """
1131 self.target = target
1132
1133 def flush(self):
1134 """
1135 For a MemoryHandler, flushing means just sending the buffered
1136 records to the target, if there is one. Override if you want
1137 different behaviour.
Vinay Sajipc84f0162010-09-21 11:25:39 +00001138
1139 The record buffer is also cleared by this operation.
Guido van Rossum57102f82002-11-13 16:15:58 +00001140 """
1141 if self.target:
1142 for record in self.buffer:
1143 self.target.handle(record)
1144 self.buffer = []
1145
1146 def close(self):
1147 """
1148 Flush, set the target to None and lose the buffer.
1149 """
1150 self.flush()
1151 self.target = None
Vinay Sajip48cfe382004-02-20 13:17:27 +00001152 BufferingHandler.close(self)
Vinay Sajip121a1c42010-09-08 10:46:15 +00001153
1154
1155class QueueHandler(logging.Handler):
1156 """
1157 This handler sends events to a queue. Typically, it would be used together
1158 with a multiprocessing Queue to centralise logging to file in one process
1159 (in a multi-process application), so as to avoid file write contention
1160 between processes.
1161
1162 This code is new in Python 3.2, but this class can be copy pasted into
1163 user code for use with earlier Python versions.
1164 """
1165
1166 def __init__(self, queue):
1167 """
1168 Initialise an instance, using the passed queue.
1169 """
1170 logging.Handler.__init__(self)
1171 self.queue = queue
1172
1173 def enqueue(self, record):
1174 """
1175 Enqueue a record.
1176
1177 The base implementation uses put_nowait. You may want to override
1178 this method if you want to use blocking, timeouts or custom queue
1179 implementations.
1180 """
1181 self.queue.put_nowait(record)
1182
Vinay Sajip0258ce82010-09-22 20:34:53 +00001183 def prepare(self, record):
1184 """
Vinay Sajip0637d492010-09-23 08:15:54 +00001185 Prepares a record for queuing. The object returned by this method is
1186 enqueued.
Vinay Sajip0258ce82010-09-22 20:34:53 +00001187
1188 The base implementation formats the record to merge the message
1189 and arguments, and removes unpickleable items from the record
1190 in-place.
1191
1192 You might want to override this method if you want to convert
1193 the record to a dict or JSON string, or send a modified copy
1194 of the record while leaving the original intact.
1195 """
1196 # The format operation gets traceback text into record.exc_text
1197 # (if there's exception data), and also puts the message into
1198 # record.message. We can then use this to replace the original
1199 # msg + args, as these might be unpickleable. We also zap the
1200 # exc_info attribute, as it's no longer needed and, if not None,
1201 # will typically not be pickleable.
1202 self.format(record)
1203 record.msg = record.message
1204 record.args = None
1205 record.exc_info = None
1206 return record
1207
Vinay Sajip121a1c42010-09-08 10:46:15 +00001208 def emit(self, record):
1209 """
1210 Emit a record.
1211
Vinay Sajip0637d492010-09-23 08:15:54 +00001212 Writes the LogRecord to the queue, preparing it for pickling first.
Vinay Sajip121a1c42010-09-08 10:46:15 +00001213 """
1214 try:
Vinay Sajip0258ce82010-09-22 20:34:53 +00001215 self.enqueue(self.prepare(record))
Vinay Sajip985ef872011-04-26 19:34:04 +01001216 except (KeyboardInterrupt, SystemExit): #pragma: no cover
Vinay Sajip121a1c42010-09-08 10:46:15 +00001217 raise
1218 except:
1219 self.handleError(record)
Vinay Sajip0637d492010-09-23 08:15:54 +00001220
1221class QueueListener(object):
1222 """
1223 This class implements an internal threaded listener which watches for
1224 LogRecords being added to a queue, removes them and passes them to a
1225 list of handlers for processing.
1226 """
1227 _sentinel = None
1228
1229 def __init__(self, queue, *handlers):
1230 """
1231 Initialise an instance with the specified queue and
1232 handlers.
1233 """
1234 self.queue = queue
1235 self.handlers = handlers
1236 self._stop = threading.Event()
1237 self._thread = None
1238
1239 def dequeue(self, block):
1240 """
1241 Dequeue a record and return it, optionally blocking.
1242
1243 The base implementation uses get. You may want to override this method
1244 if you want to use timeouts or work with custom queue implementations.
1245 """
1246 return self.queue.get(block)
1247
1248 def start(self):
1249 """
1250 Start the listener.
1251
1252 This starts up a background thread to monitor the queue for
1253 LogRecords to process.
1254 """
1255 self._thread = t = threading.Thread(target=self._monitor)
1256 t.setDaemon(True)
1257 t.start()
1258
1259 def prepare(self , record):
1260 """
1261 Prepare a record for handling.
1262
1263 This method just returns the passed-in record. You may want to
1264 override this method if you need to do any custom marshalling or
1265 manipulation of the record before passing it to the handlers.
1266 """
1267 return record
1268
1269 def handle(self, record):
1270 """
1271 Handle a record.
1272
1273 This just loops through the handlers offering them the record
1274 to handle.
1275 """
1276 record = self.prepare(record)
1277 for handler in self.handlers:
1278 handler.handle(record)
1279
1280 def _monitor(self):
1281 """
1282 Monitor the queue for records, and ask the handler
1283 to deal with them.
1284
1285 This method runs on a separate, internal thread.
1286 The thread will terminate if it sees a sentinel object in the queue.
1287 """
1288 q = self.queue
1289 has_task_done = hasattr(q, 'task_done')
1290 while not self._stop.isSet():
1291 try:
1292 record = self.dequeue(True)
1293 if record is self._sentinel:
1294 break
1295 self.handle(record)
1296 if has_task_done:
1297 q.task_done()
1298 except queue.Empty:
1299 pass
1300 # There might still be records in the queue.
1301 while True:
1302 try:
1303 record = self.dequeue(False)
1304 if record is self._sentinel:
1305 break
1306 self.handle(record)
1307 if has_task_done:
1308 q.task_done()
1309 except queue.Empty:
1310 break
1311
Vinay Sajipaa7c1792011-02-25 15:56:55 +00001312 def enqueue_sentinel(self):
1313 """
1314 This is used to enqueue the sentinel record.
1315
1316 The base implementation uses put_nowait. You may want to override this
1317 method if you want to use timeouts or work with custom queue
1318 implementations.
1319 """
1320 self.queue.put_nowait(self._sentinel)
1321
Vinay Sajip0637d492010-09-23 08:15:54 +00001322 def stop(self):
1323 """
1324 Stop the listener.
1325
1326 This asks the thread to terminate, and then waits for it to do so.
1327 Note that if you don't call this before your application exits, there
1328 may be some records still left on the queue, which won't be processed.
1329 """
1330 self._stop.set()
Vinay Sajipaa7c1792011-02-25 15:56:55 +00001331 self.enqueue_sentinel()
Vinay Sajip0637d492010-09-23 08:15:54 +00001332 self._thread.join()
1333 self._thread = None