home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / lib / python2.4 / logging / handlers.pyc (.txt) < prev   
Encoding:
Python Compiled Bytecode  |  2006-08-31  |  31.0 KB  |  1,072 lines

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