+++ /dev/null
-# Copyright 2001-2010 by Vinay Sajip. All Rights Reserved.\r
-#\r
-# Permission to use, copy, modify, and distribute this software and its\r
-# documentation for any purpose and without fee is hereby granted,\r
-# provided that the above copyright notice appear in all copies and that\r
-# both that copyright notice and this permission notice appear in\r
-# supporting documentation, and that the name of Vinay Sajip\r
-# not be used in advertising or publicity pertaining to distribution\r
-# of the software without specific, written prior permission.\r
-# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING\r
-# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL\r
-# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR\r
-# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER\r
-# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT\r
-# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\r
-\r
-"""\r
-Additional handlers for the logging package for Python. The core package is\r
-based on PEP 282 and comments thereto in comp.lang.python, and influenced by\r
-Apache's log4j system.\r
-\r
-Copyright (C) 2001-2010 Vinay Sajip. All Rights Reserved.\r
-\r
-To use, simply 'import logging.handlers' and log away!\r
-"""\r
-\r
-import logging, socket, os, cPickle, struct, time, re\r
-from stat import ST_DEV, ST_INO, ST_MTIME\r
-\r
-try:\r
- import codecs\r
-except ImportError:\r
- codecs = None\r
-try:\r
- unicode\r
- _unicode = True\r
-except NameError:\r
- _unicode = False\r
-\r
-#\r
-# Some constants...\r
-#\r
-\r
-DEFAULT_TCP_LOGGING_PORT = 9020\r
-DEFAULT_UDP_LOGGING_PORT = 9021\r
-DEFAULT_HTTP_LOGGING_PORT = 9022\r
-DEFAULT_SOAP_LOGGING_PORT = 9023\r
-SYSLOG_UDP_PORT = 514\r
-SYSLOG_TCP_PORT = 514\r
-\r
-_MIDNIGHT = 24 * 60 * 60 # number of seconds in a day\r
-\r
-class BaseRotatingHandler(logging.FileHandler):\r
- """\r
- Base class for handlers that rotate log files at a certain point.\r
- Not meant to be instantiated directly. Instead, use RotatingFileHandler\r
- or TimedRotatingFileHandler.\r
- """\r
- def __init__(self, filename, mode, encoding=None, delay=0):\r
- """\r
- Use the specified filename for streamed logging\r
- """\r
- if codecs is None:\r
- encoding = None\r
- logging.FileHandler.__init__(self, filename, mode, encoding, delay)\r
- self.mode = mode\r
- self.encoding = encoding\r
-\r
- def emit(self, record):\r
- """\r
- Emit a record.\r
-\r
- Output the record to the file, catering for rollover as described\r
- in doRollover().\r
- """\r
- try:\r
- if self.shouldRollover(record):\r
- self.doRollover()\r
- logging.FileHandler.emit(self, record)\r
- except (KeyboardInterrupt, SystemExit):\r
- raise\r
- except:\r
- self.handleError(record)\r
-\r
-class RotatingFileHandler(BaseRotatingHandler):\r
- """\r
- Handler for logging to a set of files, which switches from one file\r
- to the next when the current file reaches a certain size.\r
- """\r
- def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0):\r
- """\r
- Open the specified file and use it as the stream for logging.\r
-\r
- By default, the file grows indefinitely. You can specify particular\r
- values of maxBytes and backupCount to allow the file to rollover at\r
- a predetermined size.\r
-\r
- Rollover occurs whenever the current log file is nearly maxBytes in\r
- length. If backupCount is >= 1, the system will successively create\r
- new files with the same pathname as the base file, but with extensions\r
- ".1", ".2" etc. appended to it. For example, with a backupCount of 5\r
- and a base file name of "app.log", you would get "app.log",\r
- "app.log.1", "app.log.2", ... through to "app.log.5". The file being\r
- written to is always "app.log" - when it gets filled up, it is closed\r
- and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc.\r
- exist, then they are renamed to "app.log.2", "app.log.3" etc.\r
- respectively.\r
-\r
- If maxBytes is zero, rollover never occurs.\r
- """\r
- # If rotation/rollover is wanted, it doesn't make sense to use another\r
- # mode. If for example 'w' were specified, then if there were multiple\r
- # runs of the calling application, the logs from previous runs would be\r
- # lost if the 'w' is respected, because the log file would be truncated\r
- # on each run.\r
- if maxBytes > 0:\r
- mode = 'a'\r
- BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)\r
- self.maxBytes = maxBytes\r
- self.backupCount = backupCount\r
-\r
- def doRollover(self):\r
- """\r
- Do a rollover, as described in __init__().\r
- """\r
- if self.stream:\r
- self.stream.close()\r
- self.stream = None\r
- if self.backupCount > 0:\r
- for i in range(self.backupCount - 1, 0, -1):\r
- sfn = "%s.%d" % (self.baseFilename, i)\r
- dfn = "%s.%d" % (self.baseFilename, i + 1)\r
- if os.path.exists(sfn):\r
- #print "%s -> %s" % (sfn, dfn)\r
- if os.path.exists(dfn):\r
- os.remove(dfn)\r
- os.rename(sfn, dfn)\r
- dfn = self.baseFilename + ".1"\r
- if os.path.exists(dfn):\r
- os.remove(dfn)\r
- os.rename(self.baseFilename, dfn)\r
- #print "%s -> %s" % (self.baseFilename, dfn)\r
- self.mode = 'w'\r
- self.stream = self._open()\r
-\r
- def shouldRollover(self, record):\r
- """\r
- Determine if rollover should occur.\r
-\r
- Basically, see if the supplied record would cause the file to exceed\r
- the size limit we have.\r
- """\r
- if self.stream is None: # delay was set...\r
- self.stream = self._open()\r
- if self.maxBytes > 0: # are we rolling over?\r
- msg = "%s\n" % self.format(record)\r
- self.stream.seek(0, 2) #due to non-posix-compliant Windows feature\r
- if self.stream.tell() + len(msg) >= self.maxBytes:\r
- return 1\r
- return 0\r
-\r
-class TimedRotatingFileHandler(BaseRotatingHandler):\r
- """\r
- Handler for logging to a file, rotating the log file at certain timed\r
- intervals.\r
-\r
- If backupCount is > 0, when rollover is done, no more than backupCount\r
- files are kept - the oldest ones are deleted.\r
- """\r
- def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False):\r
- BaseRotatingHandler.__init__(self, filename, 'a', encoding, delay)\r
- self.when = when.upper()\r
- self.backupCount = backupCount\r
- self.utc = utc\r
- # Calculate the real rollover interval, which is just the number of\r
- # seconds between rollovers. Also set the filename suffix used when\r
- # a rollover occurs. Current 'when' events supported:\r
- # S - Seconds\r
- # M - Minutes\r
- # H - Hours\r
- # D - Days\r
- # midnight - roll over at midnight\r
- # W{0-6} - roll over on a certain day; 0 - Monday\r
- #\r
- # Case of the 'when' specifier is not important; lower or upper case\r
- # will work.\r
- if self.when == 'S':\r
- self.interval = 1 # one second\r
- self.suffix = "%Y-%m-%d_%H-%M-%S"\r
- self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$"\r
- elif self.when == 'M':\r
- self.interval = 60 # one minute\r
- self.suffix = "%Y-%m-%d_%H-%M"\r
- self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}$"\r
- elif self.when == 'H':\r
- self.interval = 60 * 60 # one hour\r
- self.suffix = "%Y-%m-%d_%H"\r
- self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}$"\r
- elif self.when == 'D' or self.when == 'MIDNIGHT':\r
- self.interval = 60 * 60 * 24 # one day\r
- self.suffix = "%Y-%m-%d"\r
- self.extMatch = r"^\d{4}-\d{2}-\d{2}$"\r
- elif self.when.startswith('W'):\r
- self.interval = 60 * 60 * 24 * 7 # one week\r
- if len(self.when) != 2:\r
- raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when)\r
- if self.when[1] < '0' or self.when[1] > '6':\r
- raise ValueError("Invalid day specified for weekly rollover: %s" % self.when)\r
- self.dayOfWeek = int(self.when[1])\r
- self.suffix = "%Y-%m-%d"\r
- self.extMatch = r"^\d{4}-\d{2}-\d{2}$"\r
- else:\r
- raise ValueError("Invalid rollover interval specified: %s" % self.when)\r
-\r
- self.extMatch = re.compile(self.extMatch)\r
- self.interval = self.interval * interval # multiply by units requested\r
- if os.path.exists(filename):\r
- t = os.stat(filename)[ST_MTIME]\r
- else:\r
- t = int(time.time())\r
- self.rolloverAt = self.computeRollover(t)\r
-\r
- def computeRollover(self, currentTime):\r
- """\r
- Work out the rollover time based on the specified time.\r
- """\r
- result = currentTime + self.interval\r
- # If we are rolling over at midnight or weekly, then the interval is already known.\r
- # What we need to figure out is WHEN the next interval is. In other words,\r
- # if you are rolling over at midnight, then your base interval is 1 day,\r
- # but you want to start that one day clock at midnight, not now. So, we\r
- # have to fudge the rolloverAt value in order to trigger the first rollover\r
- # at the right time. After that, the regular interval will take care of\r
- # the rest. Note that this code doesn't care about leap seconds. :)\r
- if self.when == 'MIDNIGHT' or self.when.startswith('W'):\r
- # This could be done with less code, but I wanted it to be clear\r
- if self.utc:\r
- t = time.gmtime(currentTime)\r
- else:\r
- t = time.localtime(currentTime)\r
- currentHour = t[3]\r
- currentMinute = t[4]\r
- currentSecond = t[5]\r
- # r is the number of seconds left between now and midnight\r
- r = _MIDNIGHT - ((currentHour * 60 + currentMinute) * 60 +\r
- currentSecond)\r
- result = currentTime + r\r
- # If we are rolling over on a certain day, add in the number of days until\r
- # the next rollover, but offset by 1 since we just calculated the time\r
- # until the next day starts. There are three cases:\r
- # Case 1) The day to rollover is today; in this case, do nothing\r
- # Case 2) The day to rollover is further in the interval (i.e., today is\r
- # day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to\r
- # next rollover is simply 6 - 2 - 1, or 3.\r
- # Case 3) The day to rollover is behind us in the interval (i.e., today\r
- # is day 5 (Saturday) and rollover is on day 3 (Thursday).\r
- # Days to rollover is 6 - 5 + 3, or 4. In this case, it's the\r
- # number of days left in the current week (1) plus the number\r
- # of days in the next week until the rollover day (3).\r
- # The calculations described in 2) and 3) above need to have a day added.\r
- # This is because the above time calculation takes us to midnight on this\r
- # day, i.e. the start of the next day.\r
- if self.when.startswith('W'):\r
- day = t[6] # 0 is Monday\r
- if day != self.dayOfWeek:\r
- if day < self.dayOfWeek:\r
- daysToWait = self.dayOfWeek - day\r
- else:\r
- daysToWait = 6 - day + self.dayOfWeek + 1\r
- newRolloverAt = result + (daysToWait * (60 * 60 * 24))\r
- if not self.utc:\r
- dstNow = t[-1]\r
- dstAtRollover = time.localtime(newRolloverAt)[-1]\r
- if dstNow != dstAtRollover:\r
- if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour\r
- newRolloverAt = newRolloverAt - 3600\r
- else: # DST bows out before next rollover, so we need to add an hour\r
- newRolloverAt = newRolloverAt + 3600\r
- result = newRolloverAt\r
- return result\r
-\r
- def shouldRollover(self, record):\r
- """\r
- Determine if rollover should occur.\r
-\r
- record is not used, as we are just comparing times, but it is needed so\r
- the method signatures are the same\r
- """\r
- t = int(time.time())\r
- if t >= self.rolloverAt:\r
- return 1\r
- #print "No need to rollover: %d, %d" % (t, self.rolloverAt)\r
- return 0\r
-\r
- def getFilesToDelete(self):\r
- """\r
- Determine the files to delete when rolling over.\r
-\r
- More specific than the earlier method, which just used glob.glob().\r
- """\r
- dirName, baseName = os.path.split(self.baseFilename)\r
- fileNames = os.listdir(dirName)\r
- result = []\r
- prefix = baseName + "."\r
- plen = len(prefix)\r
- for fileName in fileNames:\r
- if fileName[:plen] == prefix:\r
- suffix = fileName[plen:]\r
- if self.extMatch.match(suffix):\r
- result.append(os.path.join(dirName, fileName))\r
- result.sort()\r
- if len(result) < self.backupCount:\r
- result = []\r
- else:\r
- result = result[:len(result) - self.backupCount]\r
- return result\r
-\r
- def doRollover(self):\r
- """\r
- do a rollover; in this case, a date/time stamp is appended to the filename\r
- when the rollover happens. However, you want the file to be named for the\r
- start of the interval, not the current time. If there is a backup count,\r
- then we have to get a list of matching filenames, sort them and remove\r
- the one with the oldest suffix.\r
- """\r
- if self.stream:\r
- self.stream.close()\r
- self.stream = None\r
- # get the time that this sequence started at and make it a TimeTuple\r
- t = self.rolloverAt - self.interval\r
- if self.utc:\r
- timeTuple = time.gmtime(t)\r
- else:\r
- timeTuple = time.localtime(t)\r
- dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple)\r
- if os.path.exists(dfn):\r
- os.remove(dfn)\r
- os.rename(self.baseFilename, dfn)\r
- if self.backupCount > 0:\r
- # find the oldest log file and delete it\r
- #s = glob.glob(self.baseFilename + ".20*")\r
- #if len(s) > self.backupCount:\r
- # s.sort()\r
- # os.remove(s[0])\r
- for s in self.getFilesToDelete():\r
- os.remove(s)\r
- #print "%s -> %s" % (self.baseFilename, dfn)\r
- self.mode = 'w'\r
- self.stream = self._open()\r
- currentTime = int(time.time())\r
- newRolloverAt = self.computeRollover(currentTime)\r
- while newRolloverAt <= currentTime:\r
- newRolloverAt = newRolloverAt + self.interval\r
- #If DST changes and midnight or weekly rollover, adjust for this.\r
- if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc:\r
- dstNow = time.localtime(currentTime)[-1]\r
- dstAtRollover = time.localtime(newRolloverAt)[-1]\r
- if dstNow != dstAtRollover:\r
- if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour\r
- newRolloverAt = newRolloverAt - 3600\r
- else: # DST bows out before next rollover, so we need to add an hour\r
- newRolloverAt = newRolloverAt + 3600\r
- self.rolloverAt = newRolloverAt\r
-\r
-class WatchedFileHandler(logging.FileHandler):\r
- """\r
- A handler for logging to a file, which watches the file\r
- to see if it has changed while in use. This can happen because of\r
- usage of programs such as newsyslog and logrotate which perform\r
- log file rotation. This handler, intended for use under Unix,\r
- watches the file to see if it has changed since the last emit.\r
- (A file has changed if its device or inode have changed.)\r
- If it has changed, the old file stream is closed, and the file\r
- opened to get a new stream.\r
-\r
- This handler is not appropriate for use under Windows, because\r
- under Windows open files cannot be moved or renamed - logging\r
- opens the files with exclusive locks - and so there is no need\r
- for such a handler. Furthermore, ST_INO is not supported under\r
- Windows; stat always returns zero for this value.\r
-\r
- This handler is based on a suggestion and patch by Chad J.\r
- Schroeder.\r
- """\r
- def __init__(self, filename, mode='a', encoding=None, delay=0):\r
- logging.FileHandler.__init__(self, filename, mode, encoding, delay)\r
- if not os.path.exists(self.baseFilename):\r
- self.dev, self.ino = -1, -1\r
- else:\r
- stat = os.stat(self.baseFilename)\r
- self.dev, self.ino = stat[ST_DEV], stat[ST_INO]\r
-\r
- def emit(self, record):\r
- """\r
- Emit a record.\r
-\r
- First check if the underlying file has changed, and if it\r
- has, close the old stream and reopen the file to get the\r
- current stream.\r
- """\r
- if not os.path.exists(self.baseFilename):\r
- stat = None\r
- changed = 1\r
- else:\r
- stat = os.stat(self.baseFilename)\r
- changed = (stat[ST_DEV] != self.dev) or (stat[ST_INO] != self.ino)\r
- if changed and self.stream is not None:\r
- self.stream.flush()\r
- self.stream.close()\r
- self.stream = self._open()\r
- if stat is None:\r
- stat = os.stat(self.baseFilename)\r
- self.dev, self.ino = stat[ST_DEV], stat[ST_INO]\r
- logging.FileHandler.emit(self, record)\r
-\r
-class SocketHandler(logging.Handler):\r
- """\r
- A handler class which writes logging records, in pickle format, to\r
- a streaming socket. The socket is kept open across logging calls.\r
- If the peer resets it, an attempt is made to reconnect on the next call.\r
- The pickle which is sent is that of the LogRecord's attribute dictionary\r
- (__dict__), so that the receiver does not need to have the logging module\r
- installed in order to process the logging event.\r
-\r
- To unpickle the record at the receiving end into a LogRecord, use the\r
- makeLogRecord function.\r
- """\r
-\r
- def __init__(self, host, port):\r
- """\r
- Initializes the handler with a specific host address and port.\r
-\r
- The attribute 'closeOnError' is set to 1 - which means that if\r
- a socket error occurs, the socket is silently closed and then\r
- reopened on the next logging call.\r
- """\r
- logging.Handler.__init__(self)\r
- self.host = host\r
- self.port = port\r
- self.sock = None\r
- self.closeOnError = 0\r
- self.retryTime = None\r
- #\r
- # Exponential backoff parameters.\r
- #\r
- self.retryStart = 1.0\r
- self.retryMax = 30.0\r
- self.retryFactor = 2.0\r
-\r
- def makeSocket(self, timeout=1):\r
- """\r
- A factory method which allows subclasses to define the precise\r
- type of socket they want.\r
- """\r
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r
- if hasattr(s, 'settimeout'):\r
- s.settimeout(timeout)\r
- s.connect((self.host, self.port))\r
- return s\r
-\r
- def createSocket(self):\r
- """\r
- Try to create a socket, using an exponential backoff with\r
- a max retry time. Thanks to Robert Olson for the original patch\r
- (SF #815911) which has been slightly refactored.\r
- """\r
- now = time.time()\r
- # Either retryTime is None, in which case this\r
- # is the first time back after a disconnect, or\r
- # we've waited long enough.\r
- if self.retryTime is None:\r
- attempt = 1\r
- else:\r
- attempt = (now >= self.retryTime)\r
- if attempt:\r
- try:\r
- self.sock = self.makeSocket()\r
- self.retryTime = None # next time, no delay before trying\r
- except socket.error:\r
- #Creation failed, so set the retry time and return.\r
- if self.retryTime is None:\r
- self.retryPeriod = self.retryStart\r
- else:\r
- self.retryPeriod = self.retryPeriod * self.retryFactor\r
- if self.retryPeriod > self.retryMax:\r
- self.retryPeriod = self.retryMax\r
- self.retryTime = now + self.retryPeriod\r
-\r
- def send(self, s):\r
- """\r
- Send a pickled string to the socket.\r
-\r
- This function allows for partial sends which can happen when the\r
- network is busy.\r
- """\r
- if self.sock is None:\r
- self.createSocket()\r
- #self.sock can be None either because we haven't reached the retry\r
- #time yet, or because we have reached the retry time and retried,\r
- #but are still unable to connect.\r
- if self.sock:\r
- try:\r
- if hasattr(self.sock, "sendall"):\r
- self.sock.sendall(s)\r
- else:\r
- sentsofar = 0\r
- left = len(s)\r
- while left > 0:\r
- sent = self.sock.send(s[sentsofar:])\r
- sentsofar = sentsofar + sent\r
- left = left - sent\r
- except socket.error:\r
- self.sock.close()\r
- self.sock = None # so we can call createSocket next time\r
-\r
- def makePickle(self, record):\r
- """\r
- Pickles the record in binary format with a length prefix, and\r
- returns it ready for transmission across the socket.\r
- """\r
- ei = record.exc_info\r
- if ei:\r
- dummy = self.format(record) # just to get traceback text into record.exc_text\r
- record.exc_info = None # to avoid Unpickleable error\r
- s = cPickle.dumps(record.__dict__, 1)\r
- if ei:\r
- record.exc_info = ei # for next handler\r
- slen = struct.pack(">L", len(s))\r
- return slen + s\r
-\r
- def handleError(self, record):\r
- """\r
- Handle an error during logging.\r
-\r
- An error has occurred during logging. Most likely cause -\r
- connection lost. Close the socket so that we can retry on the\r
- next event.\r
- """\r
- if self.closeOnError and self.sock:\r
- self.sock.close()\r
- self.sock = None #try to reconnect next time\r
- else:\r
- logging.Handler.handleError(self, record)\r
-\r
- def emit(self, record):\r
- """\r
- Emit a record.\r
-\r
- Pickles the record and writes it to the socket in binary format.\r
- If there is an error with the socket, silently drop the packet.\r
- If there was a problem with the socket, re-establishes the\r
- socket.\r
- """\r
- try:\r
- s = self.makePickle(record)\r
- self.send(s)\r
- except (KeyboardInterrupt, SystemExit):\r
- raise\r
- except:\r
- self.handleError(record)\r
-\r
- def close(self):\r
- """\r
- Closes the socket.\r
- """\r
- if self.sock:\r
- self.sock.close()\r
- self.sock = None\r
- logging.Handler.close(self)\r
-\r
-class DatagramHandler(SocketHandler):\r
- """\r
- A handler class which writes logging records, in pickle format, to\r
- a datagram socket. The pickle which is sent is that of the LogRecord's\r
- attribute dictionary (__dict__), so that the receiver does not need to\r
- have the logging module installed in order to process the logging event.\r
-\r
- To unpickle the record at the receiving end into a LogRecord, use the\r
- makeLogRecord function.\r
-\r
- """\r
- def __init__(self, host, port):\r
- """\r
- Initializes the handler with a specific host address and port.\r
- """\r
- SocketHandler.__init__(self, host, port)\r
- self.closeOnError = 0\r
-\r
- def makeSocket(self):\r
- """\r
- The factory method of SocketHandler is here overridden to create\r
- a UDP socket (SOCK_DGRAM).\r
- """\r
- s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r
- return s\r
-\r
- def send(self, s):\r
- """\r
- Send a pickled string to a socket.\r
-\r
- This function no longer allows for partial sends which can happen\r
- when the network is busy - UDP does not guarantee delivery and\r
- can deliver packets out of sequence.\r
- """\r
- if self.sock is None:\r
- self.createSocket()\r
- self.sock.sendto(s, (self.host, self.port))\r
-\r
-class SysLogHandler(logging.Handler):\r
- """\r
- A handler class which sends formatted logging records to a syslog\r
- server. Based on Sam Rushing's syslog module:\r
- http://www.nightmare.com/squirl/python-ext/misc/syslog.py\r
- Contributed by Nicolas Untz (after which minor refactoring changes\r
- have been made).\r
- """\r
-\r
- # from <linux/sys/syslog.h>:\r
- # ======================================================================\r
- # priorities/facilities are encoded into a single 32-bit quantity, where\r
- # the bottom 3 bits are the priority (0-7) and the top 28 bits are the\r
- # facility (0-big number). Both the priorities and the facilities map\r
- # roughly one-to-one to strings in the syslogd(8) source code. This\r
- # mapping is included in this file.\r
- #\r
- # priorities (these are ordered)\r
-\r
- LOG_EMERG = 0 # system is unusable\r
- LOG_ALERT = 1 # action must be taken immediately\r
- LOG_CRIT = 2 # critical conditions\r
- LOG_ERR = 3 # error conditions\r
- LOG_WARNING = 4 # warning conditions\r
- LOG_NOTICE = 5 # normal but significant condition\r
- LOG_INFO = 6 # informational\r
- LOG_DEBUG = 7 # debug-level messages\r
-\r
- # facility codes\r
- LOG_KERN = 0 # kernel messages\r
- LOG_USER = 1 # random user-level messages\r
- LOG_MAIL = 2 # mail system\r
- LOG_DAEMON = 3 # system daemons\r
- LOG_AUTH = 4 # security/authorization messages\r
- LOG_SYSLOG = 5 # messages generated internally by syslogd\r
- LOG_LPR = 6 # line printer subsystem\r
- LOG_NEWS = 7 # network news subsystem\r
- LOG_UUCP = 8 # UUCP subsystem\r
- LOG_CRON = 9 # clock daemon\r
- LOG_AUTHPRIV = 10 # security/authorization messages (private)\r
- LOG_FTP = 11 # FTP daemon\r
-\r
- # other codes through 15 reserved for system use\r
- LOG_LOCAL0 = 16 # reserved for local use\r
- LOG_LOCAL1 = 17 # reserved for local use\r
- LOG_LOCAL2 = 18 # reserved for local use\r
- LOG_LOCAL3 = 19 # reserved for local use\r
- LOG_LOCAL4 = 20 # reserved for local use\r
- LOG_LOCAL5 = 21 # reserved for local use\r
- LOG_LOCAL6 = 22 # reserved for local use\r
- LOG_LOCAL7 = 23 # reserved for local use\r
-\r
- priority_names = {\r
- "alert": LOG_ALERT,\r
- "crit": LOG_CRIT,\r
- "critical": LOG_CRIT,\r
- "debug": LOG_DEBUG,\r
- "emerg": LOG_EMERG,\r
- "err": LOG_ERR,\r
- "error": LOG_ERR, # DEPRECATED\r
- "info": LOG_INFO,\r
- "notice": LOG_NOTICE,\r
- "panic": LOG_EMERG, # DEPRECATED\r
- "warn": LOG_WARNING, # DEPRECATED\r
- "warning": LOG_WARNING,\r
- }\r
-\r
- facility_names = {\r
- "auth": LOG_AUTH,\r
- "authpriv": LOG_AUTHPRIV,\r
- "cron": LOG_CRON,\r
- "daemon": LOG_DAEMON,\r
- "ftp": LOG_FTP,\r
- "kern": LOG_KERN,\r
- "lpr": LOG_LPR,\r
- "mail": LOG_MAIL,\r
- "news": LOG_NEWS,\r
- "security": LOG_AUTH, # DEPRECATED\r
- "syslog": LOG_SYSLOG,\r
- "user": LOG_USER,\r
- "uucp": LOG_UUCP,\r
- "local0": LOG_LOCAL0,\r
- "local1": LOG_LOCAL1,\r
- "local2": LOG_LOCAL2,\r
- "local3": LOG_LOCAL3,\r
- "local4": LOG_LOCAL4,\r
- "local5": LOG_LOCAL5,\r
- "local6": LOG_LOCAL6,\r
- "local7": LOG_LOCAL7,\r
- }\r
-\r
- #The map below appears to be trivially lowercasing the key. However,\r
- #there's more to it than meets the eye - in some locales, lowercasing\r
- #gives unexpected results. See SF #1524081: in the Turkish locale,\r
- #"INFO".lower() != "info"\r
- priority_map = {\r
- "DEBUG" : "debug",\r
- "INFO" : "info",\r
- "WARNING" : "warning",\r
- "ERROR" : "error",\r
- "CRITICAL" : "critical"\r
- }\r
-\r
- def __init__(self, address=('localhost', SYSLOG_UDP_PORT),\r
- facility=LOG_USER, socktype=socket.SOCK_DGRAM):\r
- """\r
- Initialize a handler.\r
-\r
- If address is specified as a string, a UNIX socket is used. To log to a\r
- local syslogd, "SysLogHandler(address="/dev/log")" can be used.\r
- If facility is not specified, LOG_USER is used.\r
- """\r
- logging.Handler.__init__(self)\r
-\r
- self.address = address\r
- self.facility = facility\r
- self.socktype = socktype\r
-\r
- if isinstance(address, basestring):\r
- self.unixsocket = 1\r
- self._connect_unixsocket(address)\r
- else:\r
- self.unixsocket = 0\r
- self.socket = socket.socket(socket.AF_INET, socktype)\r
- if socktype == socket.SOCK_STREAM:\r
- self.socket.connect(address)\r
- self.formatter = None\r
-\r
- def _connect_unixsocket(self, address):\r
- self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)\r
- # syslog may require either DGRAM or STREAM sockets\r
- try:\r
- self.socket.connect(address)\r
- except socket.error:\r
- self.socket.close()\r
- self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\r
- self.socket.connect(address)\r
-\r
- # curious: when talking to the unix-domain '/dev/log' socket, a\r
- # zero-terminator seems to be required. this string is placed\r
- # into a class variable so that it can be overridden if\r
- # necessary.\r
- log_format_string = '<%d>%s\000'\r
-\r
- def encodePriority(self, facility, priority):\r
- """\r
- Encode the facility and priority. You can pass in strings or\r
- integers - if strings are passed, the facility_names and\r
- priority_names mapping dictionaries are used to convert them to\r
- integers.\r
- """\r
- if isinstance(facility, basestring):\r
- facility = self.facility_names[facility]\r
- if isinstance(priority, basestring):\r
- priority = self.priority_names[priority]\r
- return (facility << 3) | priority\r
-\r
- def close (self):\r
- """\r
- Closes the socket.\r
- """\r
- if self.unixsocket:\r
- self.socket.close()\r
- logging.Handler.close(self)\r
-\r
- def mapPriority(self, levelName):\r
- """\r
- Map a logging level name to a key in the priority_names map.\r
- This is useful in two scenarios: when custom levels are being\r
- used, and in the case where you can't do a straightforward\r
- mapping by lowercasing the logging level name because of locale-\r
- specific issues (see SF #1524081).\r
- """\r
- return self.priority_map.get(levelName, "warning")\r
-\r
- def emit(self, record):\r
- """\r
- Emit a record.\r
-\r
- The record is formatted, and then sent to the syslog server. If\r
- exception information is present, it is NOT sent to the server.\r
- """\r
- msg = self.format(record) + '\000'\r
- """\r
- We need to convert record level to lowercase, maybe this will\r
- change in the future.\r
- """\r
- prio = '<%d>' % self.encodePriority(self.facility,\r
- self.mapPriority(record.levelname))\r
- # Message is a string. Convert to bytes as required by RFC 5424\r
- if type(msg) is unicode:\r
- msg = msg.encode('utf-8')\r
- if codecs:\r
- msg = codecs.BOM_UTF8 + msg\r
- msg = prio + msg\r
- try:\r
- if self.unixsocket:\r
- try:\r
- self.socket.send(msg)\r
- except socket.error:\r
- self._connect_unixsocket(self.address)\r
- self.socket.send(msg)\r
- elif self.socktype == socket.SOCK_DGRAM:\r
- self.socket.sendto(msg, self.address)\r
- else:\r
- self.socket.sendall(msg)\r
- except (KeyboardInterrupt, SystemExit):\r
- raise\r
- except:\r
- self.handleError(record)\r
-\r
-class SMTPHandler(logging.Handler):\r
- """\r
- A handler class which sends an SMTP email for each logging event.\r
- """\r
- def __init__(self, mailhost, fromaddr, toaddrs, subject,\r
- credentials=None, secure=None):\r
- """\r
- Initialize the handler.\r
-\r
- Initialize the instance with the from and to addresses and subject\r
- line of the email. To specify a non-standard SMTP port, use the\r
- (host, port) tuple format for the mailhost argument. To specify\r
- authentication credentials, supply a (username, password) tuple\r
- for the credentials argument. To specify the use of a secure\r
- protocol (TLS), pass in a tuple for the secure argument. This will\r
- only be used when authentication credentials are supplied. The tuple\r
- will be either an empty tuple, or a single-value tuple with the name\r
- of a keyfile, or a 2-value tuple with the names of the keyfile and\r
- certificate file. (This tuple is passed to the `starttls` method).\r
- """\r
- logging.Handler.__init__(self)\r
- if isinstance(mailhost, tuple):\r
- self.mailhost, self.mailport = mailhost\r
- else:\r
- self.mailhost, self.mailport = mailhost, None\r
- if isinstance(credentials, tuple):\r
- self.username, self.password = credentials\r
- else:\r
- self.username = None\r
- self.fromaddr = fromaddr\r
- if isinstance(toaddrs, basestring):\r
- toaddrs = [toaddrs]\r
- self.toaddrs = toaddrs\r
- self.subject = subject\r
- self.secure = secure\r
-\r
- def getSubject(self, record):\r
- """\r
- Determine the subject for the email.\r
-\r
- If you want to specify a subject line which is record-dependent,\r
- override this method.\r
- """\r
- return self.subject\r
-\r
- def emit(self, record):\r
- """\r
- Emit a record.\r
-\r
- Format the record and send it to the specified addressees.\r
- """\r
- try:\r
- import smtplib\r
- from email.utils import formatdate\r
- port = self.mailport\r
- if not port:\r
- port = smtplib.SMTP_PORT\r
- smtp = smtplib.SMTP(self.mailhost, port)\r
- msg = self.format(record)\r
- msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (\r
- self.fromaddr,\r
- ",".join(self.toaddrs),\r
- self.getSubject(record),\r
- formatdate(), msg)\r
- if self.username:\r
- if self.secure is not None:\r
- smtp.ehlo()\r
- smtp.starttls(*self.secure)\r
- smtp.ehlo()\r
- smtp.login(self.username, self.password)\r
- smtp.sendmail(self.fromaddr, self.toaddrs, msg)\r
- smtp.quit()\r
- except (KeyboardInterrupt, SystemExit):\r
- raise\r
- except:\r
- self.handleError(record)\r
-\r
-class NTEventLogHandler(logging.Handler):\r
- """\r
- A handler class which sends events to the NT Event Log. Adds a\r
- registry entry for the specified application name. If no dllname is\r
- provided, win32service.pyd (which contains some basic message\r
- placeholders) is used. Note that use of these placeholders will make\r
- your event logs big, as the entire message source is held in the log.\r
- If you want slimmer logs, you have to pass in the name of your own DLL\r
- which contains the message definitions you want to use in the event log.\r
- """\r
- def __init__(self, appname, dllname=None, logtype="Application"):\r
- logging.Handler.__init__(self)\r
- try:\r
- import win32evtlogutil, win32evtlog\r
- self.appname = appname\r
- self._welu = win32evtlogutil\r
- if not dllname:\r
- dllname = os.path.split(self._welu.__file__)\r
- dllname = os.path.split(dllname[0])\r
- dllname = os.path.join(dllname[0], r'win32service.pyd')\r
- self.dllname = dllname\r
- self.logtype = logtype\r
- self._welu.AddSourceToRegistry(appname, dllname, logtype)\r
- self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE\r
- self.typemap = {\r
- logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE,\r
- logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE,\r
- logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE,\r
- logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE,\r
- logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE,\r
- }\r
- except ImportError:\r
- print("The Python Win32 extensions for NT (service, event "\\r
- "logging) appear not to be available.")\r
- self._welu = None\r
-\r
- def getMessageID(self, record):\r
- """\r
- Return the message ID for the event record. If you are using your\r
- own messages, you could do this by having the msg passed to the\r
- logger being an ID rather than a formatting string. Then, in here,\r
- you could use a dictionary lookup to get the message ID. This\r
- version returns 1, which is the base message ID in win32service.pyd.\r
- """\r
- return 1\r
-\r
- def getEventCategory(self, record):\r
- """\r
- Return the event category for the record.\r
-\r
- Override this if you want to specify your own categories. This version\r
- returns 0.\r
- """\r
- return 0\r
-\r
- def getEventType(self, record):\r
- """\r
- Return the event type for the record.\r
-\r
- Override this if you want to specify your own types. This version does\r
- a mapping using the handler's typemap attribute, which is set up in\r
- __init__() to a dictionary which contains mappings for DEBUG, INFO,\r
- WARNING, ERROR and CRITICAL. If you are using your own levels you will\r
- either need to override this method or place a suitable dictionary in\r
- the handler's typemap attribute.\r
- """\r
- return self.typemap.get(record.levelno, self.deftype)\r
-\r
- def emit(self, record):\r
- """\r
- Emit a record.\r
-\r
- Determine the message ID, event category and event type. Then\r
- log the message in the NT event log.\r
- """\r
- if self._welu:\r
- try:\r
- id = self.getMessageID(record)\r
- cat = self.getEventCategory(record)\r
- type = self.getEventType(record)\r
- msg = self.format(record)\r
- self._welu.ReportEvent(self.appname, id, cat, type, [msg])\r
- except (KeyboardInterrupt, SystemExit):\r
- raise\r
- except:\r
- self.handleError(record)\r
-\r
- def close(self):\r
- """\r
- Clean up this handler.\r
-\r
- You can remove the application name from the registry as a\r
- source of event log entries. However, if you do this, you will\r
- not be able to see the events as you intended in the Event Log\r
- Viewer - it needs to be able to access the registry to get the\r
- DLL name.\r
- """\r
- #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype)\r
- logging.Handler.close(self)\r
-\r
-class HTTPHandler(logging.Handler):\r
- """\r
- A class which sends records to a Web server, using either GET or\r
- POST semantics.\r
- """\r
- def __init__(self, host, url, method="GET"):\r
- """\r
- Initialize the instance with the host, the request URL, and the method\r
- ("GET" or "POST")\r
- """\r
- logging.Handler.__init__(self)\r
- method = method.upper()\r
- if method not in ["GET", "POST"]:\r
- raise ValueError("method must be GET or POST")\r
- self.host = host\r
- self.url = url\r
- self.method = method\r
-\r
- def mapLogRecord(self, record):\r
- """\r
- Default implementation of mapping the log record into a dict\r
- that is sent as the CGI data. Overwrite in your class.\r
- Contributed by Franz Glasner.\r
- """\r
- return record.__dict__\r
-\r
- def emit(self, record):\r
- """\r
- Emit a record.\r
-\r
- Send the record to the Web server as a percent-encoded dictionary\r
- """\r
- try:\r
- import httplib, urllib\r
- host = self.host\r
- h = httplib.HTTP(host)\r
- url = self.url\r
- data = urllib.urlencode(self.mapLogRecord(record))\r
- if self.method == "GET":\r
- if (url.find('?') >= 0):\r
- sep = '&'\r
- else:\r
- sep = '?'\r
- url = url + "%c%s" % (sep, data)\r
- h.putrequest(self.method, url)\r
- # support multiple hosts on one IP address...\r
- # need to strip optional :port from host, if present\r
- i = host.find(":")\r
- if i >= 0:\r
- host = host[:i]\r
- h.putheader("Host", host)\r
- if self.method == "POST":\r
- h.putheader("Content-type",\r
- "application/x-www-form-urlencoded")\r
- h.putheader("Content-length", str(len(data)))\r
- h.endheaders(data if self.method == "POST" else None)\r
- h.getreply() #can't do anything with the result\r
- except (KeyboardInterrupt, SystemExit):\r
- raise\r
- except:\r
- self.handleError(record)\r
-\r
-class BufferingHandler(logging.Handler):\r
- """\r
- A handler class which buffers logging records in memory. Whenever each\r
- record is added to the buffer, a check is made to see if the buffer should\r
- be flushed. If it should, then flush() is expected to do what's needed.\r
- """\r
- def __init__(self, capacity):\r
- """\r
- Initialize the handler with the buffer size.\r
- """\r
- logging.Handler.__init__(self)\r
- self.capacity = capacity\r
- self.buffer = []\r
-\r
- def shouldFlush(self, record):\r
- """\r
- Should the handler flush its buffer?\r
-\r
- Returns true if the buffer is up to capacity. This method can be\r
- overridden to implement custom flushing strategies.\r
- """\r
- return (len(self.buffer) >= self.capacity)\r
-\r
- def emit(self, record):\r
- """\r
- Emit a record.\r
-\r
- Append the record. If shouldFlush() tells us to, call flush() to process\r
- the buffer.\r
- """\r
- self.buffer.append(record)\r
- if self.shouldFlush(record):\r
- self.flush()\r
-\r
- def flush(self):\r
- """\r
- Override to implement custom flushing behaviour.\r
-\r
- This version just zaps the buffer to empty.\r
- """\r
- self.buffer = []\r
-\r
- def close(self):\r
- """\r
- Close the handler.\r
-\r
- This version just flushes and chains to the parent class' close().\r
- """\r
- self.flush()\r
- logging.Handler.close(self)\r
-\r
-class MemoryHandler(BufferingHandler):\r
- """\r
- A handler class which buffers logging records in memory, periodically\r
- flushing them to a target handler. Flushing occurs whenever the buffer\r
- is full, or when an event of a certain severity or greater is seen.\r
- """\r
- def __init__(self, capacity, flushLevel=logging.ERROR, target=None):\r
- """\r
- Initialize the handler with the buffer size, the level at which\r
- flushing should occur and an optional target.\r
-\r
- Note that without a target being set either here or via setTarget(),\r
- a MemoryHandler is no use to anyone!\r
- """\r
- BufferingHandler.__init__(self, capacity)\r
- self.flushLevel = flushLevel\r
- self.target = target\r
-\r
- def shouldFlush(self, record):\r
- """\r
- Check for buffer full or a record at the flushLevel or higher.\r
- """\r
- return (len(self.buffer) >= self.capacity) or \\r
- (record.levelno >= self.flushLevel)\r
-\r
- def setTarget(self, target):\r
- """\r
- Set the target handler for this handler.\r
- """\r
- self.target = target\r
-\r
- def flush(self):\r
- """\r
- For a MemoryHandler, flushing means just sending the buffered\r
- records to the target, if there is one. Override if you want\r
- different behaviour.\r
- """\r
- if self.target:\r
- for record in self.buffer:\r
- self.target.handle(record)\r
- self.buffer = []\r
-\r
- def close(self):\r
- """\r
- Flush, set the target to None and lose the buffer.\r
- """\r
- self.flush()\r
- self.target = None\r
- BufferingHandler.close(self)\r