home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 January / maximum-cd-2011-01.iso / DiscContents / xbmc-9.11.exe / system / python / python24.zlib / logging / __init__.py next >
Encoding:
Python Source  |  2004-10-21  |  43.6 KB  |  1,305 lines

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