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