home *** CD-ROM | disk | FTP | other *** search
/ Mundo do CD-ROM 118 / cdrom118.iso / internet / webaroo / WebarooSetup.exe / Webaroo.msi / _A0DEB44B94924E89917E71AA90C5F226 / logging / __init__.pyc (.txt) next >
Encoding:
Python Compiled Bytecode  |  2005-12-23  |  41.4 KB  |  1,353 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.4)
  3.  
  4. """
  5. Logging package for Python. Based on PEP 282 and comments thereto in
  6. comp.lang.python, and influenced by Apache's log4j system.
  7.  
  8. Should work under Python versions >= 1.5.2, except that source line
  9. information is not available unless 'sys._getframe()' is.
  10.  
  11. Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved.
  12.  
  13. To use, simply 'import logging' and log away!
  14. """
  15. import sys
  16. import os
  17. import types
  18. import time
  19. import string
  20. import cStringIO
  21.  
  22. try:
  23.     import thread
  24.     import threading
  25. except ImportError:
  26.     thread = None
  27.  
  28. __author__ = 'Vinay Sajip <vinay_sajip@red-dove.com>'
  29. __status__ = 'beta'
  30. __version__ = '0.4.9.6'
  31. __date__ = '20 October 2004'
  32. if string.lower(__file__[-4:]) in [
  33.     '.pyc',
  34.     '.pyo']:
  35.     _srcfile = __file__[:-4] + '.py'
  36. else:
  37.     _srcfile = __file__
  38. _srcfile = os.path.normcase(_srcfile)
  39. if not hasattr(sys, '_getframe'):
  40.     _srcfile = None
  41.  
  42. _startTime = time.time()
  43. raiseExceptions = 1
  44. CRITICAL = 50
  45. FATAL = CRITICAL
  46. ERROR = 40
  47. WARNING = 30
  48. WARN = WARNING
  49. INFO = 20
  50. DEBUG = 10
  51. NOTSET = 0
  52. _levelNames = {
  53.     CRITICAL: 'CRITICAL',
  54.     ERROR: 'ERROR',
  55.     WARNING: 'WARNING',
  56.     INFO: 'INFO',
  57.     DEBUG: 'DEBUG',
  58.     NOTSET: 'NOTSET',
  59.     'CRITICAL': CRITICAL,
  60.     'ERROR': ERROR,
  61.     'WARN': WARNING,
  62.     'WARNING': WARNING,
  63.     'INFO': INFO,
  64.     'DEBUG': DEBUG,
  65.     'NOTSET': NOTSET }
  66.  
  67. def getLevelName(level):
  68.     '''
  69.     Return the textual representation of logging level \'level\'.
  70.  
  71.     If the level is one of the predefined levels (CRITICAL, ERROR, WARNING,
  72.     INFO, DEBUG) then you get the corresponding string. If you have
  73.     associated levels with names using addLevelName then the name you have
  74.     associated with \'level\' is returned.
  75.  
  76.     If a numeric value corresponding to one of the defined levels is passed
  77.     in, the corresponding string representation is returned.
  78.  
  79.     Otherwise, the string "Level %s" % level is returned.
  80.     '''
  81.     return _levelNames.get(level, 'Level %s' % level)
  82.  
  83.  
  84. def addLevelName(level, levelName):
  85.     """
  86.     Associate 'levelName' with 'level'.
  87.  
  88.     This is used when converting levels to text during message formatting.
  89.     """
  90.     _acquireLock()
  91.     
  92.     try:
  93.         _levelNames[level] = levelName
  94.         _levelNames[levelName] = level
  95.     finally:
  96.         _releaseLock()
  97.  
  98.  
  99. _lock = None
  100.  
  101. def _acquireLock():
  102.     '''
  103.     Acquire the module-level lock for serializing access to shared data.
  104.  
  105.     This should be released with _releaseLock().
  106.     '''
  107.     global _lock
  108.     if not _lock and thread:
  109.         _lock = threading.RLock()
  110.     
  111.     if _lock:
  112.         _lock.acquire()
  113.     
  114.  
  115.  
  116. def _releaseLock():
  117.     '''
  118.     Release the module-level lock acquired by calling _acquireLock().
  119.     '''
  120.     if _lock:
  121.         _lock.release()
  122.     
  123.  
  124.  
  125. class LogRecord:
  126.     '''
  127.     A LogRecord instance represents an event being logged.
  128.  
  129.     LogRecord instances are created every time something is logged. They
  130.     contain all the information pertinent to the event being logged. The
  131.     main information passed in is in msg and args, which are combined
  132.     using str(msg) % args to create the message field of the record. The
  133.     record also includes information such as when the record was created,
  134.     the source line where the logging call was made, and any exception
  135.     information to be logged.
  136.     '''
  137.     
  138.     def __init__(self, name, level, pathname, lineno, msg, args, exc_info):
  139.         '''
  140.         Initialize a logging record with interesting information.
  141.         '''
  142.         ct = time.time()
  143.         self.name = name
  144.         self.msg = msg
  145.         if args and len(args) == 1 and args[0] and type(args[0]) == types.DictType:
  146.             args = args[0]
  147.         
  148.         self.args = args
  149.         self.levelname = getLevelName(level)
  150.         self.levelno = level
  151.         self.pathname = pathname
  152.         
  153.         try:
  154.             self.filename = os.path.basename(pathname)
  155.             self.module = os.path.splitext(self.filename)[0]
  156.         except:
  157.             self.filename = pathname
  158.             self.module = 'Unknown module'
  159.  
  160.         self.exc_info = exc_info
  161.         self.exc_text = None
  162.         self.lineno = lineno
  163.         self.created = ct
  164.         self.msecs = (ct - long(ct)) * 1000
  165.         self.relativeCreated = (self.created - _startTime) * 1000
  166.         if thread:
  167.             self.thread = thread.get_ident()
  168.         else:
  169.             self.thread = None
  170.         if hasattr(os, 'getpid'):
  171.             self.process = os.getpid()
  172.         else:
  173.             self.process = None
  174.  
  175.     
  176.     def __str__(self):
  177.         return '<LogRecord: %s, %s, %s, %s, "%s">' % (self.name, self.levelno, self.pathname, self.lineno, self.msg)
  178.  
  179.     
  180.     def getMessage(self):
  181.         '''
  182.         Return the message for this LogRecord.
  183.  
  184.         Return the message for this LogRecord after merging any user-supplied
  185.         arguments with the message.
  186.         '''
  187.         if not hasattr(types, 'UnicodeType'):
  188.             msg = str(self.msg)
  189.         else:
  190.             
  191.             try:
  192.                 msg = str(self.msg)
  193.             except UnicodeError:
  194.                 msg = self.msg
  195.  
  196.         if self.args:
  197.             msg = msg % self.args
  198.         
  199.         return msg
  200.  
  201.  
  202.  
  203. def makeLogRecord(dict):
  204.     '''
  205.     Make a LogRecord whose attributes are defined by the specified dictionary,
  206.     This function is useful for converting a logging event received over
  207.     a socket connection (which is sent as a dictionary) into a LogRecord
  208.     instance.
  209.     '''
  210.     rv = LogRecord(None, None, '', 0, '', (), None)
  211.     rv.__dict__.update(dict)
  212.     return rv
  213.  
  214.  
  215. class Formatter:
  216.     '''
  217.     Formatter instances are used to convert a LogRecord to text.
  218.  
  219.     Formatters need to know how a LogRecord is constructed. They are
  220.     responsible for converting a LogRecord to (usually) a string which can
  221.     be interpreted by either a human or an external system. The base Formatter
  222.     allows a formatting string to be specified. If none is supplied, the
  223.     default value of "%s(message)\\n" is used.
  224.  
  225.     The Formatter can be initialized with a format string which makes use of
  226.     knowledge of the LogRecord attributes - e.g. the default value mentioned
  227.     above makes use of the fact that the user\'s message and arguments are pre-
  228.     formatted into a LogRecord\'s message attribute. Currently, the useful
  229.     attributes in a LogRecord are described by:
  230.  
  231.     %(name)s            Name of the logger (logging channel)
  232.     %(levelno)s         Numeric logging level for the message (DEBUG, INFO,
  233.                         WARNING, ERROR, CRITICAL)
  234.     %(levelname)s       Text logging level for the message ("DEBUG", "INFO",
  235.                         "WARNING", "ERROR", "CRITICAL")
  236.     %(pathname)s        Full pathname of the source file where the logging
  237.                         call was issued (if available)
  238.     %(filename)s        Filename portion of pathname
  239.     %(module)s          Module (name portion of filename)
  240.     %(lineno)d          Source line number where the logging call was issued
  241.                         (if available)
  242.     %(created)f         Time when the LogRecord was created (time.time()
  243.                         return value)
  244.     %(asctime)s         Textual time when the LogRecord was created
  245.     %(msecs)d           Millisecond portion of the creation time
  246.     %(relativeCreated)d Time in milliseconds when the LogRecord was created,
  247.                         relative to the time the logging module was loaded
  248.                         (typically at application startup time)
  249.     %(thread)d          Thread ID (if available)
  250.     %(process)d         Process ID (if available)
  251.     %(message)s         The result of record.getMessage(), computed just as
  252.                         the record is emitted
  253.     '''
  254.     converter = time.localtime
  255.     
  256.     def __init__(self, fmt = None, datefmt = None):
  257.         '''
  258.         Initialize the formatter with specified format strings.
  259.  
  260.         Initialize the formatter either with the specified format string, or a
  261.         default as described above. Allow for specialized date formatting with
  262.         the optional datefmt argument (if omitted, you get the ISO8601 format).
  263.         '''
  264.         if fmt:
  265.             self._fmt = fmt
  266.         else:
  267.             self._fmt = '%(message)s'
  268.         self.datefmt = datefmt
  269.  
  270.     
  271.     def formatTime(self, record, datefmt = None):
  272.         """
  273.         Return the creation time of the specified LogRecord as formatted text.
  274.  
  275.         This method should be called from format() by a formatter which
  276.         wants to make use of a formatted time. This method can be overridden
  277.         in formatters to provide for any specific requirement, but the
  278.         basic behaviour is as follows: if datefmt (a string) is specified,
  279.         it is used with time.strftime() to format the creation time of the
  280.         record. Otherwise, the ISO8601 format is used. The resulting
  281.         string is returned. This function uses a user-configurable function
  282.         to convert the creation time to a tuple. By default, time.localtime()
  283.         is used; to change this for a particular formatter instance, set the
  284.         'converter' attribute to a function with the same signature as
  285.         time.localtime() or time.gmtime(). To change it for all formatters,
  286.         for example if you want all logging times to be shown in GMT,
  287.         set the 'converter' attribute in the Formatter class.
  288.         """
  289.         ct = self.converter(record.created)
  290.         if datefmt:
  291.             s = time.strftime(datefmt, ct)
  292.         else:
  293.             t = time.strftime('%Y-%m-%d %H:%M:%S', ct)
  294.             s = '%s,%03d' % (t, record.msecs)
  295.         return s
  296.  
  297.     
  298.     def formatException(self, ei):
  299.         '''
  300.         Format and return the specified exception information as a string.
  301.  
  302.         This default implementation just uses
  303.         traceback.print_exception()
  304.         '''
  305.         import traceback
  306.         sio = cStringIO.StringIO()
  307.         traceback.print_exception(ei[0], ei[1], ei[2], None, sio)
  308.         s = sio.getvalue()
  309.         sio.close()
  310.         if s[-1] == '\n':
  311.             s = s[:-1]
  312.         
  313.         return s
  314.  
  315.     
  316.     def format(self, record):
  317.         '''
  318.         Format the specified record as text.
  319.  
  320.         The record\'s attribute dictionary is used as the operand to a
  321.         string formatting operation which yields the returned string.
  322.         Before formatting the dictionary, a couple of preparatory steps
  323.         are carried out. The message attribute of the record is computed
  324.         using LogRecord.getMessage(). If the formatting string contains
  325.         "%(asctime)", formatTime() is called to format the event time.
  326.         If there is exception information, it is formatted using
  327.         formatException() and appended to the message.
  328.         '''
  329.         record.message = record.getMessage()
  330.         if string.find(self._fmt, '%(asctime)') >= 0:
  331.             record.asctime = self.formatTime(record, self.datefmt)
  332.         
  333.         s = self._fmt % record.__dict__
  334.         if record.exc_info:
  335.             if not record.exc_text:
  336.                 record.exc_text = self.formatException(record.exc_info)
  337.             
  338.         
  339.         if record.exc_text:
  340.             if s[-1] != '\n':
  341.                 s = s + '\n'
  342.             
  343.             s = s + record.exc_text
  344.         
  345.         return s
  346.  
  347.  
  348. _defaultFormatter = Formatter()
  349.  
  350. class BufferingFormatter:
  351.     '''
  352.     A formatter suitable for formatting a number of records.
  353.     '''
  354.     
  355.     def __init__(self, linefmt = None):
  356.         '''
  357.         Optionally specify a formatter which will be used to format each
  358.         individual record.
  359.         '''
  360.         if linefmt:
  361.             self.linefmt = linefmt
  362.         else:
  363.             self.linefmt = _defaultFormatter
  364.  
  365.     
  366.     def formatHeader(self, records):
  367.         '''
  368.         Return the header string for the specified records.
  369.         '''
  370.         return ''
  371.  
  372.     
  373.     def formatFooter(self, records):
  374.         '''
  375.         Return the footer string for the specified records.
  376.         '''
  377.         return ''
  378.  
  379.     
  380.     def format(self, records):
  381.         '''
  382.         Format the specified records and return the result as a string.
  383.         '''
  384.         rv = ''
  385.         if len(records) > 0:
  386.             rv = rv + self.formatHeader(records)
  387.             for record in records:
  388.                 rv = rv + self.linefmt.format(record)
  389.             
  390.             rv = rv + self.formatFooter(records)
  391.         
  392.         return rv
  393.  
  394.  
  395.  
  396. class Filter:
  397.     '''
  398.     Filter instances are used to perform arbitrary filtering of LogRecords.
  399.  
  400.     Loggers and Handlers can optionally use Filter instances to filter
  401.     records as desired. The base filter class only allows events which are
  402.     below a certain point in the logger hierarchy. For example, a filter
  403.     initialized with "A.B" will allow events logged by loggers "A.B",
  404.     "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
  405.     initialized with the empty string, all events are passed.
  406.     '''
  407.     
  408.     def __init__(self, name = ''):
  409.         '''
  410.         Initialize a filter.
  411.  
  412.         Initialize with the name of the logger which, together with its
  413.         children, will have its events allowed through the filter. If no
  414.         name is specified, allow every event.
  415.         '''
  416.         self.name = name
  417.         self.nlen = len(name)
  418.  
  419.     
  420.     def filter(self, record):
  421.         '''
  422.         Determine if the specified record is to be logged.
  423.  
  424.         Is the specified record to be logged? Returns 0 for no, nonzero for
  425.         yes. If deemed appropriate, the record may be modified in-place.
  426.         '''
  427.         if self.nlen == 0:
  428.             return 1
  429.         elif self.name == record.name:
  430.             return 1
  431.         elif string.find(record.name, self.name, 0, self.nlen) != 0:
  432.             return 0
  433.         
  434.         return record.name[self.nlen] == '.'
  435.  
  436.  
  437.  
  438. class Filterer:
  439.     '''
  440.     A base class for loggers and handlers which allows them to share
  441.     common code.
  442.     '''
  443.     
  444.     def __init__(self):
  445.         '''
  446.         Initialize the list of filters to be an empty list.
  447.         '''
  448.         self.filters = []
  449.  
  450.     
  451.     def addFilter(self, filter):
  452.         '''
  453.         Add the specified filter to this handler.
  454.         '''
  455.         if filter not in self.filters:
  456.             self.filters.append(filter)
  457.         
  458.  
  459.     
  460.     def removeFilter(self, filter):
  461.         '''
  462.         Remove the specified filter from this handler.
  463.         '''
  464.         if filter in self.filters:
  465.             self.filters.remove(filter)
  466.         
  467.  
  468.     
  469.     def filter(self, record):
  470.         '''
  471.         Determine if a record is loggable by consulting all the filters.
  472.  
  473.         The default is to allow the record to be logged; any filter can veto
  474.         this and the record is then dropped. Returns a zero value if a record
  475.         is to be dropped, else non-zero.
  476.         '''
  477.         rv = 1
  478.         for f in self.filters:
  479.             if not f.filter(record):
  480.                 rv = 0
  481.                 break
  482.                 continue
  483.         
  484.         return rv
  485.  
  486.  
  487. _handlers = { }
  488.  
  489. class Handler(Filterer):
  490.     """
  491.     Handler instances dispatch logging events to specific destinations.
  492.  
  493.     The base handler class. Acts as a placeholder which defines the Handler
  494.     interface. Handlers can optionally use Formatter instances to format
  495.     records as desired. By default, no formatter is specified; in this case,
  496.     the 'raw' message as determined by record.message is logged.
  497.     """
  498.     
  499.     def __init__(self, level = NOTSET):
  500.         '''
  501.         Initializes the instance - basically setting the formatter to None
  502.         and the filter list to empty.
  503.         '''
  504.         Filterer.__init__(self)
  505.         self.level = level
  506.         self.formatter = None
  507.         _acquireLock()
  508.         
  509.         try:
  510.             _handlers[self] = 1
  511.         finally:
  512.             _releaseLock()
  513.  
  514.         self.createLock()
  515.  
  516.     
  517.     def createLock(self):
  518.         '''
  519.         Acquire a thread lock for serializing access to the underlying I/O.
  520.         '''
  521.         if thread:
  522.             self.lock = thread.allocate_lock()
  523.         else:
  524.             self.lock = None
  525.  
  526.     
  527.     def acquire(self):
  528.         '''
  529.         Acquire the I/O thread lock.
  530.         '''
  531.         if self.lock:
  532.             self.lock.acquire()
  533.         
  534.  
  535.     
  536.     def release(self):
  537.         '''
  538.         Release the I/O thread lock.
  539.         '''
  540.         if self.lock:
  541.             self.lock.release()
  542.         
  543.  
  544.     
  545.     def setLevel(self, level):
  546.         '''
  547.         Set the logging level of this handler.
  548.         '''
  549.         self.level = level
  550.  
  551.     
  552.     def format(self, record):
  553.         '''
  554.         Format the specified record.
  555.  
  556.         If a formatter is set, use it. Otherwise, use the default formatter
  557.         for the module.
  558.         '''
  559.         if self.formatter:
  560.             fmt = self.formatter
  561.         else:
  562.             fmt = _defaultFormatter
  563.         return fmt.format(record)
  564.  
  565.     
  566.     def emit(self, record):
  567.         '''
  568.         Do whatever it takes to actually log the specified logging record.
  569.  
  570.         This version is intended to be implemented by subclasses and so
  571.         raises a NotImplementedError.
  572.         '''
  573.         raise NotImplementedError, 'emit must be implemented by Handler subclasses'
  574.  
  575.     
  576.     def handle(self, record):
  577.         '''
  578.         Conditionally emit the specified logging record.
  579.  
  580.         Emission depends on filters which may have been added to the handler.
  581.         Wrap the actual emission of the record with acquisition/release of
  582.         the I/O thread lock. Returns whether the filter passed the record for
  583.         emission.
  584.         '''
  585.         rv = self.filter(record)
  586.         if rv:
  587.             self.acquire()
  588.             
  589.             try:
  590.                 self.emit(record)
  591.             finally:
  592.                 self.release()
  593.  
  594.         
  595.         return rv
  596.  
  597.     
  598.     def setFormatter(self, fmt):
  599.         '''
  600.         Set the formatter for this handler.
  601.         '''
  602.         self.formatter = fmt
  603.  
  604.     
  605.     def flush(self):
  606.         '''
  607.         Ensure all logging output has been flushed.
  608.  
  609.         This version does nothing and is intended to be implemented by
  610.         subclasses.
  611.         '''
  612.         pass
  613.  
  614.     
  615.     def close(self):
  616.         '''
  617.         Tidy up any resources used by the handler.
  618.  
  619.         This version does removes the handler from an internal list
  620.         of handlers which is closed when shutdown() is called. Subclasses
  621.         should ensure that this gets called from overridden close()
  622.         methods.
  623.         '''
  624.         _acquireLock()
  625.         
  626.         try:
  627.             del _handlers[self]
  628.         finally:
  629.             _releaseLock()
  630.  
  631.  
  632.     
  633.     def handleError(self, record):
  634.         '''
  635.         Handle errors which occur during an emit() call.
  636.  
  637.         This method should be called from handlers when an exception is
  638.         encountered during an emit() call. If raiseExceptions is false,
  639.         exceptions get silently ignored. This is what is mostly wanted
  640.         for a logging system - most users will not care about errors in
  641.         the logging system, they are more interested in application errors.
  642.         You could, however, replace this with a custom handler if you wish.
  643.         The record which was being processed is passed in to this method.
  644.         '''
  645.         if raiseExceptions:
  646.             import traceback
  647.             ei = sys.exc_info()
  648.             traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr)
  649.             del ei
  650.         
  651.  
  652.  
  653.  
  654. class StreamHandler(Handler):
  655.     '''
  656.     A handler class which writes logging records, appropriately formatted,
  657.     to a stream. Note that this class does not close the stream, as
  658.     sys.stdout or sys.stderr may be used.
  659.     '''
  660.     
  661.     def __init__(self, strm = None):
  662.         '''
  663.         Initialize the handler.
  664.  
  665.         If strm is not specified, sys.stderr is used.
  666.         '''
  667.         Handler.__init__(self)
  668.         if not strm:
  669.             strm = sys.stderr
  670.         
  671.         self.stream = strm
  672.         self.formatter = None
  673.  
  674.     
  675.     def flush(self):
  676.         '''
  677.         Flushes the stream.
  678.         '''
  679.         self.stream.flush()
  680.  
  681.     
  682.     def emit(self, record):
  683.         '''
  684.         Emit a record.
  685.  
  686.         If a formatter is specified, it is used to format the record.
  687.         The record is then written to the stream with a trailing newline
  688.         [N.B. this may be removed depending on feedback]. If exception
  689.         information is present, it is formatted using
  690.         traceback.print_exception and appended to the stream.
  691.         '''
  692.         
  693.         try:
  694.             msg = self.format(record)
  695.             fs = '%s\n'
  696.             if not hasattr(types, 'UnicodeType'):
  697.                 self.stream.write(fs % msg)
  698.             else:
  699.                 
  700.                 try:
  701.                     self.stream.write(fs % msg)
  702.                 except UnicodeError:
  703.                     self.stream.write(fs % msg.encode('UTF-8'))
  704.  
  705.             self.flush()
  706.         except:
  707.             self.handleError(record)
  708.  
  709.  
  710.  
  711.  
  712. class FileHandler(StreamHandler):
  713.     '''
  714.     A handler class which writes formatted logging records to disk files.
  715.     '''
  716.     
  717.     def __init__(self, filename, mode = 'a'):
  718.         '''
  719.         Open the specified file and use it as the stream for logging.
  720.         '''
  721.         StreamHandler.__init__(self, open(filename, mode))
  722.         self.baseFilename = os.path.abspath(filename)
  723.         self.mode = mode
  724.  
  725.     
  726.     def close(self):
  727.         '''
  728.         Closes the stream.
  729.         '''
  730.         self.flush()
  731.         self.stream.close()
  732.         StreamHandler.close(self)
  733.  
  734.  
  735.  
  736. class PlaceHolder:
  737.     '''
  738.     PlaceHolder instances are used in the Manager logger hierarchy to take
  739.     the place of nodes for which no loggers have been defined. This class is
  740.     intended for internal use only and not as part of the public API.
  741.     '''
  742.     
  743.     def __init__(self, alogger):
  744.         '''
  745.         Initialize with the specified logger being a child of this placeholder.
  746.         '''
  747.         self.loggers = [
  748.             alogger]
  749.  
  750.     
  751.     def append(self, alogger):
  752.         '''
  753.         Add the specified logger as a child of this placeholder.
  754.         '''
  755.         if alogger not in self.loggers:
  756.             self.loggers.append(alogger)
  757.         
  758.  
  759.  
  760. _loggerClass = None
  761.  
  762. def setLoggerClass(klass):
  763.     '''
  764.     Set the class to be used when instantiating a logger. The class should
  765.     define __init__() such that only a name argument is required, and the
  766.     __init__() should call Logger.__init__()
  767.     '''
  768.     global _loggerClass
  769.     if klass != Logger:
  770.         if not issubclass(klass, Logger):
  771.             raise TypeError, 'logger not derived from logging.Logger: ' + klass.__name__
  772.         
  773.     
  774.     _loggerClass = klass
  775.  
  776.  
  777. def getLoggerClass():
  778.     '''
  779.     Return the class to be used when instantiating a logger.
  780.     '''
  781.     return _loggerClass
  782.  
  783.  
  784. class Manager:
  785.     '''
  786.     There is [under normal circumstances] just one Manager instance, which
  787.     holds the hierarchy of loggers.
  788.     '''
  789.     
  790.     def __init__(self, rootnode):
  791.         '''
  792.         Initialize the manager with the root node of the logger hierarchy.
  793.         '''
  794.         self.root = rootnode
  795.         self.disable = 0
  796.         self.emittedNoHandlerWarning = 0
  797.         self.loggerDict = { }
  798.  
  799.     
  800.     def getLogger(self, name):
  801.         '''
  802.         Get a logger with the specified name (channel name), creating it
  803.         if it doesn\'t yet exist. This name is a dot-separated hierarchical
  804.         name, such as "a", "a.b", "a.b.c" or similar.
  805.  
  806.         If a PlaceHolder existed for the specified name [i.e. the logger
  807.         didn\'t exist but a child of it did], replace it with the created
  808.         logger and fix up the parent/child references which pointed to the
  809.         placeholder to now point to the logger.
  810.         '''
  811.         rv = None
  812.         _acquireLock()
  813.         
  814.         try:
  815.             if self.loggerDict.has_key(name):
  816.                 rv = self.loggerDict[name]
  817.                 if isinstance(rv, PlaceHolder):
  818.                     ph = rv
  819.                     rv = _loggerClass(name)
  820.                     rv.manager = self
  821.                     self.loggerDict[name] = rv
  822.                     self._fixupChildren(ph, rv)
  823.                     self._fixupParents(rv)
  824.                 
  825.             else:
  826.                 rv = _loggerClass(name)
  827.                 rv.manager = self
  828.                 self.loggerDict[name] = rv
  829.                 self._fixupParents(rv)
  830.         finally:
  831.             _releaseLock()
  832.  
  833.         return rv
  834.  
  835.     
  836.     def _fixupParents(self, alogger):
  837.         '''
  838.         Ensure that there are either loggers or placeholders all the way
  839.         from the specified logger to the root of the logger hierarchy.
  840.         '''
  841.         name = alogger.name
  842.         i = string.rfind(name, '.')
  843.         rv = None
  844.         while i > 0 and not rv:
  845.             substr = name[:i]
  846.             if not self.loggerDict.has_key(substr):
  847.                 self.loggerDict[substr] = PlaceHolder(alogger)
  848.             else:
  849.                 obj = self.loggerDict[substr]
  850.                 if isinstance(obj, Logger):
  851.                     rv = obj
  852.                 elif not isinstance(obj, PlaceHolder):
  853.                     raise AssertionError
  854.                 obj.append(alogger)
  855.             i = string.rfind(name, '.', 0, i - 1)
  856.         if not rv:
  857.             rv = self.root
  858.         
  859.         alogger.parent = rv
  860.  
  861.     
  862.     def _fixupChildren(self, ph, alogger):
  863.         '''
  864.         Ensure that children of the placeholder ph are connected to the
  865.         specified logger.
  866.         '''
  867.         for c in ph.loggers:
  868.             if string.find(c.parent.name, alogger.name) != 0:
  869.                 alogger.parent = c.parent
  870.                 c.parent = alogger
  871.                 continue
  872.         
  873.  
  874.  
  875.  
  876. class Logger(Filterer):
  877.     '''
  878.     Instances of the Logger class represent a single logging channel. A
  879.     "logging channel" indicates an area of an application. Exactly how an
  880.     "area" is defined is up to the application developer. Since an
  881.     application can have any number of areas, logging channels are identified
  882.     by a unique string. Application areas can be nested (e.g. an area
  883.     of "input processing" might include sub-areas "read CSV files", "read
  884.     XLS files" and "read Gnumeric files"). To cater for this natural nesting,
  885.     channel names are organized into a namespace hierarchy where levels are
  886.     separated by periods, much like the Java or Python package namespace. So
  887.     in the instance given above, channel names might be "input" for the upper
  888.     level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels.
  889.     There is no arbitrary limit to the depth of nesting.
  890.     '''
  891.     
  892.     def __init__(self, name, level = NOTSET):
  893.         '''
  894.         Initialize the logger with a name and an optional level.
  895.         '''
  896.         Filterer.__init__(self)
  897.         self.name = name
  898.         self.level = level
  899.         self.parent = None
  900.         self.propagate = 1
  901.         self.handlers = []
  902.         self.disabled = 0
  903.  
  904.     
  905.     def setLevel(self, level):
  906.         '''
  907.         Set the logging level of this logger.
  908.         '''
  909.         self.level = level
  910.  
  911.     
  912.     def debug(self, msg, *args, **kwargs):
  913.         '''
  914.         Log \'msg % args\' with severity \'DEBUG\'.
  915.  
  916.         To pass exception information, use the keyword argument exc_info with
  917.         a true value, e.g.
  918.  
  919.         logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
  920.         '''
  921.         if self.manager.disable >= DEBUG:
  922.             return None
  923.         
  924.         if DEBUG >= self.getEffectiveLevel():
  925.             apply(self._log, (DEBUG, msg, args), kwargs)
  926.         
  927.  
  928.     
  929.     def info(self, msg, *args, **kwargs):
  930.         '''
  931.         Log \'msg % args\' with severity \'INFO\'.
  932.  
  933.         To pass exception information, use the keyword argument exc_info with
  934.         a true value, e.g.
  935.  
  936.         logger.info("Houston, we have a %s", "interesting problem", exc_info=1)
  937.         '''
  938.         if self.manager.disable >= INFO:
  939.             return None
  940.         
  941.         if INFO >= self.getEffectiveLevel():
  942.             apply(self._log, (INFO, msg, args), kwargs)
  943.         
  944.  
  945.     
  946.     def warning(self, msg, *args, **kwargs):
  947.         '''
  948.         Log \'msg % args\' with severity \'WARNING\'.
  949.  
  950.         To pass exception information, use the keyword argument exc_info with
  951.         a true value, e.g.
  952.  
  953.         logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)
  954.         '''
  955.         if self.manager.disable >= WARNING:
  956.             return None
  957.         
  958.         if self.isEnabledFor(WARNING):
  959.             apply(self._log, (WARNING, msg, args), kwargs)
  960.         
  961.  
  962.     warn = warning
  963.     
  964.     def error(self, msg, *args, **kwargs):
  965.         '''
  966.         Log \'msg % args\' with severity \'ERROR\'.
  967.  
  968.         To pass exception information, use the keyword argument exc_info with
  969.         a true value, e.g.
  970.  
  971.         logger.error("Houston, we have a %s", "major problem", exc_info=1)
  972.         '''
  973.         if self.manager.disable >= ERROR:
  974.             return None
  975.         
  976.         if self.isEnabledFor(ERROR):
  977.             apply(self._log, (ERROR, msg, args), kwargs)
  978.         
  979.  
  980.     
  981.     def exception(self, msg, *args):
  982.         '''
  983.         Convenience method for logging an ERROR with exception information.
  984.         '''
  985.         apply(self.error, (msg,) + args, {
  986.             'exc_info': 1 })
  987.  
  988.     
  989.     def critical(self, msg, *args, **kwargs):
  990.         '''
  991.         Log \'msg % args\' with severity \'CRITICAL\'.
  992.  
  993.         To pass exception information, use the keyword argument exc_info with
  994.         a true value, e.g.
  995.  
  996.         logger.critical("Houston, we have a %s", "major disaster", exc_info=1)
  997.         '''
  998.         if self.manager.disable >= CRITICAL:
  999.             return None
  1000.         
  1001.         if CRITICAL >= self.getEffectiveLevel():
  1002.             apply(self._log, (CRITICAL, msg, args), kwargs)
  1003.         
  1004.  
  1005.     fatal = critical
  1006.     
  1007.     def log(self, level, msg, *args, **kwargs):
  1008.         '''
  1009.         Log \'msg % args\' with the integer severity \'level\'.
  1010.  
  1011.         To pass exception information, use the keyword argument exc_info with
  1012.         a true value, e.g.
  1013.  
  1014.         logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
  1015.         '''
  1016.         if type(level) != types.IntType:
  1017.             if raiseExceptions:
  1018.                 raise TypeError, 'level must be an integer'
  1019.             else:
  1020.                 return None
  1021.         
  1022.         if self.manager.disable >= level:
  1023.             return None
  1024.         
  1025.         if self.isEnabledFor(level):
  1026.             apply(self._log, (level, msg, args), kwargs)
  1027.         
  1028.  
  1029.     
  1030.     def findCaller(self):
  1031.         '''
  1032.         Find the stack frame of the caller so that we can note the source
  1033.         file name and line number.
  1034.         '''
  1035.         f = sys._getframe(1)
  1036.         while None:
  1037.             co = f.f_code
  1038.             filename = os.path.normcase(co.co_filename)
  1039.             if filename == _srcfile:
  1040.                 f = f.f_back
  1041.                 continue
  1042.             
  1043.             return (filename, f.f_lineno)
  1044.  
  1045.     
  1046.     def makeRecord(self, name, level, fn, lno, msg, args, exc_info):
  1047.         '''
  1048.         A factory method which can be overridden in subclasses to create
  1049.         specialized LogRecords.
  1050.         '''
  1051.         return LogRecord(name, level, fn, lno, msg, args, exc_info)
  1052.  
  1053.     
  1054.     def _log(self, level, msg, args, exc_info = None):
  1055.         '''
  1056.         Low-level logging routine which creates a LogRecord and then calls
  1057.         all the handlers of this logger to handle the record.
  1058.         '''
  1059.         if _srcfile:
  1060.             (fn, lno) = self.findCaller()
  1061.         else:
  1062.             (fn, lno) = ('<unknown file>', 0)
  1063.         if exc_info:
  1064.             if type(exc_info) != types.TupleType:
  1065.                 exc_info = sys.exc_info()
  1066.             
  1067.         
  1068.         record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info)
  1069.         self.handle(record)
  1070.  
  1071.     
  1072.     def handle(self, record):
  1073.         '''
  1074.         Call the handlers for the specified record.
  1075.  
  1076.         This method is used for unpickled records received from a socket, as
  1077.         well as those created locally. Logger-level filtering is applied.
  1078.         '''
  1079.         if not (self.disabled) and self.filter(record):
  1080.             self.callHandlers(record)
  1081.         
  1082.  
  1083.     
  1084.     def addHandler(self, hdlr):
  1085.         '''
  1086.         Add the specified handler to this logger.
  1087.         '''
  1088.         if hdlr not in self.handlers:
  1089.             self.handlers.append(hdlr)
  1090.         
  1091.  
  1092.     
  1093.     def removeHandler(self, hdlr):
  1094.         '''
  1095.         Remove the specified handler from this logger.
  1096.         '''
  1097.         if hdlr in self.handlers:
  1098.             self.handlers.remove(hdlr)
  1099.         
  1100.  
  1101.     
  1102.     def callHandlers(self, record):
  1103.         '''
  1104.         Pass a record to all relevant handlers.
  1105.  
  1106.         Loop through all handlers for this logger and its parents in the
  1107.         logger hierarchy. If no handler was found, output a one-off error
  1108.         message to sys.stderr. Stop searching up the hierarchy whenever a
  1109.         logger with the "propagate" attribute set to zero is found - that
  1110.         will be the last logger whose handlers are called.
  1111.         '''
  1112.         c = self
  1113.         found = 0
  1114.         while c:
  1115.             for hdlr in c.handlers:
  1116.                 found = found + 1
  1117.                 if record.levelno >= hdlr.level:
  1118.                     hdlr.handle(record)
  1119.                     continue
  1120.             
  1121.             if not c.propagate:
  1122.                 c = None
  1123.                 continue
  1124.             c = c.parent
  1125.         if found == 0 and not (self.manager.emittedNoHandlerWarning):
  1126.             sys.stderr.write('No handlers could be found for logger "%s"\n' % self.name)
  1127.             self.manager.emittedNoHandlerWarning = 1
  1128.         
  1129.  
  1130.     
  1131.     def getEffectiveLevel(self):
  1132.         '''
  1133.         Get the effective level for this logger.
  1134.  
  1135.         Loop through this logger and its parents in the logger hierarchy,
  1136.         looking for a non-zero logging level. Return the first one found.
  1137.         '''
  1138.         logger = self
  1139.         while logger:
  1140.             if logger.level:
  1141.                 return logger.level
  1142.             
  1143.             logger = logger.parent
  1144.         return NOTSET
  1145.  
  1146.     
  1147.     def isEnabledFor(self, level):
  1148.         """
  1149.         Is this logger enabled for level 'level'?
  1150.         """
  1151.         if self.manager.disable >= level:
  1152.             return 0
  1153.         
  1154.         return level >= self.getEffectiveLevel()
  1155.  
  1156.  
  1157.  
  1158. class RootLogger(Logger):
  1159.     '''
  1160.     A root logger is not that different to any other logger, except that
  1161.     it must have a logging level and there is only one instance of it in
  1162.     the hierarchy.
  1163.     '''
  1164.     
  1165.     def __init__(self, level):
  1166.         '''
  1167.         Initialize the logger with the name "root".
  1168.         '''
  1169.         Logger.__init__(self, 'root', level)
  1170.  
  1171.  
  1172. _loggerClass = Logger
  1173. root = RootLogger(WARNING)
  1174. Logger.root = root
  1175. Logger.manager = Manager(Logger.root)
  1176. BASIC_FORMAT = '%(levelname)s:%(name)s:%(message)s'
  1177.  
  1178. def basicConfig(**kwargs):
  1179.     '''
  1180.     Do basic configuration for the logging system.
  1181.  
  1182.     This function does nothing if the root logger already has handlers
  1183.     configured. It is a convenience method intended for use by simple scripts
  1184.     to do one-shot configuration of the logging package.
  1185.  
  1186.     The default behaviour is to create a StreamHandler which writes to
  1187.     sys.stderr, set a formatter using the BASIC_FORMAT format string, and
  1188.     add the handler to the root logger.
  1189.  
  1190.     A number of optional keyword arguments may be specified, which can alter
  1191.     the default behaviour.
  1192.  
  1193.     filename  Specifies that a FileHandler be created, using the specified
  1194.               filename, rather than a StreamHandler.
  1195.     filemode  Specifies the mode to open the file, if filename is specified
  1196.               (if filemode is unspecified, it defaults to "a").
  1197.     format    Use the specified format string for the handler.
  1198.     datefmt   Use the specified date/time format.
  1199.     level     Set the root logger level to the specified level.
  1200.     stream    Use the specified stream to initialize the StreamHandler. Note
  1201.               that this argument is incompatible with \'filename\' - if both
  1202.               are present, \'stream\' is ignored.
  1203.  
  1204.     Note that you could specify a stream created using open(filename, mode)
  1205.     rather than passing the filename and mode in. However, it should be
  1206.     remembered that StreamHandler does not close its stream (since it may be
  1207.     using sys.stdout or sys.stderr), whereas FileHandler closes its stream
  1208.     when the handler is closed.
  1209.     '''
  1210.     if len(root.handlers) == 0:
  1211.         filename = kwargs.get('filename')
  1212.         if filename:
  1213.             mode = kwargs.get('filemode', 'a')
  1214.             hdlr = FileHandler(filename, mode)
  1215.         else:
  1216.             stream = kwargs.get('stream')
  1217.             hdlr = StreamHandler(stream)
  1218.         fs = kwargs.get('format', BASIC_FORMAT)
  1219.         dfs = kwargs.get('datefmt', None)
  1220.         fmt = Formatter(fs, dfs)
  1221.         hdlr.setFormatter(fmt)
  1222.         root.addHandler(hdlr)
  1223.         level = kwargs.get('level')
  1224.         if level:
  1225.             root.setLevel(level)
  1226.         
  1227.     
  1228.  
  1229.  
  1230. def getLogger(name = None):
  1231.     '''
  1232.     Return a logger with the specified name, creating it if necessary.
  1233.  
  1234.     If no name is specified, return the root logger.
  1235.     '''
  1236.     if name:
  1237.         return Logger.manager.getLogger(name)
  1238.     else:
  1239.         return root
  1240.  
  1241.  
  1242. def critical(msg, *args, **kwargs):
  1243.     """
  1244.     Log a message with severity 'CRITICAL' on the root logger.
  1245.     """
  1246.     if len(root.handlers) == 0:
  1247.         basicConfig()
  1248.     
  1249.     apply(root.critical, (msg,) + args, kwargs)
  1250.  
  1251. fatal = critical
  1252.  
  1253. def error(msg, *args, **kwargs):
  1254.     """
  1255.     Log a message with severity 'ERROR' on the root logger.
  1256.     """
  1257.     if len(root.handlers) == 0:
  1258.         basicConfig()
  1259.     
  1260.     apply(root.error, (msg,) + args, kwargs)
  1261.  
  1262.  
  1263. def exception(msg, *args):
  1264.     """
  1265.     Log a message with severity 'ERROR' on the root logger,
  1266.     with exception information.
  1267.     """
  1268.     apply(error, (msg,) + args, {
  1269.         'exc_info': 1 })
  1270.  
  1271.  
  1272. def warning(msg, *args, **kwargs):
  1273.     """
  1274.     Log a message with severity 'WARNING' on the root logger.
  1275.     """
  1276.     if len(root.handlers) == 0:
  1277.         basicConfig()
  1278.     
  1279.     apply(root.warning, (msg,) + args, kwargs)
  1280.  
  1281. warn = warning
  1282.  
  1283. def info(msg, *args, **kwargs):
  1284.     """
  1285.     Log a message with severity 'INFO' on the root logger.
  1286.     """
  1287.     if len(root.handlers) == 0:
  1288.         basicConfig()
  1289.     
  1290.     apply(root.info, (msg,) + args, kwargs)
  1291.  
  1292.  
  1293. def debug(msg, *args, **kwargs):
  1294.     """
  1295.     Log a message with severity 'DEBUG' on the root logger.
  1296.     """
  1297.     if len(root.handlers) == 0:
  1298.         basicConfig()
  1299.     
  1300.     apply(root.debug, (msg,) + args, kwargs)
  1301.  
  1302.  
  1303. def log(level, msg, *args, **kwargs):
  1304.     """
  1305.     Log 'msg % args' with the integer severity 'level' on the root logger.
  1306.     """
  1307.     if len(root.handlers) == 0:
  1308.         basicConfig()
  1309.     
  1310.     apply(root.log, (level, msg) + args, kwargs)
  1311.  
  1312.  
  1313. def disable(level):
  1314.     """
  1315.     Disable all logging calls less severe than 'level'.
  1316.     """
  1317.     root.manager.disable = level
  1318.  
  1319.  
  1320. def shutdown():
  1321.     '''
  1322.     Perform any cleanup actions in the logging system (e.g. flushing
  1323.     buffers).
  1324.  
  1325.     Should be called at application exit.
  1326.     '''
  1327.     for h in _handlers.keys():
  1328.         
  1329.         try:
  1330.             h.flush()
  1331.             h.close()
  1332.         continue
  1333.         continue
  1334.  
  1335.     
  1336.  
  1337.  
  1338. try:
  1339.     import atexit
  1340.     atexit.register(shutdown)
  1341. except ImportError:
  1342.     
  1343.     def exithook(status, old_exit = sys.exit):
  1344.         
  1345.         try:
  1346.             shutdown()
  1347.         finally:
  1348.             old_exit(status)
  1349.  
  1350.  
  1351.     sys.exit = exithook
  1352.  
  1353.