PageRenderTime 56ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/Lib/logging/__init__.py

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