jpayne@68: # Copyright 2001-2016 by Vinay Sajip. All Rights Reserved. jpayne@68: # jpayne@68: # Permission to use, copy, modify, and distribute this software and its jpayne@68: # documentation for any purpose and without fee is hereby granted, jpayne@68: # provided that the above copyright notice appear in all copies and that jpayne@68: # both that copyright notice and this permission notice appear in jpayne@68: # supporting documentation, and that the name of Vinay Sajip jpayne@68: # not be used in advertising or publicity pertaining to distribution jpayne@68: # of the software without specific, written prior permission. jpayne@68: # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING jpayne@68: # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL jpayne@68: # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR jpayne@68: # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER jpayne@68: # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT jpayne@68: # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. jpayne@68: jpayne@68: """ jpayne@68: Additional handlers for the logging package for Python. The core package is jpayne@68: based on PEP 282 and comments thereto in comp.lang.python. jpayne@68: jpayne@68: Copyright (C) 2001-2016 Vinay Sajip. All Rights Reserved. jpayne@68: jpayne@68: To use, simply 'import logging.handlers' and log away! jpayne@68: """ jpayne@68: jpayne@68: import logging, socket, os, pickle, struct, time, re jpayne@68: from stat import ST_DEV, ST_INO, ST_MTIME jpayne@68: import queue jpayne@68: import threading jpayne@68: import copy jpayne@68: jpayne@68: # jpayne@68: # Some constants... jpayne@68: # jpayne@68: jpayne@68: DEFAULT_TCP_LOGGING_PORT = 9020 jpayne@68: DEFAULT_UDP_LOGGING_PORT = 9021 jpayne@68: DEFAULT_HTTP_LOGGING_PORT = 9022 jpayne@68: DEFAULT_SOAP_LOGGING_PORT = 9023 jpayne@68: SYSLOG_UDP_PORT = 514 jpayne@68: SYSLOG_TCP_PORT = 514 jpayne@68: jpayne@68: _MIDNIGHT = 24 * 60 * 60 # number of seconds in a day jpayne@68: jpayne@68: class BaseRotatingHandler(logging.FileHandler): jpayne@68: """ jpayne@68: Base class for handlers that rotate log files at a certain point. jpayne@68: Not meant to be instantiated directly. Instead, use RotatingFileHandler jpayne@68: or TimedRotatingFileHandler. jpayne@68: """ jpayne@68: def __init__(self, filename, mode, encoding=None, delay=False): jpayne@68: """ jpayne@68: Use the specified filename for streamed logging jpayne@68: """ jpayne@68: logging.FileHandler.__init__(self, filename, mode, encoding, delay) jpayne@68: self.mode = mode jpayne@68: self.encoding = encoding jpayne@68: self.namer = None jpayne@68: self.rotator = None jpayne@68: jpayne@68: def emit(self, record): jpayne@68: """ jpayne@68: Emit a record. jpayne@68: jpayne@68: Output the record to the file, catering for rollover as described jpayne@68: in doRollover(). jpayne@68: """ jpayne@68: try: jpayne@68: if self.shouldRollover(record): jpayne@68: self.doRollover() jpayne@68: logging.FileHandler.emit(self, record) jpayne@68: except Exception: jpayne@68: self.handleError(record) jpayne@68: jpayne@68: def rotation_filename(self, default_name): jpayne@68: """ jpayne@68: Modify the filename of a log file when rotating. jpayne@68: jpayne@68: This is provided so that a custom filename can be provided. jpayne@68: jpayne@68: The default implementation calls the 'namer' attribute of the jpayne@68: handler, if it's callable, passing the default name to jpayne@68: it. If the attribute isn't callable (the default is None), the name jpayne@68: is returned unchanged. jpayne@68: jpayne@68: :param default_name: The default name for the log file. jpayne@68: """ jpayne@68: if not callable(self.namer): jpayne@68: result = default_name jpayne@68: else: jpayne@68: result = self.namer(default_name) jpayne@68: return result jpayne@68: jpayne@68: def rotate(self, source, dest): jpayne@68: """ jpayne@68: When rotating, rotate the current log. jpayne@68: jpayne@68: The default implementation calls the 'rotator' attribute of the jpayne@68: handler, if it's callable, passing the source and dest arguments to jpayne@68: it. If the attribute isn't callable (the default is None), the source jpayne@68: is simply renamed to the destination. jpayne@68: jpayne@68: :param source: The source filename. This is normally the base jpayne@68: filename, e.g. 'test.log' jpayne@68: :param dest: The destination filename. This is normally jpayne@68: what the source is rotated to, e.g. 'test.log.1'. jpayne@68: """ jpayne@68: if not callable(self.rotator): jpayne@68: # Issue 18940: A file may not have been created if delay is True. jpayne@68: if os.path.exists(source): jpayne@68: os.rename(source, dest) jpayne@68: else: jpayne@68: self.rotator(source, dest) jpayne@68: jpayne@68: class RotatingFileHandler(BaseRotatingHandler): jpayne@68: """ jpayne@68: Handler for logging to a set of files, which switches from one file jpayne@68: to the next when the current file reaches a certain size. jpayne@68: """ jpayne@68: def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False): jpayne@68: """ jpayne@68: Open the specified file and use it as the stream for logging. jpayne@68: jpayne@68: By default, the file grows indefinitely. You can specify particular jpayne@68: values of maxBytes and backupCount to allow the file to rollover at jpayne@68: a predetermined size. jpayne@68: jpayne@68: Rollover occurs whenever the current log file is nearly maxBytes in jpayne@68: length. If backupCount is >= 1, the system will successively create jpayne@68: new files with the same pathname as the base file, but with extensions jpayne@68: ".1", ".2" etc. appended to it. For example, with a backupCount of 5 jpayne@68: and a base file name of "app.log", you would get "app.log", jpayne@68: "app.log.1", "app.log.2", ... through to "app.log.5". The file being jpayne@68: written to is always "app.log" - when it gets filled up, it is closed jpayne@68: and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc. jpayne@68: exist, then they are renamed to "app.log.2", "app.log.3" etc. jpayne@68: respectively. jpayne@68: jpayne@68: If maxBytes is zero, rollover never occurs. jpayne@68: """ jpayne@68: # If rotation/rollover is wanted, it doesn't make sense to use another jpayne@68: # mode. If for example 'w' were specified, then if there were multiple jpayne@68: # runs of the calling application, the logs from previous runs would be jpayne@68: # lost if the 'w' is respected, because the log file would be truncated jpayne@68: # on each run. jpayne@68: if maxBytes > 0: jpayne@68: mode = 'a' jpayne@68: BaseRotatingHandler.__init__(self, filename, mode, encoding, delay) jpayne@68: self.maxBytes = maxBytes jpayne@68: self.backupCount = backupCount jpayne@68: jpayne@68: def doRollover(self): jpayne@68: """ jpayne@68: Do a rollover, as described in __init__(). jpayne@68: """ jpayne@68: if self.stream: jpayne@68: self.stream.close() jpayne@68: self.stream = None jpayne@68: if self.backupCount > 0: jpayne@68: for i in range(self.backupCount - 1, 0, -1): jpayne@68: sfn = self.rotation_filename("%s.%d" % (self.baseFilename, i)) jpayne@68: dfn = self.rotation_filename("%s.%d" % (self.baseFilename, jpayne@68: i + 1)) jpayne@68: if os.path.exists(sfn): jpayne@68: if os.path.exists(dfn): jpayne@68: os.remove(dfn) jpayne@68: os.rename(sfn, dfn) jpayne@68: dfn = self.rotation_filename(self.baseFilename + ".1") jpayne@68: if os.path.exists(dfn): jpayne@68: os.remove(dfn) jpayne@68: self.rotate(self.baseFilename, dfn) jpayne@68: if not self.delay: jpayne@68: self.stream = self._open() jpayne@68: jpayne@68: def shouldRollover(self, record): jpayne@68: """ jpayne@68: Determine if rollover should occur. jpayne@68: jpayne@68: Basically, see if the supplied record would cause the file to exceed jpayne@68: the size limit we have. jpayne@68: """ jpayne@68: if self.stream is None: # delay was set... jpayne@68: self.stream = self._open() jpayne@68: if self.maxBytes > 0: # are we rolling over? jpayne@68: msg = "%s\n" % self.format(record) jpayne@68: self.stream.seek(0, 2) #due to non-posix-compliant Windows feature jpayne@68: if self.stream.tell() + len(msg) >= self.maxBytes: jpayne@68: return 1 jpayne@68: return 0 jpayne@68: jpayne@68: class TimedRotatingFileHandler(BaseRotatingHandler): jpayne@68: """ jpayne@68: Handler for logging to a file, rotating the log file at certain timed jpayne@68: intervals. jpayne@68: jpayne@68: If backupCount is > 0, when rollover is done, no more than backupCount jpayne@68: files are kept - the oldest ones are deleted. jpayne@68: """ jpayne@68: def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None): jpayne@68: BaseRotatingHandler.__init__(self, filename, 'a', encoding, delay) jpayne@68: self.when = when.upper() jpayne@68: self.backupCount = backupCount jpayne@68: self.utc = utc jpayne@68: self.atTime = atTime jpayne@68: # Calculate the real rollover interval, which is just the number of jpayne@68: # seconds between rollovers. Also set the filename suffix used when jpayne@68: # a rollover occurs. Current 'when' events supported: jpayne@68: # S - Seconds jpayne@68: # M - Minutes jpayne@68: # H - Hours jpayne@68: # D - Days jpayne@68: # midnight - roll over at midnight jpayne@68: # W{0-6} - roll over on a certain day; 0 - Monday jpayne@68: # jpayne@68: # Case of the 'when' specifier is not important; lower or upper case jpayne@68: # will work. jpayne@68: if self.when == 'S': jpayne@68: self.interval = 1 # one second jpayne@68: self.suffix = "%Y-%m-%d_%H-%M-%S" jpayne@68: self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}(\.\w+)?$" jpayne@68: elif self.when == 'M': jpayne@68: self.interval = 60 # one minute jpayne@68: self.suffix = "%Y-%m-%d_%H-%M" jpayne@68: self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}(\.\w+)?$" jpayne@68: elif self.when == 'H': jpayne@68: self.interval = 60 * 60 # one hour jpayne@68: self.suffix = "%Y-%m-%d_%H" jpayne@68: self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}(\.\w+)?$" jpayne@68: elif self.when == 'D' or self.when == 'MIDNIGHT': jpayne@68: self.interval = 60 * 60 * 24 # one day jpayne@68: self.suffix = "%Y-%m-%d" jpayne@68: self.extMatch = r"^\d{4}-\d{2}-\d{2}(\.\w+)?$" jpayne@68: elif self.when.startswith('W'): jpayne@68: self.interval = 60 * 60 * 24 * 7 # one week jpayne@68: if len(self.when) != 2: jpayne@68: raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when) jpayne@68: if self.when[1] < '0' or self.when[1] > '6': jpayne@68: raise ValueError("Invalid day specified for weekly rollover: %s" % self.when) jpayne@68: self.dayOfWeek = int(self.when[1]) jpayne@68: self.suffix = "%Y-%m-%d" jpayne@68: self.extMatch = r"^\d{4}-\d{2}-\d{2}(\.\w+)?$" jpayne@68: else: jpayne@68: raise ValueError("Invalid rollover interval specified: %s" % self.when) jpayne@68: jpayne@68: self.extMatch = re.compile(self.extMatch, re.ASCII) jpayne@68: self.interval = self.interval * interval # multiply by units requested jpayne@68: # The following line added because the filename passed in could be a jpayne@68: # path object (see Issue #27493), but self.baseFilename will be a string jpayne@68: filename = self.baseFilename jpayne@68: if os.path.exists(filename): jpayne@68: t = os.stat(filename)[ST_MTIME] jpayne@68: else: jpayne@68: t = int(time.time()) jpayne@68: self.rolloverAt = self.computeRollover(t) jpayne@68: jpayne@68: def computeRollover(self, currentTime): jpayne@68: """ jpayne@68: Work out the rollover time based on the specified time. jpayne@68: """ jpayne@68: result = currentTime + self.interval jpayne@68: # If we are rolling over at midnight or weekly, then the interval is already known. jpayne@68: # What we need to figure out is WHEN the next interval is. In other words, jpayne@68: # if you are rolling over at midnight, then your base interval is 1 day, jpayne@68: # but you want to start that one day clock at midnight, not now. So, we jpayne@68: # have to fudge the rolloverAt value in order to trigger the first rollover jpayne@68: # at the right time. After that, the regular interval will take care of jpayne@68: # the rest. Note that this code doesn't care about leap seconds. :) jpayne@68: if self.when == 'MIDNIGHT' or self.when.startswith('W'): jpayne@68: # This could be done with less code, but I wanted it to be clear jpayne@68: if self.utc: jpayne@68: t = time.gmtime(currentTime) jpayne@68: else: jpayne@68: t = time.localtime(currentTime) jpayne@68: currentHour = t[3] jpayne@68: currentMinute = t[4] jpayne@68: currentSecond = t[5] jpayne@68: currentDay = t[6] jpayne@68: # r is the number of seconds left between now and the next rotation jpayne@68: if self.atTime is None: jpayne@68: rotate_ts = _MIDNIGHT jpayne@68: else: jpayne@68: rotate_ts = ((self.atTime.hour * 60 + self.atTime.minute)*60 + jpayne@68: self.atTime.second) jpayne@68: jpayne@68: r = rotate_ts - ((currentHour * 60 + currentMinute) * 60 + jpayne@68: currentSecond) jpayne@68: if r < 0: jpayne@68: # Rotate time is before the current time (for example when jpayne@68: # self.rotateAt is 13:45 and it now 14:15), rotation is jpayne@68: # tomorrow. jpayne@68: r += _MIDNIGHT jpayne@68: currentDay = (currentDay + 1) % 7 jpayne@68: result = currentTime + r jpayne@68: # If we are rolling over on a certain day, add in the number of days until jpayne@68: # the next rollover, but offset by 1 since we just calculated the time jpayne@68: # until the next day starts. There are three cases: jpayne@68: # Case 1) The day to rollover is today; in this case, do nothing jpayne@68: # Case 2) The day to rollover is further in the interval (i.e., today is jpayne@68: # day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to jpayne@68: # next rollover is simply 6 - 2 - 1, or 3. jpayne@68: # Case 3) The day to rollover is behind us in the interval (i.e., today jpayne@68: # is day 5 (Saturday) and rollover is on day 3 (Thursday). jpayne@68: # Days to rollover is 6 - 5 + 3, or 4. In this case, it's the jpayne@68: # number of days left in the current week (1) plus the number jpayne@68: # of days in the next week until the rollover day (3). jpayne@68: # The calculations described in 2) and 3) above need to have a day added. jpayne@68: # This is because the above time calculation takes us to midnight on this jpayne@68: # day, i.e. the start of the next day. jpayne@68: if self.when.startswith('W'): jpayne@68: day = currentDay # 0 is Monday jpayne@68: if day != self.dayOfWeek: jpayne@68: if day < self.dayOfWeek: jpayne@68: daysToWait = self.dayOfWeek - day jpayne@68: else: jpayne@68: daysToWait = 6 - day + self.dayOfWeek + 1 jpayne@68: newRolloverAt = result + (daysToWait * (60 * 60 * 24)) jpayne@68: if not self.utc: jpayne@68: dstNow = t[-1] jpayne@68: dstAtRollover = time.localtime(newRolloverAt)[-1] jpayne@68: if dstNow != dstAtRollover: jpayne@68: if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour jpayne@68: addend = -3600 jpayne@68: else: # DST bows out before next rollover, so we need to add an hour jpayne@68: addend = 3600 jpayne@68: newRolloverAt += addend jpayne@68: result = newRolloverAt jpayne@68: return result jpayne@68: jpayne@68: def shouldRollover(self, record): jpayne@68: """ jpayne@68: Determine if rollover should occur. jpayne@68: jpayne@68: record is not used, as we are just comparing times, but it is needed so jpayne@68: the method signatures are the same jpayne@68: """ jpayne@68: t = int(time.time()) jpayne@68: if t >= self.rolloverAt: jpayne@68: return 1 jpayne@68: return 0 jpayne@68: jpayne@68: def getFilesToDelete(self): jpayne@68: """ jpayne@68: Determine the files to delete when rolling over. jpayne@68: jpayne@68: More specific than the earlier method, which just used glob.glob(). jpayne@68: """ jpayne@68: dirName, baseName = os.path.split(self.baseFilename) jpayne@68: fileNames = os.listdir(dirName) jpayne@68: result = [] jpayne@68: prefix = baseName + "." jpayne@68: plen = len(prefix) jpayne@68: for fileName in fileNames: jpayne@68: if fileName[:plen] == prefix: jpayne@68: suffix = fileName[plen:] jpayne@68: if self.extMatch.match(suffix): jpayne@68: result.append(os.path.join(dirName, fileName)) jpayne@68: if len(result) < self.backupCount: jpayne@68: result = [] jpayne@68: else: jpayne@68: result.sort() jpayne@68: result = result[:len(result) - self.backupCount] jpayne@68: return result jpayne@68: jpayne@68: def doRollover(self): jpayne@68: """ jpayne@68: do a rollover; in this case, a date/time stamp is appended to the filename jpayne@68: when the rollover happens. However, you want the file to be named for the jpayne@68: start of the interval, not the current time. If there is a backup count, jpayne@68: then we have to get a list of matching filenames, sort them and remove jpayne@68: the one with the oldest suffix. jpayne@68: """ jpayne@68: if self.stream: jpayne@68: self.stream.close() jpayne@68: self.stream = None jpayne@68: # get the time that this sequence started at and make it a TimeTuple jpayne@68: currentTime = int(time.time()) jpayne@68: dstNow = time.localtime(currentTime)[-1] jpayne@68: t = self.rolloverAt - self.interval jpayne@68: if self.utc: jpayne@68: timeTuple = time.gmtime(t) jpayne@68: else: jpayne@68: timeTuple = time.localtime(t) jpayne@68: dstThen = timeTuple[-1] jpayne@68: if dstNow != dstThen: jpayne@68: if dstNow: jpayne@68: addend = 3600 jpayne@68: else: jpayne@68: addend = -3600 jpayne@68: timeTuple = time.localtime(t + addend) jpayne@68: dfn = self.rotation_filename(self.baseFilename + "." + jpayne@68: time.strftime(self.suffix, timeTuple)) jpayne@68: if os.path.exists(dfn): jpayne@68: os.remove(dfn) jpayne@68: self.rotate(self.baseFilename, dfn) jpayne@68: if self.backupCount > 0: jpayne@68: for s in self.getFilesToDelete(): jpayne@68: os.remove(s) jpayne@68: if not self.delay: jpayne@68: self.stream = self._open() jpayne@68: newRolloverAt = self.computeRollover(currentTime) jpayne@68: while newRolloverAt <= currentTime: jpayne@68: newRolloverAt = newRolloverAt + self.interval jpayne@68: #If DST changes and midnight or weekly rollover, adjust for this. jpayne@68: if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc: jpayne@68: dstAtRollover = time.localtime(newRolloverAt)[-1] jpayne@68: if dstNow != dstAtRollover: jpayne@68: if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour jpayne@68: addend = -3600 jpayne@68: else: # DST bows out before next rollover, so we need to add an hour jpayne@68: addend = 3600 jpayne@68: newRolloverAt += addend jpayne@68: self.rolloverAt = newRolloverAt jpayne@68: jpayne@68: class WatchedFileHandler(logging.FileHandler): jpayne@68: """ jpayne@68: A handler for logging to a file, which watches the file jpayne@68: to see if it has changed while in use. This can happen because of jpayne@68: usage of programs such as newsyslog and logrotate which perform jpayne@68: log file rotation. This handler, intended for use under Unix, jpayne@68: watches the file to see if it has changed since the last emit. jpayne@68: (A file has changed if its device or inode have changed.) jpayne@68: If it has changed, the old file stream is closed, and the file jpayne@68: opened to get a new stream. jpayne@68: jpayne@68: This handler is not appropriate for use under Windows, because jpayne@68: under Windows open files cannot be moved or renamed - logging jpayne@68: opens the files with exclusive locks - and so there is no need jpayne@68: for such a handler. Furthermore, ST_INO is not supported under jpayne@68: Windows; stat always returns zero for this value. jpayne@68: jpayne@68: This handler is based on a suggestion and patch by Chad J. jpayne@68: Schroeder. jpayne@68: """ jpayne@68: def __init__(self, filename, mode='a', encoding=None, delay=False): jpayne@68: logging.FileHandler.__init__(self, filename, mode, encoding, delay) jpayne@68: self.dev, self.ino = -1, -1 jpayne@68: self._statstream() jpayne@68: jpayne@68: def _statstream(self): jpayne@68: if self.stream: jpayne@68: sres = os.fstat(self.stream.fileno()) jpayne@68: self.dev, self.ino = sres[ST_DEV], sres[ST_INO] jpayne@68: jpayne@68: def reopenIfNeeded(self): jpayne@68: """ jpayne@68: Reopen log file if needed. jpayne@68: jpayne@68: Checks if the underlying file has changed, and if it jpayne@68: has, close the old stream and reopen the file to get the jpayne@68: current stream. jpayne@68: """ jpayne@68: # Reduce the chance of race conditions by stat'ing by path only jpayne@68: # once and then fstat'ing our new fd if we opened a new log stream. jpayne@68: # See issue #14632: Thanks to John Mulligan for the problem report jpayne@68: # and patch. jpayne@68: try: jpayne@68: # stat the file by path, checking for existence jpayne@68: sres = os.stat(self.baseFilename) jpayne@68: except FileNotFoundError: jpayne@68: sres = None jpayne@68: # compare file system stat with that of our stream file handle jpayne@68: if not sres or sres[ST_DEV] != self.dev or sres[ST_INO] != self.ino: jpayne@68: if self.stream is not None: jpayne@68: # we have an open file handle, clean it up jpayne@68: self.stream.flush() jpayne@68: self.stream.close() jpayne@68: self.stream = None # See Issue #21742: _open () might fail. jpayne@68: # open a new file handle and get new stat info from that fd jpayne@68: self.stream = self._open() jpayne@68: self._statstream() jpayne@68: jpayne@68: def emit(self, record): jpayne@68: """ jpayne@68: Emit a record. jpayne@68: jpayne@68: If underlying file has changed, reopen the file before emitting the jpayne@68: record to it. jpayne@68: """ jpayne@68: self.reopenIfNeeded() jpayne@68: logging.FileHandler.emit(self, record) jpayne@68: jpayne@68: jpayne@68: class SocketHandler(logging.Handler): jpayne@68: """ jpayne@68: A handler class which writes logging records, in pickle format, to jpayne@68: a streaming socket. The socket is kept open across logging calls. jpayne@68: If the peer resets it, an attempt is made to reconnect on the next call. jpayne@68: The pickle which is sent is that of the LogRecord's attribute dictionary jpayne@68: (__dict__), so that the receiver does not need to have the logging module jpayne@68: installed in order to process the logging event. jpayne@68: jpayne@68: To unpickle the record at the receiving end into a LogRecord, use the jpayne@68: makeLogRecord function. jpayne@68: """ jpayne@68: jpayne@68: def __init__(self, host, port): jpayne@68: """ jpayne@68: Initializes the handler with a specific host address and port. jpayne@68: jpayne@68: When the attribute *closeOnError* is set to True - if a socket error jpayne@68: occurs, the socket is silently closed and then reopened on the next jpayne@68: logging call. jpayne@68: """ jpayne@68: logging.Handler.__init__(self) jpayne@68: self.host = host jpayne@68: self.port = port jpayne@68: if port is None: jpayne@68: self.address = host jpayne@68: else: jpayne@68: self.address = (host, port) jpayne@68: self.sock = None jpayne@68: self.closeOnError = False jpayne@68: self.retryTime = None jpayne@68: # jpayne@68: # Exponential backoff parameters. jpayne@68: # jpayne@68: self.retryStart = 1.0 jpayne@68: self.retryMax = 30.0 jpayne@68: self.retryFactor = 2.0 jpayne@68: jpayne@68: def makeSocket(self, timeout=1): jpayne@68: """ jpayne@68: A factory method which allows subclasses to define the precise jpayne@68: type of socket they want. jpayne@68: """ jpayne@68: if self.port is not None: jpayne@68: result = socket.create_connection(self.address, timeout=timeout) jpayne@68: else: jpayne@68: result = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) jpayne@68: result.settimeout(timeout) jpayne@68: try: jpayne@68: result.connect(self.address) jpayne@68: except OSError: jpayne@68: result.close() # Issue 19182 jpayne@68: raise jpayne@68: return result jpayne@68: jpayne@68: def createSocket(self): jpayne@68: """ jpayne@68: Try to create a socket, using an exponential backoff with jpayne@68: a max retry time. Thanks to Robert Olson for the original patch jpayne@68: (SF #815911) which has been slightly refactored. jpayne@68: """ jpayne@68: now = time.time() jpayne@68: # Either retryTime is None, in which case this jpayne@68: # is the first time back after a disconnect, or jpayne@68: # we've waited long enough. jpayne@68: if self.retryTime is None: jpayne@68: attempt = True jpayne@68: else: jpayne@68: attempt = (now >= self.retryTime) jpayne@68: if attempt: jpayne@68: try: jpayne@68: self.sock = self.makeSocket() jpayne@68: self.retryTime = None # next time, no delay before trying jpayne@68: except OSError: jpayne@68: #Creation failed, so set the retry time and return. jpayne@68: if self.retryTime is None: jpayne@68: self.retryPeriod = self.retryStart jpayne@68: else: jpayne@68: self.retryPeriod = self.retryPeriod * self.retryFactor jpayne@68: if self.retryPeriod > self.retryMax: jpayne@68: self.retryPeriod = self.retryMax jpayne@68: self.retryTime = now + self.retryPeriod jpayne@68: jpayne@68: def send(self, s): jpayne@68: """ jpayne@68: Send a pickled string to the socket. jpayne@68: jpayne@68: This function allows for partial sends which can happen when the jpayne@68: network is busy. jpayne@68: """ jpayne@68: if self.sock is None: jpayne@68: self.createSocket() jpayne@68: #self.sock can be None either because we haven't reached the retry jpayne@68: #time yet, or because we have reached the retry time and retried, jpayne@68: #but are still unable to connect. jpayne@68: if self.sock: jpayne@68: try: jpayne@68: self.sock.sendall(s) jpayne@68: except OSError: #pragma: no cover jpayne@68: self.sock.close() jpayne@68: self.sock = None # so we can call createSocket next time jpayne@68: jpayne@68: def makePickle(self, record): jpayne@68: """ jpayne@68: Pickles the record in binary format with a length prefix, and jpayne@68: returns it ready for transmission across the socket. jpayne@68: """ jpayne@68: ei = record.exc_info jpayne@68: if ei: jpayne@68: # just to get traceback text into record.exc_text ... jpayne@68: dummy = self.format(record) jpayne@68: # See issue #14436: If msg or args are objects, they may not be jpayne@68: # available on the receiving end. So we convert the msg % args jpayne@68: # to a string, save it as msg and zap the args. jpayne@68: d = dict(record.__dict__) jpayne@68: d['msg'] = record.getMessage() jpayne@68: d['args'] = None jpayne@68: d['exc_info'] = None jpayne@68: # Issue #25685: delete 'message' if present: redundant with 'msg' jpayne@68: d.pop('message', None) jpayne@68: s = pickle.dumps(d, 1) jpayne@68: slen = struct.pack(">L", len(s)) jpayne@68: return slen + s jpayne@68: jpayne@68: def handleError(self, record): jpayne@68: """ jpayne@68: Handle an error during logging. jpayne@68: jpayne@68: An error has occurred during logging. Most likely cause - jpayne@68: connection lost. Close the socket so that we can retry on the jpayne@68: next event. jpayne@68: """ jpayne@68: if self.closeOnError and self.sock: jpayne@68: self.sock.close() jpayne@68: self.sock = None #try to reconnect next time jpayne@68: else: jpayne@68: logging.Handler.handleError(self, record) jpayne@68: jpayne@68: def emit(self, record): jpayne@68: """ jpayne@68: Emit a record. jpayne@68: jpayne@68: Pickles the record and writes it to the socket in binary format. jpayne@68: If there is an error with the socket, silently drop the packet. jpayne@68: If there was a problem with the socket, re-establishes the jpayne@68: socket. jpayne@68: """ jpayne@68: try: jpayne@68: s = self.makePickle(record) jpayne@68: self.send(s) jpayne@68: except Exception: jpayne@68: self.handleError(record) jpayne@68: jpayne@68: def close(self): jpayne@68: """ jpayne@68: Closes the socket. jpayne@68: """ jpayne@68: self.acquire() jpayne@68: try: jpayne@68: sock = self.sock jpayne@68: if sock: jpayne@68: self.sock = None jpayne@68: sock.close() jpayne@68: logging.Handler.close(self) jpayne@68: finally: jpayne@68: self.release() jpayne@68: jpayne@68: class DatagramHandler(SocketHandler): jpayne@68: """ jpayne@68: A handler class which writes logging records, in pickle format, to jpayne@68: a datagram socket. The pickle which is sent is that of the LogRecord's jpayne@68: attribute dictionary (__dict__), so that the receiver does not need to jpayne@68: have the logging module installed in order to process the logging event. jpayne@68: jpayne@68: To unpickle the record at the receiving end into a LogRecord, use the jpayne@68: makeLogRecord function. jpayne@68: jpayne@68: """ jpayne@68: def __init__(self, host, port): jpayne@68: """ jpayne@68: Initializes the handler with a specific host address and port. jpayne@68: """ jpayne@68: SocketHandler.__init__(self, host, port) jpayne@68: self.closeOnError = False jpayne@68: jpayne@68: def makeSocket(self): jpayne@68: """ jpayne@68: The factory method of SocketHandler is here overridden to create jpayne@68: a UDP socket (SOCK_DGRAM). jpayne@68: """ jpayne@68: if self.port is None: jpayne@68: family = socket.AF_UNIX jpayne@68: else: jpayne@68: family = socket.AF_INET jpayne@68: s = socket.socket(family, socket.SOCK_DGRAM) jpayne@68: return s jpayne@68: jpayne@68: def send(self, s): jpayne@68: """ jpayne@68: Send a pickled string to a socket. jpayne@68: jpayne@68: This function no longer allows for partial sends which can happen jpayne@68: when the network is busy - UDP does not guarantee delivery and jpayne@68: can deliver packets out of sequence. jpayne@68: """ jpayne@68: if self.sock is None: jpayne@68: self.createSocket() jpayne@68: self.sock.sendto(s, self.address) jpayne@68: jpayne@68: class SysLogHandler(logging.Handler): jpayne@68: """ jpayne@68: A handler class which sends formatted logging records to a syslog jpayne@68: server. Based on Sam Rushing's syslog module: jpayne@68: http://www.nightmare.com/squirl/python-ext/misc/syslog.py jpayne@68: Contributed by Nicolas Untz (after which minor refactoring changes jpayne@68: have been made). jpayne@68: """ jpayne@68: jpayne@68: # from : jpayne@68: # ====================================================================== jpayne@68: # priorities/facilities are encoded into a single 32-bit quantity, where jpayne@68: # the bottom 3 bits are the priority (0-7) and the top 28 bits are the jpayne@68: # facility (0-big number). Both the priorities and the facilities map jpayne@68: # roughly one-to-one to strings in the syslogd(8) source code. This jpayne@68: # mapping is included in this file. jpayne@68: # jpayne@68: # priorities (these are ordered) jpayne@68: jpayne@68: LOG_EMERG = 0 # system is unusable jpayne@68: LOG_ALERT = 1 # action must be taken immediately jpayne@68: LOG_CRIT = 2 # critical conditions jpayne@68: LOG_ERR = 3 # error conditions jpayne@68: LOG_WARNING = 4 # warning conditions jpayne@68: LOG_NOTICE = 5 # normal but significant condition jpayne@68: LOG_INFO = 6 # informational jpayne@68: LOG_DEBUG = 7 # debug-level messages jpayne@68: jpayne@68: # facility codes jpayne@68: LOG_KERN = 0 # kernel messages jpayne@68: LOG_USER = 1 # random user-level messages jpayne@68: LOG_MAIL = 2 # mail system jpayne@68: LOG_DAEMON = 3 # system daemons jpayne@68: LOG_AUTH = 4 # security/authorization messages jpayne@68: LOG_SYSLOG = 5 # messages generated internally by syslogd jpayne@68: LOG_LPR = 6 # line printer subsystem jpayne@68: LOG_NEWS = 7 # network news subsystem jpayne@68: LOG_UUCP = 8 # UUCP subsystem jpayne@68: LOG_CRON = 9 # clock daemon jpayne@68: LOG_AUTHPRIV = 10 # security/authorization messages (private) jpayne@68: LOG_FTP = 11 # FTP daemon jpayne@68: jpayne@68: # other codes through 15 reserved for system use jpayne@68: LOG_LOCAL0 = 16 # reserved for local use jpayne@68: LOG_LOCAL1 = 17 # reserved for local use jpayne@68: LOG_LOCAL2 = 18 # reserved for local use jpayne@68: LOG_LOCAL3 = 19 # reserved for local use jpayne@68: LOG_LOCAL4 = 20 # reserved for local use jpayne@68: LOG_LOCAL5 = 21 # reserved for local use jpayne@68: LOG_LOCAL6 = 22 # reserved for local use jpayne@68: LOG_LOCAL7 = 23 # reserved for local use jpayne@68: jpayne@68: priority_names = { jpayne@68: "alert": LOG_ALERT, jpayne@68: "crit": LOG_CRIT, jpayne@68: "critical": LOG_CRIT, jpayne@68: "debug": LOG_DEBUG, jpayne@68: "emerg": LOG_EMERG, jpayne@68: "err": LOG_ERR, jpayne@68: "error": LOG_ERR, # DEPRECATED jpayne@68: "info": LOG_INFO, jpayne@68: "notice": LOG_NOTICE, jpayne@68: "panic": LOG_EMERG, # DEPRECATED jpayne@68: "warn": LOG_WARNING, # DEPRECATED jpayne@68: "warning": LOG_WARNING, jpayne@68: } jpayne@68: jpayne@68: facility_names = { jpayne@68: "auth": LOG_AUTH, jpayne@68: "authpriv": LOG_AUTHPRIV, jpayne@68: "cron": LOG_CRON, jpayne@68: "daemon": LOG_DAEMON, jpayne@68: "ftp": LOG_FTP, jpayne@68: "kern": LOG_KERN, jpayne@68: "lpr": LOG_LPR, jpayne@68: "mail": LOG_MAIL, jpayne@68: "news": LOG_NEWS, jpayne@68: "security": LOG_AUTH, # DEPRECATED jpayne@68: "syslog": LOG_SYSLOG, jpayne@68: "user": LOG_USER, jpayne@68: "uucp": LOG_UUCP, jpayne@68: "local0": LOG_LOCAL0, jpayne@68: "local1": LOG_LOCAL1, jpayne@68: "local2": LOG_LOCAL2, jpayne@68: "local3": LOG_LOCAL3, jpayne@68: "local4": LOG_LOCAL4, jpayne@68: "local5": LOG_LOCAL5, jpayne@68: "local6": LOG_LOCAL6, jpayne@68: "local7": LOG_LOCAL7, jpayne@68: } jpayne@68: jpayne@68: #The map below appears to be trivially lowercasing the key. However, jpayne@68: #there's more to it than meets the eye - in some locales, lowercasing jpayne@68: #gives unexpected results. See SF #1524081: in the Turkish locale, jpayne@68: #"INFO".lower() != "info" jpayne@68: priority_map = { jpayne@68: "DEBUG" : "debug", jpayne@68: "INFO" : "info", jpayne@68: "WARNING" : "warning", jpayne@68: "ERROR" : "error", jpayne@68: "CRITICAL" : "critical" jpayne@68: } jpayne@68: jpayne@68: def __init__(self, address=('localhost', SYSLOG_UDP_PORT), jpayne@68: facility=LOG_USER, socktype=None): jpayne@68: """ jpayne@68: Initialize a handler. jpayne@68: jpayne@68: If address is specified as a string, a UNIX socket is used. To log to a jpayne@68: local syslogd, "SysLogHandler(address="/dev/log")" can be used. jpayne@68: If facility is not specified, LOG_USER is used. If socktype is jpayne@68: specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific jpayne@68: socket type will be used. For Unix sockets, you can also specify a jpayne@68: socktype of None, in which case socket.SOCK_DGRAM will be used, falling jpayne@68: back to socket.SOCK_STREAM. jpayne@68: """ jpayne@68: logging.Handler.__init__(self) jpayne@68: jpayne@68: self.address = address jpayne@68: self.facility = facility jpayne@68: self.socktype = socktype jpayne@68: jpayne@68: if isinstance(address, str): jpayne@68: self.unixsocket = True jpayne@68: # Syslog server may be unavailable during handler initialisation. jpayne@68: # C's openlog() function also ignores connection errors. jpayne@68: # Moreover, we ignore these errors while logging, so it not worse jpayne@68: # to ignore it also here. jpayne@68: try: jpayne@68: self._connect_unixsocket(address) jpayne@68: except OSError: jpayne@68: pass jpayne@68: else: jpayne@68: self.unixsocket = False jpayne@68: if socktype is None: jpayne@68: socktype = socket.SOCK_DGRAM jpayne@68: host, port = address jpayne@68: ress = socket.getaddrinfo(host, port, 0, socktype) jpayne@68: if not ress: jpayne@68: raise OSError("getaddrinfo returns an empty list") jpayne@68: for res in ress: jpayne@68: af, socktype, proto, _, sa = res jpayne@68: err = sock = None jpayne@68: try: jpayne@68: sock = socket.socket(af, socktype, proto) jpayne@68: if socktype == socket.SOCK_STREAM: jpayne@68: sock.connect(sa) jpayne@68: break jpayne@68: except OSError as exc: jpayne@68: err = exc jpayne@68: if sock is not None: jpayne@68: sock.close() jpayne@68: if err is not None: jpayne@68: raise err jpayne@68: self.socket = sock jpayne@68: self.socktype = socktype jpayne@68: jpayne@68: def _connect_unixsocket(self, address): jpayne@68: use_socktype = self.socktype jpayne@68: if use_socktype is None: jpayne@68: use_socktype = socket.SOCK_DGRAM jpayne@68: self.socket = socket.socket(socket.AF_UNIX, use_socktype) jpayne@68: try: jpayne@68: self.socket.connect(address) jpayne@68: # it worked, so set self.socktype to the used type jpayne@68: self.socktype = use_socktype jpayne@68: except OSError: jpayne@68: self.socket.close() jpayne@68: if self.socktype is not None: jpayne@68: # user didn't specify falling back, so fail jpayne@68: raise jpayne@68: use_socktype = socket.SOCK_STREAM jpayne@68: self.socket = socket.socket(socket.AF_UNIX, use_socktype) jpayne@68: try: jpayne@68: self.socket.connect(address) jpayne@68: # it worked, so set self.socktype to the used type jpayne@68: self.socktype = use_socktype jpayne@68: except OSError: jpayne@68: self.socket.close() jpayne@68: raise jpayne@68: jpayne@68: def encodePriority(self, facility, priority): jpayne@68: """ jpayne@68: Encode the facility and priority. You can pass in strings or jpayne@68: integers - if strings are passed, the facility_names and jpayne@68: priority_names mapping dictionaries are used to convert them to jpayne@68: integers. jpayne@68: """ jpayne@68: if isinstance(facility, str): jpayne@68: facility = self.facility_names[facility] jpayne@68: if isinstance(priority, str): jpayne@68: priority = self.priority_names[priority] jpayne@68: return (facility << 3) | priority jpayne@68: jpayne@68: def close(self): jpayne@68: """ jpayne@68: Closes the socket. jpayne@68: """ jpayne@68: self.acquire() jpayne@68: try: jpayne@68: self.socket.close() jpayne@68: logging.Handler.close(self) jpayne@68: finally: jpayne@68: self.release() jpayne@68: jpayne@68: def mapPriority(self, levelName): jpayne@68: """ jpayne@68: Map a logging level name to a key in the priority_names map. jpayne@68: This is useful in two scenarios: when custom levels are being jpayne@68: used, and in the case where you can't do a straightforward jpayne@68: mapping by lowercasing the logging level name because of locale- jpayne@68: specific issues (see SF #1524081). jpayne@68: """ jpayne@68: return self.priority_map.get(levelName, "warning") jpayne@68: jpayne@68: ident = '' # prepended to all messages jpayne@68: append_nul = True # some old syslog daemons expect a NUL terminator jpayne@68: jpayne@68: def emit(self, record): jpayne@68: """ jpayne@68: Emit a record. jpayne@68: jpayne@68: The record is formatted, and then sent to the syslog server. If jpayne@68: exception information is present, it is NOT sent to the server. jpayne@68: """ jpayne@68: try: jpayne@68: msg = self.format(record) jpayne@68: if self.ident: jpayne@68: msg = self.ident + msg jpayne@68: if self.append_nul: jpayne@68: msg += '\000' jpayne@68: jpayne@68: # We need to convert record level to lowercase, maybe this will jpayne@68: # change in the future. jpayne@68: prio = '<%d>' % self.encodePriority(self.facility, jpayne@68: self.mapPriority(record.levelname)) jpayne@68: prio = prio.encode('utf-8') jpayne@68: # Message is a string. Convert to bytes as required by RFC 5424 jpayne@68: msg = msg.encode('utf-8') jpayne@68: msg = prio + msg jpayne@68: if self.unixsocket: jpayne@68: try: jpayne@68: self.socket.send(msg) jpayne@68: except OSError: jpayne@68: self.socket.close() jpayne@68: self._connect_unixsocket(self.address) jpayne@68: self.socket.send(msg) jpayne@68: elif self.socktype == socket.SOCK_DGRAM: jpayne@68: self.socket.sendto(msg, self.address) jpayne@68: else: jpayne@68: self.socket.sendall(msg) jpayne@68: except Exception: jpayne@68: self.handleError(record) jpayne@68: jpayne@68: class SMTPHandler(logging.Handler): jpayne@68: """ jpayne@68: A handler class which sends an SMTP email for each logging event. jpayne@68: """ jpayne@68: def __init__(self, mailhost, fromaddr, toaddrs, subject, jpayne@68: credentials=None, secure=None, timeout=5.0): jpayne@68: """ jpayne@68: Initialize the handler. jpayne@68: jpayne@68: Initialize the instance with the from and to addresses and subject jpayne@68: line of the email. To specify a non-standard SMTP port, use the jpayne@68: (host, port) tuple format for the mailhost argument. To specify jpayne@68: authentication credentials, supply a (username, password) tuple jpayne@68: for the credentials argument. To specify the use of a secure jpayne@68: protocol (TLS), pass in a tuple for the secure argument. This will jpayne@68: only be used when authentication credentials are supplied. The tuple jpayne@68: will be either an empty tuple, or a single-value tuple with the name jpayne@68: of a keyfile, or a 2-value tuple with the names of the keyfile and jpayne@68: certificate file. (This tuple is passed to the `starttls` method). jpayne@68: A timeout in seconds can be specified for the SMTP connection (the jpayne@68: default is one second). jpayne@68: """ jpayne@68: logging.Handler.__init__(self) jpayne@68: if isinstance(mailhost, (list, tuple)): jpayne@68: self.mailhost, self.mailport = mailhost jpayne@68: else: jpayne@68: self.mailhost, self.mailport = mailhost, None jpayne@68: if isinstance(credentials, (list, tuple)): jpayne@68: self.username, self.password = credentials jpayne@68: else: jpayne@68: self.username = None jpayne@68: self.fromaddr = fromaddr jpayne@68: if isinstance(toaddrs, str): jpayne@68: toaddrs = [toaddrs] jpayne@68: self.toaddrs = toaddrs jpayne@68: self.subject = subject jpayne@68: self.secure = secure jpayne@68: self.timeout = timeout jpayne@68: jpayne@68: def getSubject(self, record): jpayne@68: """ jpayne@68: Determine the subject for the email. jpayne@68: jpayne@68: If you want to specify a subject line which is record-dependent, jpayne@68: override this method. jpayne@68: """ jpayne@68: return self.subject jpayne@68: jpayne@68: def emit(self, record): jpayne@68: """ jpayne@68: Emit a record. jpayne@68: jpayne@68: Format the record and send it to the specified addressees. jpayne@68: """ jpayne@68: try: jpayne@68: import smtplib jpayne@68: from email.message import EmailMessage jpayne@68: import email.utils jpayne@68: jpayne@68: port = self.mailport jpayne@68: if not port: jpayne@68: port = smtplib.SMTP_PORT jpayne@68: smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout) jpayne@68: msg = EmailMessage() jpayne@68: msg['From'] = self.fromaddr jpayne@68: msg['To'] = ','.join(self.toaddrs) jpayne@68: msg['Subject'] = self.getSubject(record) jpayne@68: msg['Date'] = email.utils.localtime() jpayne@68: msg.set_content(self.format(record)) jpayne@68: if self.username: jpayne@68: if self.secure is not None: jpayne@68: smtp.ehlo() jpayne@68: smtp.starttls(*self.secure) jpayne@68: smtp.ehlo() jpayne@68: smtp.login(self.username, self.password) jpayne@68: smtp.send_message(msg) jpayne@68: smtp.quit() jpayne@68: except Exception: jpayne@68: self.handleError(record) jpayne@68: jpayne@68: class NTEventLogHandler(logging.Handler): jpayne@68: """ jpayne@68: A handler class which sends events to the NT Event Log. Adds a jpayne@68: registry entry for the specified application name. If no dllname is jpayne@68: provided, win32service.pyd (which contains some basic message jpayne@68: placeholders) is used. Note that use of these placeholders will make jpayne@68: your event logs big, as the entire message source is held in the log. jpayne@68: If you want slimmer logs, you have to pass in the name of your own DLL jpayne@68: which contains the message definitions you want to use in the event log. jpayne@68: """ jpayne@68: def __init__(self, appname, dllname=None, logtype="Application"): jpayne@68: logging.Handler.__init__(self) jpayne@68: try: jpayne@68: import win32evtlogutil, win32evtlog jpayne@68: self.appname = appname jpayne@68: self._welu = win32evtlogutil jpayne@68: if not dllname: jpayne@68: dllname = os.path.split(self._welu.__file__) jpayne@68: dllname = os.path.split(dllname[0]) jpayne@68: dllname = os.path.join(dllname[0], r'win32service.pyd') jpayne@68: self.dllname = dllname jpayne@68: self.logtype = logtype jpayne@68: self._welu.AddSourceToRegistry(appname, dllname, logtype) jpayne@68: self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE jpayne@68: self.typemap = { jpayne@68: logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE, jpayne@68: logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE, jpayne@68: logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE, jpayne@68: logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE, jpayne@68: logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE, jpayne@68: } jpayne@68: except ImportError: jpayne@68: print("The Python Win32 extensions for NT (service, event "\ jpayne@68: "logging) appear not to be available.") jpayne@68: self._welu = None jpayne@68: jpayne@68: def getMessageID(self, record): jpayne@68: """ jpayne@68: Return the message ID for the event record. If you are using your jpayne@68: own messages, you could do this by having the msg passed to the jpayne@68: logger being an ID rather than a formatting string. Then, in here, jpayne@68: you could use a dictionary lookup to get the message ID. This jpayne@68: version returns 1, which is the base message ID in win32service.pyd. jpayne@68: """ jpayne@68: return 1 jpayne@68: jpayne@68: def getEventCategory(self, record): jpayne@68: """ jpayne@68: Return the event category for the record. jpayne@68: jpayne@68: Override this if you want to specify your own categories. This version jpayne@68: returns 0. jpayne@68: """ jpayne@68: return 0 jpayne@68: jpayne@68: def getEventType(self, record): jpayne@68: """ jpayne@68: Return the event type for the record. jpayne@68: jpayne@68: Override this if you want to specify your own types. This version does jpayne@68: a mapping using the handler's typemap attribute, which is set up in jpayne@68: __init__() to a dictionary which contains mappings for DEBUG, INFO, jpayne@68: WARNING, ERROR and CRITICAL. If you are using your own levels you will jpayne@68: either need to override this method or place a suitable dictionary in jpayne@68: the handler's typemap attribute. jpayne@68: """ jpayne@68: return self.typemap.get(record.levelno, self.deftype) jpayne@68: jpayne@68: def emit(self, record): jpayne@68: """ jpayne@68: Emit a record. jpayne@68: jpayne@68: Determine the message ID, event category and event type. Then jpayne@68: log the message in the NT event log. jpayne@68: """ jpayne@68: if self._welu: jpayne@68: try: jpayne@68: id = self.getMessageID(record) jpayne@68: cat = self.getEventCategory(record) jpayne@68: type = self.getEventType(record) jpayne@68: msg = self.format(record) jpayne@68: self._welu.ReportEvent(self.appname, id, cat, type, [msg]) jpayne@68: except Exception: jpayne@68: self.handleError(record) jpayne@68: jpayne@68: def close(self): jpayne@68: """ jpayne@68: Clean up this handler. jpayne@68: jpayne@68: You can remove the application name from the registry as a jpayne@68: source of event log entries. However, if you do this, you will jpayne@68: not be able to see the events as you intended in the Event Log jpayne@68: Viewer - it needs to be able to access the registry to get the jpayne@68: DLL name. jpayne@68: """ jpayne@68: #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype) jpayne@68: logging.Handler.close(self) jpayne@68: jpayne@68: class HTTPHandler(logging.Handler): jpayne@68: """ jpayne@68: A class which sends records to a Web server, using either GET or jpayne@68: POST semantics. jpayne@68: """ jpayne@68: def __init__(self, host, url, method="GET", secure=False, credentials=None, jpayne@68: context=None): jpayne@68: """ jpayne@68: Initialize the instance with the host, the request URL, and the method jpayne@68: ("GET" or "POST") jpayne@68: """ jpayne@68: logging.Handler.__init__(self) jpayne@68: method = method.upper() jpayne@68: if method not in ["GET", "POST"]: jpayne@68: raise ValueError("method must be GET or POST") jpayne@68: if not secure and context is not None: jpayne@68: raise ValueError("context parameter only makes sense " jpayne@68: "with secure=True") jpayne@68: self.host = host jpayne@68: self.url = url jpayne@68: self.method = method jpayne@68: self.secure = secure jpayne@68: self.credentials = credentials jpayne@68: self.context = context jpayne@68: jpayne@68: def mapLogRecord(self, record): jpayne@68: """ jpayne@68: Default implementation of mapping the log record into a dict jpayne@68: that is sent as the CGI data. Overwrite in your class. jpayne@68: Contributed by Franz Glasner. jpayne@68: """ jpayne@68: return record.__dict__ jpayne@68: jpayne@68: def emit(self, record): jpayne@68: """ jpayne@68: Emit a record. jpayne@68: jpayne@68: Send the record to the Web server as a percent-encoded dictionary jpayne@68: """ jpayne@68: try: jpayne@68: import http.client, urllib.parse jpayne@68: host = self.host jpayne@68: if self.secure: jpayne@68: h = http.client.HTTPSConnection(host, context=self.context) jpayne@68: else: jpayne@68: h = http.client.HTTPConnection(host) jpayne@68: url = self.url jpayne@68: data = urllib.parse.urlencode(self.mapLogRecord(record)) jpayne@68: if self.method == "GET": jpayne@68: if (url.find('?') >= 0): jpayne@68: sep = '&' jpayne@68: else: jpayne@68: sep = '?' jpayne@68: url = url + "%c%s" % (sep, data) jpayne@68: h.putrequest(self.method, url) jpayne@68: # support multiple hosts on one IP address... jpayne@68: # need to strip optional :port from host, if present jpayne@68: i = host.find(":") jpayne@68: if i >= 0: jpayne@68: host = host[:i] jpayne@68: # See issue #30904: putrequest call above already adds this header jpayne@68: # on Python 3.x. jpayne@68: # h.putheader("Host", host) jpayne@68: if self.method == "POST": jpayne@68: h.putheader("Content-type", jpayne@68: "application/x-www-form-urlencoded") jpayne@68: h.putheader("Content-length", str(len(data))) jpayne@68: if self.credentials: jpayne@68: import base64 jpayne@68: s = ('%s:%s' % self.credentials).encode('utf-8') jpayne@68: s = 'Basic ' + base64.b64encode(s).strip().decode('ascii') jpayne@68: h.putheader('Authorization', s) jpayne@68: h.endheaders() jpayne@68: if self.method == "POST": jpayne@68: h.send(data.encode('utf-8')) jpayne@68: h.getresponse() #can't do anything with the result jpayne@68: except Exception: jpayne@68: self.handleError(record) jpayne@68: jpayne@68: class BufferingHandler(logging.Handler): jpayne@68: """ jpayne@68: A handler class which buffers logging records in memory. Whenever each jpayne@68: record is added to the buffer, a check is made to see if the buffer should jpayne@68: be flushed. If it should, then flush() is expected to do what's needed. jpayne@68: """ jpayne@68: def __init__(self, capacity): jpayne@68: """ jpayne@68: Initialize the handler with the buffer size. jpayne@68: """ jpayne@68: logging.Handler.__init__(self) jpayne@68: self.capacity = capacity jpayne@68: self.buffer = [] jpayne@68: jpayne@68: def shouldFlush(self, record): jpayne@68: """ jpayne@68: Should the handler flush its buffer? jpayne@68: jpayne@68: Returns true if the buffer is up to capacity. This method can be jpayne@68: overridden to implement custom flushing strategies. jpayne@68: """ jpayne@68: return (len(self.buffer) >= self.capacity) jpayne@68: jpayne@68: def emit(self, record): jpayne@68: """ jpayne@68: Emit a record. jpayne@68: jpayne@68: Append the record. If shouldFlush() tells us to, call flush() to process jpayne@68: the buffer. jpayne@68: """ jpayne@68: self.buffer.append(record) jpayne@68: if self.shouldFlush(record): jpayne@68: self.flush() jpayne@68: jpayne@68: def flush(self): jpayne@68: """ jpayne@68: Override to implement custom flushing behaviour. jpayne@68: jpayne@68: This version just zaps the buffer to empty. jpayne@68: """ jpayne@68: self.acquire() jpayne@68: try: jpayne@68: self.buffer = [] jpayne@68: finally: jpayne@68: self.release() jpayne@68: jpayne@68: def close(self): jpayne@68: """ jpayne@68: Close the handler. jpayne@68: jpayne@68: This version just flushes and chains to the parent class' close(). jpayne@68: """ jpayne@68: try: jpayne@68: self.flush() jpayne@68: finally: jpayne@68: logging.Handler.close(self) jpayne@68: jpayne@68: class MemoryHandler(BufferingHandler): jpayne@68: """ jpayne@68: A handler class which buffers logging records in memory, periodically jpayne@68: flushing them to a target handler. Flushing occurs whenever the buffer jpayne@68: is full, or when an event of a certain severity or greater is seen. jpayne@68: """ jpayne@68: def __init__(self, capacity, flushLevel=logging.ERROR, target=None, jpayne@68: flushOnClose=True): jpayne@68: """ jpayne@68: Initialize the handler with the buffer size, the level at which jpayne@68: flushing should occur and an optional target. jpayne@68: jpayne@68: Note that without a target being set either here or via setTarget(), jpayne@68: a MemoryHandler is no use to anyone! jpayne@68: jpayne@68: The ``flushOnClose`` argument is ``True`` for backward compatibility jpayne@68: reasons - the old behaviour is that when the handler is closed, the jpayne@68: buffer is flushed, even if the flush level hasn't been exceeded nor the jpayne@68: capacity exceeded. To prevent this, set ``flushOnClose`` to ``False``. jpayne@68: """ jpayne@68: BufferingHandler.__init__(self, capacity) jpayne@68: self.flushLevel = flushLevel jpayne@68: self.target = target jpayne@68: # See Issue #26559 for why this has been added jpayne@68: self.flushOnClose = flushOnClose jpayne@68: jpayne@68: def shouldFlush(self, record): jpayne@68: """ jpayne@68: Check for buffer full or a record at the flushLevel or higher. jpayne@68: """ jpayne@68: return (len(self.buffer) >= self.capacity) or \ jpayne@68: (record.levelno >= self.flushLevel) jpayne@68: jpayne@68: def setTarget(self, target): jpayne@68: """ jpayne@68: Set the target handler for this handler. jpayne@68: """ jpayne@68: self.target = target jpayne@68: jpayne@68: def flush(self): jpayne@68: """ jpayne@68: For a MemoryHandler, flushing means just sending the buffered jpayne@68: records to the target, if there is one. Override if you want jpayne@68: different behaviour. jpayne@68: jpayne@68: The record buffer is also cleared by this operation. jpayne@68: """ jpayne@68: self.acquire() jpayne@68: try: jpayne@68: if self.target: jpayne@68: for record in self.buffer: jpayne@68: self.target.handle(record) jpayne@68: self.buffer = [] jpayne@68: finally: jpayne@68: self.release() jpayne@68: jpayne@68: def close(self): jpayne@68: """ jpayne@68: Flush, if appropriately configured, set the target to None and lose the jpayne@68: buffer. jpayne@68: """ jpayne@68: try: jpayne@68: if self.flushOnClose: jpayne@68: self.flush() jpayne@68: finally: jpayne@68: self.acquire() jpayne@68: try: jpayne@68: self.target = None jpayne@68: BufferingHandler.close(self) jpayne@68: finally: jpayne@68: self.release() jpayne@68: jpayne@68: jpayne@68: class QueueHandler(logging.Handler): jpayne@68: """ jpayne@68: This handler sends events to a queue. Typically, it would be used together jpayne@68: with a multiprocessing Queue to centralise logging to file in one process jpayne@68: (in a multi-process application), so as to avoid file write contention jpayne@68: between processes. jpayne@68: jpayne@68: This code is new in Python 3.2, but this class can be copy pasted into jpayne@68: user code for use with earlier Python versions. jpayne@68: """ jpayne@68: jpayne@68: def __init__(self, queue): jpayne@68: """ jpayne@68: Initialise an instance, using the passed queue. jpayne@68: """ jpayne@68: logging.Handler.__init__(self) jpayne@68: self.queue = queue jpayne@68: jpayne@68: def enqueue(self, record): jpayne@68: """ jpayne@68: Enqueue a record. jpayne@68: jpayne@68: The base implementation uses put_nowait. You may want to override jpayne@68: this method if you want to use blocking, timeouts or custom queue jpayne@68: implementations. jpayne@68: """ jpayne@68: self.queue.put_nowait(record) jpayne@68: jpayne@68: def prepare(self, record): jpayne@68: """ jpayne@68: Prepares a record for queuing. The object returned by this method is jpayne@68: enqueued. jpayne@68: jpayne@68: The base implementation formats the record to merge the message jpayne@68: and arguments, and removes unpickleable items from the record jpayne@68: in-place. jpayne@68: jpayne@68: You might want to override this method if you want to convert jpayne@68: the record to a dict or JSON string, or send a modified copy jpayne@68: of the record while leaving the original intact. jpayne@68: """ jpayne@68: # The format operation gets traceback text into record.exc_text jpayne@68: # (if there's exception data), and also returns the formatted jpayne@68: # message. We can then use this to replace the original jpayne@68: # msg + args, as these might be unpickleable. We also zap the jpayne@68: # exc_info and exc_text attributes, as they are no longer jpayne@68: # needed and, if not None, will typically not be pickleable. jpayne@68: msg = self.format(record) jpayne@68: # bpo-35726: make copy of record to avoid affecting other handlers in the chain. jpayne@68: record = copy.copy(record) jpayne@68: record.message = msg jpayne@68: record.msg = msg jpayne@68: record.args = None jpayne@68: record.exc_info = None jpayne@68: record.exc_text = None jpayne@68: return record jpayne@68: jpayne@68: def emit(self, record): jpayne@68: """ jpayne@68: Emit a record. jpayne@68: jpayne@68: Writes the LogRecord to the queue, preparing it for pickling first. jpayne@68: """ jpayne@68: try: jpayne@68: self.enqueue(self.prepare(record)) jpayne@68: except Exception: jpayne@68: self.handleError(record) jpayne@68: jpayne@68: jpayne@68: class QueueListener(object): jpayne@68: """ jpayne@68: This class implements an internal threaded listener which watches for jpayne@68: LogRecords being added to a queue, removes them and passes them to a jpayne@68: list of handlers for processing. jpayne@68: """ jpayne@68: _sentinel = None jpayne@68: jpayne@68: def __init__(self, queue, *handlers, respect_handler_level=False): jpayne@68: """ jpayne@68: Initialise an instance with the specified queue and jpayne@68: handlers. jpayne@68: """ jpayne@68: self.queue = queue jpayne@68: self.handlers = handlers jpayne@68: self._thread = None jpayne@68: self.respect_handler_level = respect_handler_level jpayne@68: jpayne@68: def dequeue(self, block): jpayne@68: """ jpayne@68: Dequeue a record and return it, optionally blocking. jpayne@68: jpayne@68: The base implementation uses get. You may want to override this method jpayne@68: if you want to use timeouts or work with custom queue implementations. jpayne@68: """ jpayne@68: return self.queue.get(block) jpayne@68: jpayne@68: def start(self): jpayne@68: """ jpayne@68: Start the listener. jpayne@68: jpayne@68: This starts up a background thread to monitor the queue for jpayne@68: LogRecords to process. jpayne@68: """ jpayne@68: self._thread = t = threading.Thread(target=self._monitor) jpayne@68: t.daemon = True jpayne@68: t.start() jpayne@68: jpayne@68: def prepare(self, record): jpayne@68: """ jpayne@68: Prepare a record for handling. jpayne@68: jpayne@68: This method just returns the passed-in record. You may want to jpayne@68: override this method if you need to do any custom marshalling or jpayne@68: manipulation of the record before passing it to the handlers. jpayne@68: """ jpayne@68: return record jpayne@68: jpayne@68: def handle(self, record): jpayne@68: """ jpayne@68: Handle a record. jpayne@68: jpayne@68: This just loops through the handlers offering them the record jpayne@68: to handle. jpayne@68: """ jpayne@68: record = self.prepare(record) jpayne@68: for handler in self.handlers: jpayne@68: if not self.respect_handler_level: jpayne@68: process = True jpayne@68: else: jpayne@68: process = record.levelno >= handler.level jpayne@68: if process: jpayne@68: handler.handle(record) jpayne@68: jpayne@68: def _monitor(self): jpayne@68: """ jpayne@68: Monitor the queue for records, and ask the handler jpayne@68: to deal with them. jpayne@68: jpayne@68: This method runs on a separate, internal thread. jpayne@68: The thread will terminate if it sees a sentinel object in the queue. jpayne@68: """ jpayne@68: q = self.queue jpayne@68: has_task_done = hasattr(q, 'task_done') jpayne@68: while True: jpayne@68: try: jpayne@68: record = self.dequeue(True) jpayne@68: if record is self._sentinel: jpayne@68: if has_task_done: jpayne@68: q.task_done() jpayne@68: break jpayne@68: self.handle(record) jpayne@68: if has_task_done: jpayne@68: q.task_done() jpayne@68: except queue.Empty: jpayne@68: break jpayne@68: jpayne@68: def enqueue_sentinel(self): jpayne@68: """ jpayne@68: This is used to enqueue the sentinel record. jpayne@68: jpayne@68: The base implementation uses put_nowait. You may want to override this jpayne@68: method if you want to use timeouts or work with custom queue jpayne@68: implementations. jpayne@68: """ jpayne@68: self.queue.put_nowait(self._sentinel) jpayne@68: jpayne@68: def stop(self): jpayne@68: """ jpayne@68: Stop the listener. jpayne@68: jpayne@68: This asks the thread to terminate, and then waits for it to do so. jpayne@68: Note that if you don't call this before your application exits, there jpayne@68: may be some records still left on the queue, which won't be processed. jpayne@68: """ jpayne@68: self.enqueue_sentinel() jpayne@68: self._thread.join() jpayne@68: self._thread = None