PageRenderTime 70ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/logging/__init__.py

https://bitbucket.org/dac_io/pypy
Python | 1707 lines | 1679 code | 4 blank | 24 comment | 7 complexity | 3293c17316c5c7adf2f978ac4aaed929 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file