logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

__init__.py (79820B)


  1. # Copyright 2001-2019 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.
  19. Copyright (C) 2001-2019 Vinay Sajip. All Rights Reserved.
  20. To use, simply 'import logging' and log away!
  21. """
  22. import sys, os, time, io, re, traceback, warnings, weakref, collections.abc
  23. from string import Template
  24. from string import Formatter as StrFormatter
  25. __all__ = ['BASIC_FORMAT', 'BufferingFormatter', 'CRITICAL', 'DEBUG', 'ERROR',
  26. 'FATAL', 'FileHandler', 'Filter', 'Formatter', 'Handler', 'INFO',
  27. 'LogRecord', 'Logger', 'LoggerAdapter', 'NOTSET', 'NullHandler',
  28. 'StreamHandler', 'WARN', 'WARNING', 'addLevelName', 'basicConfig',
  29. 'captureWarnings', 'critical', 'debug', 'disable', 'error',
  30. 'exception', 'fatal', 'getLevelName', 'getLogger', 'getLoggerClass',
  31. 'info', 'log', 'makeLogRecord', 'setLoggerClass', 'shutdown',
  32. 'warn', 'warning', 'getLogRecordFactory', 'setLogRecordFactory',
  33. 'lastResort', 'raiseExceptions']
  34. import threading
  35. __author__ = "Vinay Sajip <vinay_sajip@red-dove.com>"
  36. __status__ = "production"
  37. # The following module attributes are no longer updated.
  38. __version__ = "0.5.1.2"
  39. __date__ = "07 February 2010"
  40. #---------------------------------------------------------------------------
  41. # Miscellaneous module data
  42. #---------------------------------------------------------------------------
  43. #
  44. #_startTime is used as the base when calculating the relative time of events
  45. #
  46. _startTime = time.time()
  47. #
  48. #raiseExceptions is used to see if exceptions during handling should be
  49. #propagated
  50. #
  51. raiseExceptions = True
  52. #
  53. # If you don't want threading information in the log, set this to zero
  54. #
  55. logThreads = True
  56. #
  57. # If you don't want multiprocessing information in the log, set this to zero
  58. #
  59. logMultiprocessing = True
  60. #
  61. # If you don't want process information in the log, set this to zero
  62. #
  63. logProcesses = True
  64. #---------------------------------------------------------------------------
  65. # Level related stuff
  66. #---------------------------------------------------------------------------
  67. #
  68. # Default levels and level names, these can be replaced with any positive set
  69. # of values having corresponding names. There is a pseudo-level, NOTSET, which
  70. # is only really there as a lower limit for user-defined levels. Handlers and
  71. # loggers are initialized with NOTSET so that they will log all messages, even
  72. # at user-defined levels.
  73. #
  74. CRITICAL = 50
  75. FATAL = CRITICAL
  76. ERROR = 40
  77. WARNING = 30
  78. WARN = WARNING
  79. INFO = 20
  80. DEBUG = 10
  81. NOTSET = 0
  82. _levelToName = {
  83. CRITICAL: 'CRITICAL',
  84. ERROR: 'ERROR',
  85. WARNING: 'WARNING',
  86. INFO: 'INFO',
  87. DEBUG: 'DEBUG',
  88. NOTSET: 'NOTSET',
  89. }
  90. _nameToLevel = {
  91. 'CRITICAL': CRITICAL,
  92. 'FATAL': FATAL,
  93. 'ERROR': ERROR,
  94. 'WARN': WARNING,
  95. 'WARNING': WARNING,
  96. 'INFO': INFO,
  97. 'DEBUG': DEBUG,
  98. 'NOTSET': NOTSET,
  99. }
  100. def getLevelName(level):
  101. """
  102. Return the textual or numeric representation of logging level 'level'.
  103. If the level is one of the predefined levels (CRITICAL, ERROR, WARNING,
  104. INFO, DEBUG) then you get the corresponding string. If you have
  105. associated levels with names using addLevelName then the name you have
  106. associated with 'level' is returned.
  107. If a numeric value corresponding to one of the defined levels is passed
  108. in, the corresponding string representation is returned.
  109. If a string representation of the level is passed in, the corresponding
  110. numeric value is returned.
  111. If no matching numeric or string value is passed in, the string
  112. 'Level %s' % level is returned.
  113. """
  114. # See Issues #22386, #27937 and #29220 for why it's this way
  115. result = _levelToName.get(level)
  116. if result is not None:
  117. return result
  118. result = _nameToLevel.get(level)
  119. if result is not None:
  120. return result
  121. return "Level %s" % level
  122. def addLevelName(level, levelName):
  123. """
  124. Associate 'levelName' with 'level'.
  125. This is used when converting levels to text during message formatting.
  126. """
  127. _acquireLock()
  128. try: #unlikely to cause an exception, but you never know...
  129. _levelToName[level] = levelName
  130. _nameToLevel[levelName] = level
  131. finally:
  132. _releaseLock()
  133. if hasattr(sys, '_getframe'):
  134. currentframe = lambda: sys._getframe(3)
  135. else: #pragma: no cover
  136. def currentframe():
  137. """Return the frame object for the caller's stack frame."""
  138. try:
  139. raise Exception
  140. except Exception:
  141. return sys.exc_info()[2].tb_frame.f_back
  142. #
  143. # _srcfile is used when walking the stack to check when we've got the first
  144. # caller stack frame, by skipping frames whose filename is that of this
  145. # module's source. It therefore should contain the filename of this module's
  146. # source file.
  147. #
  148. # Ordinarily we would use __file__ for this, but frozen modules don't always
  149. # have __file__ set, for some reason (see Issue #21736). Thus, we get the
  150. # filename from a handy code object from a function defined in this module.
  151. # (There's no particular reason for picking addLevelName.)
  152. #
  153. _srcfile = os.path.normcase(addLevelName.__code__.co_filename)
  154. # _srcfile is only used in conjunction with sys._getframe().
  155. # To provide compatibility with older versions of Python, set _srcfile
  156. # to None if _getframe() is not available; this value will prevent
  157. # findCaller() from being called. You can also do this if you want to avoid
  158. # the overhead of fetching caller information, even when _getframe() is
  159. # available.
  160. #if not hasattr(sys, '_getframe'):
  161. # _srcfile = None
  162. def _checkLevel(level):
  163. if isinstance(level, int):
  164. rv = level
  165. elif str(level) == level:
  166. if level not in _nameToLevel:
  167. raise ValueError("Unknown level: %r" % level)
  168. rv = _nameToLevel[level]
  169. else:
  170. raise TypeError("Level not an integer or a valid string: %r"
  171. % (level,))
  172. return rv
  173. #---------------------------------------------------------------------------
  174. # Thread-related stuff
  175. #---------------------------------------------------------------------------
  176. #
  177. #_lock is used to serialize access to shared data structures in this module.
  178. #This needs to be an RLock because fileConfig() creates and configures
  179. #Handlers, and so might arbitrary user threads. Since Handler code updates the
  180. #shared dictionary _handlers, it needs to acquire the lock. But if configuring,
  181. #the lock would already have been acquired - so we need an RLock.
  182. #The same argument applies to Loggers and Manager.loggerDict.
  183. #
  184. _lock = threading.RLock()
  185. def _acquireLock():
  186. """
  187. Acquire the module-level lock for serializing access to shared data.
  188. This should be released with _releaseLock().
  189. """
  190. if _lock:
  191. _lock.acquire()
  192. def _releaseLock():
  193. """
  194. Release the module-level lock acquired by calling _acquireLock().
  195. """
  196. if _lock:
  197. _lock.release()
  198. # Prevent a held logging lock from blocking a child from logging.
  199. if not hasattr(os, 'register_at_fork'): # Windows and friends.
  200. def _register_at_fork_reinit_lock(instance):
  201. pass # no-op when os.register_at_fork does not exist.
  202. else:
  203. # A collection of instances with a _at_fork_reinit method (logging.Handler)
  204. # to be called in the child after forking. The weakref avoids us keeping
  205. # discarded Handler instances alive.
  206. _at_fork_reinit_lock_weakset = weakref.WeakSet()
  207. def _register_at_fork_reinit_lock(instance):
  208. _acquireLock()
  209. try:
  210. _at_fork_reinit_lock_weakset.add(instance)
  211. finally:
  212. _releaseLock()
  213. def _after_at_fork_child_reinit_locks():
  214. for handler in _at_fork_reinit_lock_weakset:
  215. handler._at_fork_reinit()
  216. # _acquireLock() was called in the parent before forking.
  217. # The lock is reinitialized to unlocked state.
  218. _lock._at_fork_reinit()
  219. os.register_at_fork(before=_acquireLock,
  220. after_in_child=_after_at_fork_child_reinit_locks,
  221. after_in_parent=_releaseLock)
  222. #---------------------------------------------------------------------------
  223. # The logging record
  224. #---------------------------------------------------------------------------
  225. class LogRecord(object):
  226. """
  227. A LogRecord instance represents an event being logged.
  228. LogRecord instances are created every time something is logged. They
  229. contain all the information pertinent to the event being logged. The
  230. main information passed in is in msg and args, which are combined
  231. using str(msg) % args to create the message field of the record. The
  232. record also includes information such as when the record was created,
  233. the source line where the logging call was made, and any exception
  234. information to be logged.
  235. """
  236. def __init__(self, name, level, pathname, lineno,
  237. msg, args, exc_info, func=None, sinfo=None, **kwargs):
  238. """
  239. Initialize a logging record with interesting information.
  240. """
  241. ct = time.time()
  242. self.name = name
  243. self.msg = msg
  244. #
  245. # The following statement allows passing of a dictionary as a sole
  246. # argument, so that you can do something like
  247. # logging.debug("a %(a)d b %(b)s", {'a':1, 'b':2})
  248. # Suggested by Stefan Behnel.
  249. # Note that without the test for args[0], we get a problem because
  250. # during formatting, we test to see if the arg is present using
  251. # 'if self.args:'. If the event being logged is e.g. 'Value is %d'
  252. # and if the passed arg fails 'if self.args:' then no formatting
  253. # is done. For example, logger.warning('Value is %d', 0) would log
  254. # 'Value is %d' instead of 'Value is 0'.
  255. # For the use case of passing a dictionary, this should not be a
  256. # problem.
  257. # Issue #21172: a request was made to relax the isinstance check
  258. # to hasattr(args[0], '__getitem__'). However, the docs on string
  259. # formatting still seem to suggest a mapping object is required.
  260. # Thus, while not removing the isinstance check, it does now look
  261. # for collections.abc.Mapping rather than, as before, dict.
  262. if (args and len(args) == 1 and isinstance(args[0], collections.abc.Mapping)
  263. and args[0]):
  264. args = args[0]
  265. self.args = args
  266. self.levelname = getLevelName(level)
  267. self.levelno = level
  268. self.pathname = pathname
  269. try:
  270. self.filename = os.path.basename(pathname)
  271. self.module = os.path.splitext(self.filename)[0]
  272. except (TypeError, ValueError, AttributeError):
  273. self.filename = pathname
  274. self.module = "Unknown module"
  275. self.exc_info = exc_info
  276. self.exc_text = None # used to cache the traceback text
  277. self.stack_info = sinfo
  278. self.lineno = lineno
  279. self.funcName = func
  280. self.created = ct
  281. self.msecs = (ct - int(ct)) * 1000
  282. self.relativeCreated = (self.created - _startTime) * 1000
  283. if logThreads:
  284. self.thread = threading.get_ident()
  285. self.threadName = threading.current_thread().name
  286. else: # pragma: no cover
  287. self.thread = None
  288. self.threadName = None
  289. if not logMultiprocessing: # pragma: no cover
  290. self.processName = None
  291. else:
  292. self.processName = 'MainProcess'
  293. mp = sys.modules.get('multiprocessing')
  294. if mp is not None:
  295. # Errors may occur if multiprocessing has not finished loading
  296. # yet - e.g. if a custom import hook causes third-party code
  297. # to run when multiprocessing calls import. See issue 8200
  298. # for an example
  299. try:
  300. self.processName = mp.current_process().name
  301. except Exception: #pragma: no cover
  302. pass
  303. if logProcesses and hasattr(os, 'getpid'):
  304. self.process = os.getpid()
  305. else:
  306. self.process = None
  307. def __repr__(self):
  308. return '<LogRecord: %s, %s, %s, %s, "%s">'%(self.name, self.levelno,
  309. self.pathname, self.lineno, self.msg)
  310. def getMessage(self):
  311. """
  312. Return the message for this LogRecord.
  313. Return the message for this LogRecord after merging any user-supplied
  314. arguments with the message.
  315. """
  316. msg = str(self.msg)
  317. if self.args:
  318. msg = msg % self.args
  319. return msg
  320. #
  321. # Determine which class to use when instantiating log records.
  322. #
  323. _logRecordFactory = LogRecord
  324. def setLogRecordFactory(factory):
  325. """
  326. Set the factory to be used when instantiating a log record.
  327. :param factory: A callable which will be called to instantiate
  328. a log record.
  329. """
  330. global _logRecordFactory
  331. _logRecordFactory = factory
  332. def getLogRecordFactory():
  333. """
  334. Return the factory to be used when instantiating a log record.
  335. """
  336. return _logRecordFactory
  337. def makeLogRecord(dict):
  338. """
  339. Make a LogRecord whose attributes are defined by the specified dictionary,
  340. This function is useful for converting a logging event received over
  341. a socket connection (which is sent as a dictionary) into a LogRecord
  342. instance.
  343. """
  344. rv = _logRecordFactory(None, None, "", 0, "", (), None, None)
  345. rv.__dict__.update(dict)
  346. return rv
  347. #---------------------------------------------------------------------------
  348. # Formatter classes and functions
  349. #---------------------------------------------------------------------------
  350. _str_formatter = StrFormatter()
  351. del StrFormatter
  352. class PercentStyle(object):
  353. default_format = '%(message)s'
  354. asctime_format = '%(asctime)s'
  355. asctime_search = '%(asctime)'
  356. validation_pattern = re.compile(r'%\(\w+\)[#0+ -]*(\*|\d+)?(\.(\*|\d+))?[diouxefgcrsa%]', re.I)
  357. def __init__(self, fmt, *, defaults=None):
  358. self._fmt = fmt or self.default_format
  359. self._defaults = defaults
  360. def usesTime(self):
  361. return self._fmt.find(self.asctime_search) >= 0
  362. def validate(self):
  363. """Validate the input format, ensure it matches the correct style"""
  364. if not self.validation_pattern.search(self._fmt):
  365. raise ValueError("Invalid format '%s' for '%s' style" % (self._fmt, self.default_format[0]))
  366. def _format(self, record):
  367. if defaults := self._defaults:
  368. values = defaults | record.__dict__
  369. else:
  370. values = record.__dict__
  371. return self._fmt % values
  372. def format(self, record):
  373. try:
  374. return self._format(record)
  375. except KeyError as e:
  376. raise ValueError('Formatting field not found in record: %s' % e)
  377. class StrFormatStyle(PercentStyle):
  378. default_format = '{message}'
  379. asctime_format = '{asctime}'
  380. asctime_search = '{asctime'
  381. fmt_spec = re.compile(r'^(.?[<>=^])?[+ -]?#?0?(\d+|{\w+})?[,_]?(\.(\d+|{\w+}))?[bcdefgnosx%]?$', re.I)
  382. field_spec = re.compile(r'^(\d+|\w+)(\.\w+|\[[^]]+\])*$')
  383. def _format(self, record):
  384. if defaults := self._defaults:
  385. values = defaults | record.__dict__
  386. else:
  387. values = record.__dict__
  388. return self._fmt.format(**values)
  389. def validate(self):
  390. """Validate the input format, ensure it is the correct string formatting style"""
  391. fields = set()
  392. try:
  393. for _, fieldname, spec, conversion in _str_formatter.parse(self._fmt):
  394. if fieldname:
  395. if not self.field_spec.match(fieldname):
  396. raise ValueError('invalid field name/expression: %r' % fieldname)
  397. fields.add(fieldname)
  398. if conversion and conversion not in 'rsa':
  399. raise ValueError('invalid conversion: %r' % conversion)
  400. if spec and not self.fmt_spec.match(spec):
  401. raise ValueError('bad specifier: %r' % spec)
  402. except ValueError as e:
  403. raise ValueError('invalid format: %s' % e)
  404. if not fields:
  405. raise ValueError('invalid format: no fields')
  406. class StringTemplateStyle(PercentStyle):
  407. default_format = '${message}'
  408. asctime_format = '${asctime}'
  409. asctime_search = '${asctime}'
  410. def __init__(self, *args, **kwargs):
  411. super().__init__(*args, **kwargs)
  412. self._tpl = Template(self._fmt)
  413. def usesTime(self):
  414. fmt = self._fmt
  415. return fmt.find('$asctime') >= 0 or fmt.find(self.asctime_format) >= 0
  416. def validate(self):
  417. pattern = Template.pattern
  418. fields = set()
  419. for m in pattern.finditer(self._fmt):
  420. d = m.groupdict()
  421. if d['named']:
  422. fields.add(d['named'])
  423. elif d['braced']:
  424. fields.add(d['braced'])
  425. elif m.group(0) == '$':
  426. raise ValueError('invalid format: bare \'$\' not allowed')
  427. if not fields:
  428. raise ValueError('invalid format: no fields')
  429. def _format(self, record):
  430. if defaults := self._defaults:
  431. values = defaults | record.__dict__
  432. else:
  433. values = record.__dict__
  434. return self._tpl.substitute(**values)
  435. BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s"
  436. _STYLES = {
  437. '%': (PercentStyle, BASIC_FORMAT),
  438. '{': (StrFormatStyle, '{levelname}:{name}:{message}'),
  439. '$': (StringTemplateStyle, '${levelname}:${name}:${message}'),
  440. }
  441. class Formatter(object):
  442. """
  443. Formatter instances are used to convert a LogRecord to text.
  444. Formatters need to know how a LogRecord is constructed. They are
  445. responsible for converting a LogRecord to (usually) a string which can
  446. be interpreted by either a human or an external system. The base Formatter
  447. allows a formatting string to be specified. If none is supplied, the
  448. style-dependent default value, "%(message)s", "{message}", or
  449. "${message}", is used.
  450. The Formatter can be initialized with a format string which makes use of
  451. knowledge of the LogRecord attributes - e.g. the default value mentioned
  452. above makes use of the fact that the user's message and arguments are pre-
  453. formatted into a LogRecord's message attribute. Currently, the useful
  454. attributes in a LogRecord are described by:
  455. %(name)s Name of the logger (logging channel)
  456. %(levelno)s Numeric logging level for the message (DEBUG, INFO,
  457. WARNING, ERROR, CRITICAL)
  458. %(levelname)s Text logging level for the message ("DEBUG", "INFO",
  459. "WARNING", "ERROR", "CRITICAL")
  460. %(pathname)s Full pathname of the source file where the logging
  461. call was issued (if available)
  462. %(filename)s Filename portion of pathname
  463. %(module)s Module (name portion of filename)
  464. %(lineno)d Source line number where the logging call was issued
  465. (if available)
  466. %(funcName)s Function name
  467. %(created)f Time when the LogRecord was created (time.time()
  468. return value)
  469. %(asctime)s Textual time when the LogRecord was created
  470. %(msecs)d Millisecond portion of the creation time
  471. %(relativeCreated)d Time in milliseconds when the LogRecord was created,
  472. relative to the time the logging module was loaded
  473. (typically at application startup time)
  474. %(thread)d Thread ID (if available)
  475. %(threadName)s Thread name (if available)
  476. %(process)d Process ID (if available)
  477. %(message)s The result of record.getMessage(), computed just as
  478. the record is emitted
  479. """
  480. converter = time.localtime
  481. def __init__(self, fmt=None, datefmt=None, style='%', validate=True, *,
  482. defaults=None):
  483. """
  484. Initialize the formatter with specified format strings.
  485. Initialize the formatter either with the specified format string, or a
  486. default as described above. Allow for specialized date formatting with
  487. the optional datefmt argument. If datefmt is omitted, you get an
  488. ISO8601-like (or RFC 3339-like) format.
  489. Use a style parameter of '%', '{' or '$' to specify that you want to
  490. use one of %-formatting, :meth:`str.format` (``{}``) formatting or
  491. :class:`string.Template` formatting in your format string.
  492. .. versionchanged:: 3.2
  493. Added the ``style`` parameter.
  494. """
  495. if style not in _STYLES:
  496. raise ValueError('Style must be one of: %s' % ','.join(
  497. _STYLES.keys()))
  498. self._style = _STYLES[style][0](fmt, defaults=defaults)
  499. if validate:
  500. self._style.validate()
  501. self._fmt = self._style._fmt
  502. self.datefmt = datefmt
  503. default_time_format = '%Y-%m-%d %H:%M:%S'
  504. default_msec_format = '%s,%03d'
  505. def formatTime(self, record, datefmt=None):
  506. """
  507. Return the creation time of the specified LogRecord as formatted text.
  508. This method should be called from format() by a formatter which
  509. wants to make use of a formatted time. This method can be overridden
  510. in formatters to provide for any specific requirement, but the
  511. basic behaviour is as follows: if datefmt (a string) is specified,
  512. it is used with time.strftime() to format the creation time of the
  513. record. Otherwise, an ISO8601-like (or RFC 3339-like) format is used.
  514. The resulting string is returned. This function uses a user-configurable
  515. function to convert the creation time to a tuple. By default,
  516. time.localtime() is used; to change this for a particular formatter
  517. instance, set the 'converter' attribute to a function with the same
  518. signature as time.localtime() or time.gmtime(). To change it for all
  519. formatters, for example if you want all logging times to be shown in GMT,
  520. set the 'converter' attribute in the Formatter class.
  521. """
  522. ct = self.converter(record.created)
  523. if datefmt:
  524. s = time.strftime(datefmt, ct)
  525. else:
  526. s = time.strftime(self.default_time_format, ct)
  527. if self.default_msec_format:
  528. s = self.default_msec_format % (s, record.msecs)
  529. return s
  530. def formatException(self, ei):
  531. """
  532. Format and return the specified exception information as a string.
  533. This default implementation just uses
  534. traceback.print_exception()
  535. """
  536. sio = io.StringIO()
  537. tb = ei[2]
  538. # See issues #9427, #1553375. Commented out for now.
  539. #if getattr(self, 'fullstack', False):
  540. # traceback.print_stack(tb.tb_frame.f_back, file=sio)
  541. traceback.print_exception(ei[0], ei[1], tb, None, sio)
  542. s = sio.getvalue()
  543. sio.close()
  544. if s[-1:] == "\n":
  545. s = s[:-1]
  546. return s
  547. def usesTime(self):
  548. """
  549. Check if the format uses the creation time of the record.
  550. """
  551. return self._style.usesTime()
  552. def formatMessage(self, record):
  553. return self._style.format(record)
  554. def formatStack(self, stack_info):
  555. """
  556. This method is provided as an extension point for specialized
  557. formatting of stack information.
  558. The input data is a string as returned from a call to
  559. :func:`traceback.print_stack`, but with the last trailing newline
  560. removed.
  561. The base implementation just returns the value passed in.
  562. """
  563. return stack_info
  564. def format(self, record):
  565. """
  566. Format the specified record as text.
  567. The record's attribute dictionary is used as the operand to a
  568. string formatting operation which yields the returned string.
  569. Before formatting the dictionary, a couple of preparatory steps
  570. are carried out. The message attribute of the record is computed
  571. using LogRecord.getMessage(). If the formatting string uses the
  572. time (as determined by a call to usesTime(), formatTime() is
  573. called to format the event time. If there is exception information,
  574. it is formatted using formatException() and appended to the message.
  575. """
  576. record.message = record.getMessage()
  577. if self.usesTime():
  578. record.asctime = self.formatTime(record, self.datefmt)
  579. s = self.formatMessage(record)
  580. if record.exc_info:
  581. # Cache the traceback text to avoid converting it multiple times
  582. # (it's constant anyway)
  583. if not record.exc_text:
  584. record.exc_text = self.formatException(record.exc_info)
  585. if record.exc_text:
  586. if s[-1:] != "\n":
  587. s = s + "\n"
  588. s = s + record.exc_text
  589. if record.stack_info:
  590. if s[-1:] != "\n":
  591. s = s + "\n"
  592. s = s + self.formatStack(record.stack_info)
  593. return s
  594. #
  595. # The default formatter to use when no other is specified
  596. #
  597. _defaultFormatter = Formatter()
  598. class BufferingFormatter(object):
  599. """
  600. A formatter suitable for formatting a number of records.
  601. """
  602. def __init__(self, linefmt=None):
  603. """
  604. Optionally specify a formatter which will be used to format each
  605. individual record.
  606. """
  607. if linefmt:
  608. self.linefmt = linefmt
  609. else:
  610. self.linefmt = _defaultFormatter
  611. def formatHeader(self, records):
  612. """
  613. Return the header string for the specified records.
  614. """
  615. return ""
  616. def formatFooter(self, records):
  617. """
  618. Return the footer string for the specified records.
  619. """
  620. return ""
  621. def format(self, records):
  622. """
  623. Format the specified records and return the result as a string.
  624. """
  625. rv = ""
  626. if len(records) > 0:
  627. rv = rv + self.formatHeader(records)
  628. for record in records:
  629. rv = rv + self.linefmt.format(record)
  630. rv = rv + self.formatFooter(records)
  631. return rv
  632. #---------------------------------------------------------------------------
  633. # Filter classes and functions
  634. #---------------------------------------------------------------------------
  635. class Filter(object):
  636. """
  637. Filter instances are used to perform arbitrary filtering of LogRecords.
  638. Loggers and Handlers can optionally use Filter instances to filter
  639. records as desired. The base filter class only allows events which are
  640. below a certain point in the logger hierarchy. For example, a filter
  641. initialized with "A.B" will allow events logged by loggers "A.B",
  642. "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
  643. initialized with the empty string, all events are passed.
  644. """
  645. def __init__(self, name=''):
  646. """
  647. Initialize a filter.
  648. Initialize with the name of the logger which, together with its
  649. children, will have its events allowed through the filter. If no
  650. name is specified, allow every event.
  651. """
  652. self.name = name
  653. self.nlen = len(name)
  654. def filter(self, record):
  655. """
  656. Determine if the specified record is to be logged.
  657. Returns True if the record should be logged, or False otherwise.
  658. If deemed appropriate, the record may be modified in-place.
  659. """
  660. if self.nlen == 0:
  661. return True
  662. elif self.name == record.name:
  663. return True
  664. elif record.name.find(self.name, 0, self.nlen) != 0:
  665. return False
  666. return (record.name[self.nlen] == ".")
  667. class Filterer(object):
  668. """
  669. A base class for loggers and handlers which allows them to share
  670. common code.
  671. """
  672. def __init__(self):
  673. """
  674. Initialize the list of filters to be an empty list.
  675. """
  676. self.filters = []
  677. def addFilter(self, filter):
  678. """
  679. Add the specified filter to this handler.
  680. """
  681. if not (filter in self.filters):
  682. self.filters.append(filter)
  683. def removeFilter(self, filter):
  684. """
  685. Remove the specified filter from this handler.
  686. """
  687. if filter in self.filters:
  688. self.filters.remove(filter)
  689. def filter(self, record):
  690. """
  691. Determine if a record is loggable by consulting all the filters.
  692. The default is to allow the record to be logged; any filter can veto
  693. this and the record is then dropped. Returns a zero value if a record
  694. is to be dropped, else non-zero.
  695. .. versionchanged:: 3.2
  696. Allow filters to be just callables.
  697. """
  698. rv = True
  699. for f in self.filters:
  700. if hasattr(f, 'filter'):
  701. result = f.filter(record)
  702. else:
  703. result = f(record) # assume callable - will raise if not
  704. if not result:
  705. rv = False
  706. break
  707. return rv
  708. #---------------------------------------------------------------------------
  709. # Handler classes and functions
  710. #---------------------------------------------------------------------------
  711. _handlers = weakref.WeakValueDictionary() #map of handler names to handlers
  712. _handlerList = [] # added to allow handlers to be removed in reverse of order initialized
  713. def _removeHandlerRef(wr):
  714. """
  715. Remove a handler reference from the internal cleanup list.
  716. """
  717. # This function can be called during module teardown, when globals are
  718. # set to None. It can also be called from another thread. So we need to
  719. # pre-emptively grab the necessary globals and check if they're None,
  720. # to prevent race conditions and failures during interpreter shutdown.
  721. acquire, release, handlers = _acquireLock, _releaseLock, _handlerList
  722. if acquire and release and handlers:
  723. acquire()
  724. try:
  725. if wr in handlers:
  726. handlers.remove(wr)
  727. finally:
  728. release()
  729. def _addHandlerRef(handler):
  730. """
  731. Add a handler to the internal cleanup list using a weak reference.
  732. """
  733. _acquireLock()
  734. try:
  735. _handlerList.append(weakref.ref(handler, _removeHandlerRef))
  736. finally:
  737. _releaseLock()
  738. class Handler(Filterer):
  739. """
  740. Handler instances dispatch logging events to specific destinations.
  741. The base handler class. Acts as a placeholder which defines the Handler
  742. interface. Handlers can optionally use Formatter instances to format
  743. records as desired. By default, no formatter is specified; in this case,
  744. the 'raw' message as determined by record.message is logged.
  745. """
  746. def __init__(self, level=NOTSET):
  747. """
  748. Initializes the instance - basically setting the formatter to None
  749. and the filter list to empty.
  750. """
  751. Filterer.__init__(self)
  752. self._name = None
  753. self.level = _checkLevel(level)
  754. self.formatter = None
  755. # Add the handler to the global _handlerList (for cleanup on shutdown)
  756. _addHandlerRef(self)
  757. self.createLock()
  758. def get_name(self):
  759. return self._name
  760. def set_name(self, name):
  761. _acquireLock()
  762. try:
  763. if self._name in _handlers:
  764. del _handlers[self._name]
  765. self._name = name
  766. if name:
  767. _handlers[name] = self
  768. finally:
  769. _releaseLock()
  770. name = property(get_name, set_name)
  771. def createLock(self):
  772. """
  773. Acquire a thread lock for serializing access to the underlying I/O.
  774. """
  775. self.lock = threading.RLock()
  776. _register_at_fork_reinit_lock(self)
  777. def _at_fork_reinit(self):
  778. self.lock._at_fork_reinit()
  779. def acquire(self):
  780. """
  781. Acquire the I/O thread lock.
  782. """
  783. if self.lock:
  784. self.lock.acquire()
  785. def release(self):
  786. """
  787. Release the I/O thread lock.
  788. """
  789. if self.lock:
  790. self.lock.release()
  791. def setLevel(self, level):
  792. """
  793. Set the logging level of this handler. level must be an int or a str.
  794. """
  795. self.level = _checkLevel(level)
  796. def format(self, record):
  797. """
  798. Format the specified record.
  799. If a formatter is set, use it. Otherwise, use the default formatter
  800. for the module.
  801. """
  802. if self.formatter:
  803. fmt = self.formatter
  804. else:
  805. fmt = _defaultFormatter
  806. return fmt.format(record)
  807. def emit(self, record):
  808. """
  809. Do whatever it takes to actually log the specified logging record.
  810. This version is intended to be implemented by subclasses and so
  811. raises a NotImplementedError.
  812. """
  813. raise NotImplementedError('emit must be implemented '
  814. 'by Handler subclasses')
  815. def handle(self, record):
  816. """
  817. Conditionally emit the specified logging record.
  818. Emission depends on filters which may have been added to the handler.
  819. Wrap the actual emission of the record with acquisition/release of
  820. the I/O thread lock. Returns whether the filter passed the record for
  821. emission.
  822. """
  823. rv = self.filter(record)
  824. if rv:
  825. self.acquire()
  826. try:
  827. self.emit(record)
  828. finally:
  829. self.release()
  830. return rv
  831. def setFormatter(self, fmt):
  832. """
  833. Set the formatter for this handler.
  834. """
  835. self.formatter = fmt
  836. def flush(self):
  837. """
  838. Ensure all logging output has been flushed.
  839. This version does nothing and is intended to be implemented by
  840. subclasses.
  841. """
  842. pass
  843. def close(self):
  844. """
  845. Tidy up any resources used by the handler.
  846. This version removes the handler from an internal map of handlers,
  847. _handlers, which is used for handler lookup by name. Subclasses
  848. should ensure that this gets called from overridden close()
  849. methods.
  850. """
  851. #get the module data lock, as we're updating a shared structure.
  852. _acquireLock()
  853. try: #unlikely to raise an exception, but you never know...
  854. if self._name and self._name in _handlers:
  855. del _handlers[self._name]
  856. finally:
  857. _releaseLock()
  858. def handleError(self, record):
  859. """
  860. Handle errors which occur during an emit() call.
  861. This method should be called from handlers when an exception is
  862. encountered during an emit() call. If raiseExceptions is false,
  863. exceptions get silently ignored. This is what is mostly wanted
  864. for a logging system - most users will not care about errors in
  865. the logging system, they are more interested in application errors.
  866. You could, however, replace this with a custom handler if you wish.
  867. The record which was being processed is passed in to this method.
  868. """
  869. if raiseExceptions and sys.stderr: # see issue 13807
  870. t, v, tb = sys.exc_info()
  871. try:
  872. sys.stderr.write('--- Logging error ---\n')
  873. traceback.print_exception(t, v, tb, None, sys.stderr)
  874. sys.stderr.write('Call stack:\n')
  875. # Walk the stack frame up until we're out of logging,
  876. # so as to print the calling context.
  877. frame = tb.tb_frame
  878. while (frame and os.path.dirname(frame.f_code.co_filename) ==
  879. __path__[0]):
  880. frame = frame.f_back
  881. if frame:
  882. traceback.print_stack(frame, file=sys.stderr)
  883. else:
  884. # couldn't find the right stack frame, for some reason
  885. sys.stderr.write('Logged from file %s, line %s\n' % (
  886. record.filename, record.lineno))
  887. # Issue 18671: output logging message and arguments
  888. try:
  889. sys.stderr.write('Message: %r\n'
  890. 'Arguments: %s\n' % (record.msg,
  891. record.args))
  892. except RecursionError: # See issue 36272
  893. raise
  894. except Exception:
  895. sys.stderr.write('Unable to print the message and arguments'
  896. ' - possible formatting error.\nUse the'
  897. ' traceback above to help find the error.\n'
  898. )
  899. except OSError: #pragma: no cover
  900. pass # see issue 5971
  901. finally:
  902. del t, v, tb
  903. def __repr__(self):
  904. level = getLevelName(self.level)
  905. return '<%s (%s)>' % (self.__class__.__name__, level)
  906. class StreamHandler(Handler):
  907. """
  908. A handler class which writes logging records, appropriately formatted,
  909. to a stream. Note that this class does not close the stream, as
  910. sys.stdout or sys.stderr may be used.
  911. """
  912. terminator = '\n'
  913. def __init__(self, stream=None):
  914. """
  915. Initialize the handler.
  916. If stream is not specified, sys.stderr is used.
  917. """
  918. Handler.__init__(self)
  919. if stream is None:
  920. stream = sys.stderr
  921. self.stream = stream
  922. def flush(self):
  923. """
  924. Flushes the stream.
  925. """
  926. self.acquire()
  927. try:
  928. if self.stream and hasattr(self.stream, "flush"):
  929. self.stream.flush()
  930. finally:
  931. self.release()
  932. def emit(self, record):
  933. """
  934. Emit a record.
  935. If a formatter is specified, it is used to format the record.
  936. The record is then written to the stream with a trailing newline. If
  937. exception information is present, it is formatted using
  938. traceback.print_exception and appended to the stream. If the stream
  939. has an 'encoding' attribute, it is used to determine how to do the
  940. output to the stream.
  941. """
  942. try:
  943. msg = self.format(record)
  944. stream = self.stream
  945. # issue 35046: merged two stream.writes into one.
  946. stream.write(msg + self.terminator)
  947. self.flush()
  948. except RecursionError: # See issue 36272
  949. raise
  950. except Exception:
  951. self.handleError(record)
  952. def setStream(self, stream):
  953. """
  954. Sets the StreamHandler's stream to the specified value,
  955. if it is different.
  956. Returns the old stream, if the stream was changed, or None
  957. if it wasn't.
  958. """
  959. if stream is self.stream:
  960. result = None
  961. else:
  962. result = self.stream
  963. self.acquire()
  964. try:
  965. self.flush()
  966. self.stream = stream
  967. finally:
  968. self.release()
  969. return result
  970. def __repr__(self):
  971. level = getLevelName(self.level)
  972. name = getattr(self.stream, 'name', '')
  973. # bpo-36015: name can be an int
  974. name = str(name)
  975. if name:
  976. name += ' '
  977. return '<%s %s(%s)>' % (self.__class__.__name__, name, level)
  978. class FileHandler(StreamHandler):
  979. """
  980. A handler class which writes formatted logging records to disk files.
  981. """
  982. def __init__(self, filename, mode='a', encoding=None, delay=False, errors=None):
  983. """
  984. Open the specified file and use it as the stream for logging.
  985. """
  986. # Issue #27493: add support for Path objects to be passed in
  987. filename = os.fspath(filename)
  988. #keep the absolute path, otherwise derived classes which use this
  989. #may come a cropper when the current directory changes
  990. self.baseFilename = os.path.abspath(filename)
  991. self.mode = mode
  992. self.encoding = encoding
  993. if "b" not in mode:
  994. self.encoding = io.text_encoding(encoding)
  995. self.errors = errors
  996. self.delay = delay
  997. # bpo-26789: FileHandler keeps a reference to the builtin open()
  998. # function to be able to open or reopen the file during Python
  999. # finalization.
  1000. self._builtin_open = open
  1001. if delay:
  1002. #We don't open the stream, but we still need to call the
  1003. #Handler constructor to set level, formatter, lock etc.
  1004. Handler.__init__(self)
  1005. self.stream = None
  1006. else:
  1007. StreamHandler.__init__(self, self._open())
  1008. def close(self):
  1009. """
  1010. Closes the stream.
  1011. """
  1012. self.acquire()
  1013. try:
  1014. try:
  1015. if self.stream:
  1016. try:
  1017. self.flush()
  1018. finally:
  1019. stream = self.stream
  1020. self.stream = None
  1021. if hasattr(stream, "close"):
  1022. stream.close()
  1023. finally:
  1024. # Issue #19523: call unconditionally to
  1025. # prevent a handler leak when delay is set
  1026. StreamHandler.close(self)
  1027. finally:
  1028. self.release()
  1029. def _open(self):
  1030. """
  1031. Open the current base file with the (original) mode and encoding.
  1032. Return the resulting stream.
  1033. """
  1034. open_func = self._builtin_open
  1035. return open_func(self.baseFilename, self.mode,
  1036. encoding=self.encoding, errors=self.errors)
  1037. def emit(self, record):
  1038. """
  1039. Emit a record.
  1040. If the stream was not opened because 'delay' was specified in the
  1041. constructor, open it before calling the superclass's emit.
  1042. """
  1043. if self.stream is None:
  1044. self.stream = self._open()
  1045. StreamHandler.emit(self, record)
  1046. def __repr__(self):
  1047. level = getLevelName(self.level)
  1048. return '<%s %s (%s)>' % (self.__class__.__name__, self.baseFilename, level)
  1049. class _StderrHandler(StreamHandler):
  1050. """
  1051. This class is like a StreamHandler using sys.stderr, but always uses
  1052. whatever sys.stderr is currently set to rather than the value of
  1053. sys.stderr at handler construction time.
  1054. """
  1055. def __init__(self, level=NOTSET):
  1056. """
  1057. Initialize the handler.
  1058. """
  1059. Handler.__init__(self, level)
  1060. @property
  1061. def stream(self):
  1062. return sys.stderr
  1063. _defaultLastResort = _StderrHandler(WARNING)
  1064. lastResort = _defaultLastResort
  1065. #---------------------------------------------------------------------------
  1066. # Manager classes and functions
  1067. #---------------------------------------------------------------------------
  1068. class PlaceHolder(object):
  1069. """
  1070. PlaceHolder instances are used in the Manager logger hierarchy to take
  1071. the place of nodes for which no loggers have been defined. This class is
  1072. intended for internal use only and not as part of the public API.
  1073. """
  1074. def __init__(self, alogger):
  1075. """
  1076. Initialize with the specified logger being a child of this placeholder.
  1077. """
  1078. self.loggerMap = { alogger : None }
  1079. def append(self, alogger):
  1080. """
  1081. Add the specified logger as a child of this placeholder.
  1082. """
  1083. if alogger not in self.loggerMap:
  1084. self.loggerMap[alogger] = None
  1085. #
  1086. # Determine which class to use when instantiating loggers.
  1087. #
  1088. def setLoggerClass(klass):
  1089. """
  1090. Set the class to be used when instantiating a logger. The class should
  1091. define __init__() such that only a name argument is required, and the
  1092. __init__() should call Logger.__init__()
  1093. """
  1094. if klass != Logger:
  1095. if not issubclass(klass, Logger):
  1096. raise TypeError("logger not derived from logging.Logger: "
  1097. + klass.__name__)
  1098. global _loggerClass
  1099. _loggerClass = klass
  1100. def getLoggerClass():
  1101. """
  1102. Return the class to be used when instantiating a logger.
  1103. """
  1104. return _loggerClass
  1105. class Manager(object):
  1106. """
  1107. There is [under normal circumstances] just one Manager instance, which
  1108. holds the hierarchy of loggers.
  1109. """
  1110. def __init__(self, rootnode):
  1111. """
  1112. Initialize the manager with the root node of the logger hierarchy.
  1113. """
  1114. self.root = rootnode
  1115. self.disable = 0
  1116. self.emittedNoHandlerWarning = False
  1117. self.loggerDict = {}
  1118. self.loggerClass = None
  1119. self.logRecordFactory = None
  1120. @property
  1121. def disable(self):
  1122. return self._disable
  1123. @disable.setter
  1124. def disable(self, value):
  1125. self._disable = _checkLevel(value)
  1126. def getLogger(self, name):
  1127. """
  1128. Get a logger with the specified name (channel name), creating it
  1129. if it doesn't yet exist. This name is a dot-separated hierarchical
  1130. name, such as "a", "a.b", "a.b.c" or similar.
  1131. If a PlaceHolder existed for the specified name [i.e. the logger
  1132. didn't exist but a child of it did], replace it with the created
  1133. logger and fix up the parent/child references which pointed to the
  1134. placeholder to now point to the logger.
  1135. """
  1136. rv = None
  1137. if not isinstance(name, str):
  1138. raise TypeError('A logger name must be a string')
  1139. _acquireLock()
  1140. try:
  1141. if name in self.loggerDict:
  1142. rv = self.loggerDict[name]
  1143. if isinstance(rv, PlaceHolder):
  1144. ph = rv
  1145. rv = (self.loggerClass or _loggerClass)(name)
  1146. rv.manager = self
  1147. self.loggerDict[name] = rv
  1148. self._fixupChildren(ph, rv)
  1149. self._fixupParents(rv)
  1150. else:
  1151. rv = (self.loggerClass or _loggerClass)(name)
  1152. rv.manager = self
  1153. self.loggerDict[name] = rv
  1154. self._fixupParents(rv)
  1155. finally:
  1156. _releaseLock()
  1157. return rv
  1158. def setLoggerClass(self, klass):
  1159. """
  1160. Set the class to be used when instantiating a logger with this Manager.
  1161. """
  1162. if klass != Logger:
  1163. if not issubclass(klass, Logger):
  1164. raise TypeError("logger not derived from logging.Logger: "
  1165. + klass.__name__)
  1166. self.loggerClass = klass
  1167. def setLogRecordFactory(self, factory):
  1168. """
  1169. Set the factory to be used when instantiating a log record with this
  1170. Manager.
  1171. """
  1172. self.logRecordFactory = factory
  1173. def _fixupParents(self, alogger):
  1174. """
  1175. Ensure that there are either loggers or placeholders all the way
  1176. from the specified logger to the root of the logger hierarchy.
  1177. """
  1178. name = alogger.name
  1179. i = name.rfind(".")
  1180. rv = None
  1181. while (i > 0) and not rv:
  1182. substr = name[:i]
  1183. if substr not in self.loggerDict:
  1184. self.loggerDict[substr] = PlaceHolder(alogger)
  1185. else:
  1186. obj = self.loggerDict[substr]
  1187. if isinstance(obj, Logger):
  1188. rv = obj
  1189. else:
  1190. assert isinstance(obj, PlaceHolder)
  1191. obj.append(alogger)
  1192. i = name.rfind(".", 0, i - 1)
  1193. if not rv:
  1194. rv = self.root
  1195. alogger.parent = rv
  1196. def _fixupChildren(self, ph, alogger):
  1197. """
  1198. Ensure that children of the placeholder ph are connected to the
  1199. specified logger.
  1200. """
  1201. name = alogger.name
  1202. namelen = len(name)
  1203. for c in ph.loggerMap.keys():
  1204. #The if means ... if not c.parent.name.startswith(nm)
  1205. if c.parent.name[:namelen] != name:
  1206. alogger.parent = c.parent
  1207. c.parent = alogger
  1208. def _clear_cache(self):
  1209. """
  1210. Clear the cache for all loggers in loggerDict
  1211. Called when level changes are made
  1212. """
  1213. _acquireLock()
  1214. for logger in self.loggerDict.values():
  1215. if isinstance(logger, Logger):
  1216. logger._cache.clear()
  1217. self.root._cache.clear()
  1218. _releaseLock()
  1219. #---------------------------------------------------------------------------
  1220. # Logger classes and functions
  1221. #---------------------------------------------------------------------------
  1222. class Logger(Filterer):
  1223. """
  1224. Instances of the Logger class represent a single logging channel. A
  1225. "logging channel" indicates an area of an application. Exactly how an
  1226. "area" is defined is up to the application developer. Since an
  1227. application can have any number of areas, logging channels are identified
  1228. by a unique string. Application areas can be nested (e.g. an area
  1229. of "input processing" might include sub-areas "read CSV files", "read
  1230. XLS files" and "read Gnumeric files"). To cater for this natural nesting,
  1231. channel names are organized into a namespace hierarchy where levels are
  1232. separated by periods, much like the Java or Python package namespace. So
  1233. in the instance given above, channel names might be "input" for the upper
  1234. level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels.
  1235. There is no arbitrary limit to the depth of nesting.
  1236. """
  1237. def __init__(self, name, level=NOTSET):
  1238. """
  1239. Initialize the logger with a name and an optional level.
  1240. """
  1241. Filterer.__init__(self)
  1242. self.name = name
  1243. self.level = _checkLevel(level)
  1244. self.parent = None
  1245. self.propagate = True
  1246. self.handlers = []
  1247. self.disabled = False
  1248. self._cache = {}
  1249. def setLevel(self, level):
  1250. """
  1251. Set the logging level of this logger. level must be an int or a str.
  1252. """
  1253. self.level = _checkLevel(level)
  1254. self.manager._clear_cache()
  1255. def debug(self, msg, *args, **kwargs):
  1256. """
  1257. Log 'msg % args' with severity 'DEBUG'.
  1258. To pass exception information, use the keyword argument exc_info with
  1259. a true value, e.g.
  1260. logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
  1261. """
  1262. if self.isEnabledFor(DEBUG):
  1263. self._log(DEBUG, msg, args, **kwargs)
  1264. def info(self, msg, *args, **kwargs):
  1265. """
  1266. Log 'msg % args' with severity 'INFO'.
  1267. To pass exception information, use the keyword argument exc_info with
  1268. a true value, e.g.
  1269. logger.info("Houston, we have a %s", "interesting problem", exc_info=1)
  1270. """
  1271. if self.isEnabledFor(INFO):
  1272. self._log(INFO, msg, args, **kwargs)
  1273. def warning(self, msg, *args, **kwargs):
  1274. """
  1275. Log 'msg % args' with severity 'WARNING'.
  1276. To pass exception information, use the keyword argument exc_info with
  1277. a true value, e.g.
  1278. logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)
  1279. """
  1280. if self.isEnabledFor(WARNING):
  1281. self._log(WARNING, msg, args, **kwargs)
  1282. def warn(self, msg, *args, **kwargs):
  1283. warnings.warn("The 'warn' method is deprecated, "
  1284. "use 'warning' instead", DeprecationWarning, 2)
  1285. self.warning(msg, *args, **kwargs)
  1286. def error(self, msg, *args, **kwargs):
  1287. """
  1288. Log 'msg % args' with severity 'ERROR'.
  1289. To pass exception information, use the keyword argument exc_info with
  1290. a true value, e.g.
  1291. logger.error("Houston, we have a %s", "major problem", exc_info=1)
  1292. """
  1293. if self.isEnabledFor(ERROR):
  1294. self._log(ERROR, msg, args, **kwargs)
  1295. def exception(self, msg, *args, exc_info=True, **kwargs):
  1296. """
  1297. Convenience method for logging an ERROR with exception information.
  1298. """
  1299. self.error(msg, *args, exc_info=exc_info, **kwargs)
  1300. def critical(self, msg, *args, **kwargs):
  1301. """
  1302. Log 'msg % args' with severity 'CRITICAL'.
  1303. To pass exception information, use the keyword argument exc_info with
  1304. a true value, e.g.
  1305. logger.critical("Houston, we have a %s", "major disaster", exc_info=1)
  1306. """
  1307. if self.isEnabledFor(CRITICAL):
  1308. self._log(CRITICAL, msg, args, **kwargs)
  1309. def fatal(self, msg, *args, **kwargs):
  1310. """
  1311. Don't use this method, use critical() instead.
  1312. """
  1313. self.critical(msg, *args, **kwargs)
  1314. def log(self, level, msg, *args, **kwargs):
  1315. """
  1316. Log 'msg % args' with the integer severity 'level'.
  1317. To pass exception information, use the keyword argument exc_info with
  1318. a true value, e.g.
  1319. logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
  1320. """
  1321. if not isinstance(level, int):
  1322. if raiseExceptions:
  1323. raise TypeError("level must be an integer")
  1324. else:
  1325. return
  1326. if self.isEnabledFor(level):
  1327. self._log(level, msg, args, **kwargs)
  1328. def findCaller(self, stack_info=False, stacklevel=1):
  1329. """
  1330. Find the stack frame of the caller so that we can note the source
  1331. file name, line number and function name.
  1332. """
  1333. f = currentframe()
  1334. #On some versions of IronPython, currentframe() returns None if
  1335. #IronPython isn't run with -X:Frames.
  1336. if f is not None:
  1337. f = f.f_back
  1338. orig_f = f
  1339. while f and stacklevel > 1:
  1340. f = f.f_back
  1341. stacklevel -= 1
  1342. if not f:
  1343. f = orig_f
  1344. rv = "(unknown file)", 0, "(unknown function)", None
  1345. while hasattr(f, "f_code"):
  1346. co = f.f_code
  1347. filename = os.path.normcase(co.co_filename)
  1348. if filename == _srcfile:
  1349. f = f.f_back
  1350. continue
  1351. sinfo = None
  1352. if stack_info:
  1353. sio = io.StringIO()
  1354. sio.write('Stack (most recent call last):\n')
  1355. traceback.print_stack(f, file=sio)
  1356. sinfo = sio.getvalue()
  1357. if sinfo[-1] == '\n':
  1358. sinfo = sinfo[:-1]
  1359. sio.close()
  1360. rv = (co.co_filename, f.f_lineno, co.co_name, sinfo)
  1361. break
  1362. return rv
  1363. def makeRecord(self, name, level, fn, lno, msg, args, exc_info,
  1364. func=None, extra=None, sinfo=None):
  1365. """
  1366. A factory method which can be overridden in subclasses to create
  1367. specialized LogRecords.
  1368. """
  1369. rv = _logRecordFactory(name, level, fn, lno, msg, args, exc_info, func,
  1370. sinfo)
  1371. if extra is not None:
  1372. for key in extra:
  1373. if (key in ["message", "asctime"]) or (key in rv.__dict__):
  1374. raise KeyError("Attempt to overwrite %r in LogRecord" % key)
  1375. rv.__dict__[key] = extra[key]
  1376. return rv
  1377. def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False,
  1378. stacklevel=1):
  1379. """
  1380. Low-level logging routine which creates a LogRecord and then calls
  1381. all the handlers of this logger to handle the record.
  1382. """
  1383. sinfo = None
  1384. if _srcfile:
  1385. #IronPython doesn't track Python frames, so findCaller raises an
  1386. #exception on some versions of IronPython. We trap it here so that
  1387. #IronPython can use logging.
  1388. try:
  1389. fn, lno, func, sinfo = self.findCaller(stack_info, stacklevel)
  1390. except ValueError: # pragma: no cover
  1391. fn, lno, func = "(unknown file)", 0, "(unknown function)"
  1392. else: # pragma: no cover
  1393. fn, lno, func = "(unknown file)", 0, "(unknown function)"
  1394. if exc_info:
  1395. if isinstance(exc_info, BaseException):
  1396. exc_info = (type(exc_info), exc_info, exc_info.__traceback__)
  1397. elif not isinstance(exc_info, tuple):
  1398. exc_info = sys.exc_info()
  1399. record = self.makeRecord(self.name, level, fn, lno, msg, args,
  1400. exc_info, func, extra, sinfo)
  1401. self.handle(record)
  1402. def handle(self, record):
  1403. """
  1404. Call the handlers for the specified record.
  1405. This method is used for unpickled records received from a socket, as
  1406. well as those created locally. Logger-level filtering is applied.
  1407. """
  1408. if (not self.disabled) and self.filter(record):
  1409. self.callHandlers(record)
  1410. def addHandler(self, hdlr):
  1411. """
  1412. Add the specified handler to this logger.
  1413. """
  1414. _acquireLock()
  1415. try:
  1416. if not (hdlr in self.handlers):
  1417. self.handlers.append(hdlr)
  1418. finally:
  1419. _releaseLock()
  1420. def removeHandler(self, hdlr):
  1421. """
  1422. Remove the specified handler from this logger.
  1423. """
  1424. _acquireLock()
  1425. try:
  1426. if hdlr in self.handlers:
  1427. self.handlers.remove(hdlr)
  1428. finally:
  1429. _releaseLock()
  1430. def hasHandlers(self):
  1431. """
  1432. See if this logger has any handlers configured.
  1433. Loop through all handlers for this logger and its parents in the
  1434. logger hierarchy. Return True if a handler was found, else False.
  1435. Stop searching up the hierarchy whenever a logger with the "propagate"
  1436. attribute set to zero is found - that will be the last logger which
  1437. is checked for the existence of handlers.
  1438. """
  1439. c = self
  1440. rv = False
  1441. while c:
  1442. if c.handlers:
  1443. rv = True
  1444. break
  1445. if not c.propagate:
  1446. break
  1447. else:
  1448. c = c.parent
  1449. return rv
  1450. def callHandlers(self, record):
  1451. """
  1452. Pass a record to all relevant handlers.
  1453. Loop through all handlers for this logger and its parents in the
  1454. logger hierarchy. If no handler was found, output a one-off error
  1455. message to sys.stderr. Stop searching up the hierarchy whenever a
  1456. logger with the "propagate" attribute set to zero is found - that
  1457. will be the last logger whose handlers are called.
  1458. """
  1459. c = self
  1460. found = 0
  1461. while c:
  1462. for hdlr in c.handlers:
  1463. found = found + 1
  1464. if record.levelno >= hdlr.level:
  1465. hdlr.handle(record)
  1466. if not c.propagate:
  1467. c = None #break out
  1468. else:
  1469. c = c.parent
  1470. if (found == 0):
  1471. if lastResort:
  1472. if record.levelno >= lastResort.level:
  1473. lastResort.handle(record)
  1474. elif raiseExceptions and not self.manager.emittedNoHandlerWarning:
  1475. sys.stderr.write("No handlers could be found for logger"
  1476. " \"%s\"\n" % self.name)
  1477. self.manager.emittedNoHandlerWarning = True
  1478. def getEffectiveLevel(self):
  1479. """
  1480. Get the effective level for this logger.
  1481. Loop through this logger and its parents in the logger hierarchy,
  1482. looking for a non-zero logging level. Return the first one found.
  1483. """
  1484. logger = self
  1485. while logger:
  1486. if logger.level:
  1487. return logger.level
  1488. logger = logger.parent
  1489. return NOTSET
  1490. def isEnabledFor(self, level):
  1491. """
  1492. Is this logger enabled for level 'level'?
  1493. """
  1494. if self.disabled:
  1495. return False
  1496. try:
  1497. return self._cache[level]
  1498. except KeyError:
  1499. _acquireLock()
  1500. try:
  1501. if self.manager.disable >= level:
  1502. is_enabled = self._cache[level] = False
  1503. else:
  1504. is_enabled = self._cache[level] = (
  1505. level >= self.getEffectiveLevel()
  1506. )
  1507. finally:
  1508. _releaseLock()
  1509. return is_enabled
  1510. def getChild(self, suffix):
  1511. """
  1512. Get a logger which is a descendant to this one.
  1513. This is a convenience method, such that
  1514. logging.getLogger('abc').getChild('def.ghi')
  1515. is the same as
  1516. logging.getLogger('abc.def.ghi')
  1517. It's useful, for example, when the parent logger is named using
  1518. __name__ rather than a literal string.
  1519. """
  1520. if self.root is not self:
  1521. suffix = '.'.join((self.name, suffix))
  1522. return self.manager.getLogger(suffix)
  1523. def __repr__(self):
  1524. level = getLevelName(self.getEffectiveLevel())
  1525. return '<%s %s (%s)>' % (self.__class__.__name__, self.name, level)
  1526. def __reduce__(self):
  1527. # In general, only the root logger will not be accessible via its name.
  1528. # However, the root logger's class has its own __reduce__ method.
  1529. if getLogger(self.name) is not self:
  1530. import pickle
  1531. raise pickle.PicklingError('logger cannot be pickled')
  1532. return getLogger, (self.name,)
  1533. class RootLogger(Logger):
  1534. """
  1535. A root logger is not that different to any other logger, except that
  1536. it must have a logging level and there is only one instance of it in
  1537. the hierarchy.
  1538. """
  1539. def __init__(self, level):
  1540. """
  1541. Initialize the logger with the name "root".
  1542. """
  1543. Logger.__init__(self, "root", level)
  1544. def __reduce__(self):
  1545. return getLogger, ()
  1546. _loggerClass = Logger
  1547. class LoggerAdapter(object):
  1548. """
  1549. An adapter for loggers which makes it easier to specify contextual
  1550. information in logging output.
  1551. """
  1552. def __init__(self, logger, extra=None):
  1553. """
  1554. Initialize the adapter with a logger and a dict-like object which
  1555. provides contextual information. This constructor signature allows
  1556. easy stacking of LoggerAdapters, if so desired.
  1557. You can effectively pass keyword arguments as shown in the
  1558. following example:
  1559. adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2"))
  1560. """
  1561. self.logger = logger
  1562. self.extra = extra
  1563. def process(self, msg, kwargs):
  1564. """
  1565. Process the logging message and keyword arguments passed in to
  1566. a logging call to insert contextual information. You can either
  1567. manipulate the message itself, the keyword args or both. Return
  1568. the message and kwargs modified (or not) to suit your needs.
  1569. Normally, you'll only need to override this one method in a
  1570. LoggerAdapter subclass for your specific needs.
  1571. """
  1572. kwargs["extra"] = self.extra
  1573. return msg, kwargs
  1574. #
  1575. # Boilerplate convenience methods
  1576. #
  1577. def debug(self, msg, *args, **kwargs):
  1578. """
  1579. Delegate a debug call to the underlying logger.
  1580. """
  1581. self.log(DEBUG, msg, *args, **kwargs)
  1582. def info(self, msg, *args, **kwargs):
  1583. """
  1584. Delegate an info call to the underlying logger.
  1585. """
  1586. self.log(INFO, msg, *args, **kwargs)
  1587. def warning(self, msg, *args, **kwargs):
  1588. """
  1589. Delegate a warning call to the underlying logger.
  1590. """
  1591. self.log(WARNING, msg, *args, **kwargs)
  1592. def warn(self, msg, *args, **kwargs):
  1593. warnings.warn("The 'warn' method is deprecated, "
  1594. "use 'warning' instead", DeprecationWarning, 2)
  1595. self.warning(msg, *args, **kwargs)
  1596. def error(self, msg, *args, **kwargs):
  1597. """
  1598. Delegate an error call to the underlying logger.
  1599. """
  1600. self.log(ERROR, msg, *args, **kwargs)
  1601. def exception(self, msg, *args, exc_info=True, **kwargs):
  1602. """
  1603. Delegate an exception call to the underlying logger.
  1604. """
  1605. self.log(ERROR, msg, *args, exc_info=exc_info, **kwargs)
  1606. def critical(self, msg, *args, **kwargs):
  1607. """
  1608. Delegate a critical call to the underlying logger.
  1609. """
  1610. self.log(CRITICAL, msg, *args, **kwargs)
  1611. def log(self, level, msg, *args, **kwargs):
  1612. """
  1613. Delegate a log call to the underlying logger, after adding
  1614. contextual information from this adapter instance.
  1615. """
  1616. if self.isEnabledFor(level):
  1617. msg, kwargs = self.process(msg, kwargs)
  1618. self.logger.log(level, msg, *args, **kwargs)
  1619. def isEnabledFor(self, level):
  1620. """
  1621. Is this logger enabled for level 'level'?
  1622. """
  1623. return self.logger.isEnabledFor(level)
  1624. def setLevel(self, level):
  1625. """
  1626. Set the specified level on the underlying logger.
  1627. """
  1628. self.logger.setLevel(level)
  1629. def getEffectiveLevel(self):
  1630. """
  1631. Get the effective level for the underlying logger.
  1632. """
  1633. return self.logger.getEffectiveLevel()
  1634. def hasHandlers(self):
  1635. """
  1636. See if the underlying logger has any handlers.
  1637. """
  1638. return self.logger.hasHandlers()
  1639. def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False):
  1640. """
  1641. Low-level log implementation, proxied to allow nested logger adapters.
  1642. """
  1643. return self.logger._log(
  1644. level,
  1645. msg,
  1646. args,
  1647. exc_info=exc_info,
  1648. extra=extra,
  1649. stack_info=stack_info,
  1650. )
  1651. @property
  1652. def manager(self):
  1653. return self.logger.manager
  1654. @manager.setter
  1655. def manager(self, value):
  1656. self.logger.manager = value
  1657. @property
  1658. def name(self):
  1659. return self.logger.name
  1660. def __repr__(self):
  1661. logger = self.logger
  1662. level = getLevelName(logger.getEffectiveLevel())
  1663. return '<%s %s (%s)>' % (self.__class__.__name__, logger.name, level)
  1664. root = RootLogger(WARNING)
  1665. Logger.root = root
  1666. Logger.manager = Manager(Logger.root)
  1667. #---------------------------------------------------------------------------
  1668. # Configuration classes and functions
  1669. #---------------------------------------------------------------------------
  1670. def basicConfig(**kwargs):
  1671. """
  1672. Do basic configuration for the logging system.
  1673. This function does nothing if the root logger already has handlers
  1674. configured, unless the keyword argument *force* is set to ``True``.
  1675. It is a convenience method intended for use by simple scripts
  1676. to do one-shot configuration of the logging package.
  1677. The default behaviour is to create a StreamHandler which writes to
  1678. sys.stderr, set a formatter using the BASIC_FORMAT format string, and
  1679. add the handler to the root logger.
  1680. A number of optional keyword arguments may be specified, which can alter
  1681. the default behaviour.
  1682. filename Specifies that a FileHandler be created, using the specified
  1683. filename, rather than a StreamHandler.
  1684. filemode Specifies the mode to open the file, if filename is specified
  1685. (if filemode is unspecified, it defaults to 'a').
  1686. format Use the specified format string for the handler.
  1687. datefmt Use the specified date/time format.
  1688. style If a format string is specified, use this to specify the
  1689. type of format string (possible values '%', '{', '$', for
  1690. %-formatting, :meth:`str.format` and :class:`string.Template`
  1691. - defaults to '%').
  1692. level Set the root logger level to the specified level.
  1693. stream Use the specified stream to initialize the StreamHandler. Note
  1694. that this argument is incompatible with 'filename' - if both
  1695. are present, 'stream' is ignored.
  1696. handlers If specified, this should be an iterable of already created
  1697. handlers, which will be added to the root handler. Any handler
  1698. in the list which does not have a formatter assigned will be
  1699. assigned the formatter created in this function.
  1700. force If this keyword is specified as true, any existing handlers
  1701. attached to the root logger are removed and closed, before
  1702. carrying out the configuration as specified by the other
  1703. arguments.
  1704. encoding If specified together with a filename, this encoding is passed to
  1705. the created FileHandler, causing it to be used when the file is
  1706. opened.
  1707. errors If specified together with a filename, this value is passed to the
  1708. created FileHandler, causing it to be used when the file is
  1709. opened in text mode. If not specified, the default value is
  1710. `backslashreplace`.
  1711. Note that you could specify a stream created using open(filename, mode)
  1712. rather than passing the filename and mode in. However, it should be
  1713. remembered that StreamHandler does not close its stream (since it may be
  1714. using sys.stdout or sys.stderr), whereas FileHandler closes its stream
  1715. when the handler is closed.
  1716. .. versionchanged:: 3.2
  1717. Added the ``style`` parameter.
  1718. .. versionchanged:: 3.3
  1719. Added the ``handlers`` parameter. A ``ValueError`` is now thrown for
  1720. incompatible arguments (e.g. ``handlers`` specified together with
  1721. ``filename``/``filemode``, or ``filename``/``filemode`` specified
  1722. together with ``stream``, or ``handlers`` specified together with
  1723. ``stream``.
  1724. .. versionchanged:: 3.8
  1725. Added the ``force`` parameter.
  1726. .. versionchanged:: 3.9
  1727. Added the ``encoding`` and ``errors`` parameters.
  1728. """
  1729. # Add thread safety in case someone mistakenly calls
  1730. # basicConfig() from multiple threads
  1731. _acquireLock()
  1732. try:
  1733. force = kwargs.pop('force', False)
  1734. encoding = kwargs.pop('encoding', None)
  1735. errors = kwargs.pop('errors', 'backslashreplace')
  1736. if force:
  1737. for h in root.handlers[:]:
  1738. root.removeHandler(h)
  1739. h.close()
  1740. if len(root.handlers) == 0:
  1741. handlers = kwargs.pop("handlers", None)
  1742. if handlers is None:
  1743. if "stream" in kwargs and "filename" in kwargs:
  1744. raise ValueError("'stream' and 'filename' should not be "
  1745. "specified together")
  1746. else:
  1747. if "stream" in kwargs or "filename" in kwargs:
  1748. raise ValueError("'stream' or 'filename' should not be "
  1749. "specified together with 'handlers'")
  1750. if handlers is None:
  1751. filename = kwargs.pop("filename", None)
  1752. mode = kwargs.pop("filemode", 'a')
  1753. if filename:
  1754. if 'b' in mode:
  1755. errors = None
  1756. else:
  1757. encoding = io.text_encoding(encoding)
  1758. h = FileHandler(filename, mode,
  1759. encoding=encoding, errors=errors)
  1760. else:
  1761. stream = kwargs.pop("stream", None)
  1762. h = StreamHandler(stream)
  1763. handlers = [h]
  1764. dfs = kwargs.pop("datefmt", None)
  1765. style = kwargs.pop("style", '%')
  1766. if style not in _STYLES:
  1767. raise ValueError('Style must be one of: %s' % ','.join(
  1768. _STYLES.keys()))
  1769. fs = kwargs.pop("format", _STYLES[style][1])
  1770. fmt = Formatter(fs, dfs, style)
  1771. for h in handlers:
  1772. if h.formatter is None:
  1773. h.setFormatter(fmt)
  1774. root.addHandler(h)
  1775. level = kwargs.pop("level", None)
  1776. if level is not None:
  1777. root.setLevel(level)
  1778. if kwargs:
  1779. keys = ', '.join(kwargs.keys())
  1780. raise ValueError('Unrecognised argument(s): %s' % keys)
  1781. finally:
  1782. _releaseLock()
  1783. #---------------------------------------------------------------------------
  1784. # Utility functions at module level.
  1785. # Basically delegate everything to the root logger.
  1786. #---------------------------------------------------------------------------
  1787. def getLogger(name=None):
  1788. """
  1789. Return a logger with the specified name, creating it if necessary.
  1790. If no name is specified, return the root logger.
  1791. """
  1792. if not name or isinstance(name, str) and name == root.name:
  1793. return root
  1794. return Logger.manager.getLogger(name)
  1795. def critical(msg, *args, **kwargs):
  1796. """
  1797. Log a message with severity 'CRITICAL' on the root logger. If the logger
  1798. has no handlers, call basicConfig() to add a console handler with a
  1799. pre-defined format.
  1800. """
  1801. if len(root.handlers) == 0:
  1802. basicConfig()
  1803. root.critical(msg, *args, **kwargs)
  1804. def fatal(msg, *args, **kwargs):
  1805. """
  1806. Don't use this function, use critical() instead.
  1807. """
  1808. critical(msg, *args, **kwargs)
  1809. def error(msg, *args, **kwargs):
  1810. """
  1811. Log a message with severity 'ERROR' on the root logger. If the logger has
  1812. no handlers, call basicConfig() to add a console handler with a pre-defined
  1813. format.
  1814. """
  1815. if len(root.handlers) == 0:
  1816. basicConfig()
  1817. root.error(msg, *args, **kwargs)
  1818. def exception(msg, *args, exc_info=True, **kwargs):
  1819. """
  1820. Log a message with severity 'ERROR' on the root logger, with exception
  1821. information. If the logger has no handlers, basicConfig() is called to add
  1822. a console handler with a pre-defined format.
  1823. """
  1824. error(msg, *args, exc_info=exc_info, **kwargs)
  1825. def warning(msg, *args, **kwargs):
  1826. """
  1827. Log a message with severity 'WARNING' on the root logger. If the logger has
  1828. no handlers, call basicConfig() to add a console handler with a pre-defined
  1829. format.
  1830. """
  1831. if len(root.handlers) == 0:
  1832. basicConfig()
  1833. root.warning(msg, *args, **kwargs)
  1834. def warn(msg, *args, **kwargs):
  1835. warnings.warn("The 'warn' function is deprecated, "
  1836. "use 'warning' instead", DeprecationWarning, 2)
  1837. warning(msg, *args, **kwargs)
  1838. def info(msg, *args, **kwargs):
  1839. """
  1840. Log a message with severity 'INFO' on the root logger. If the logger has
  1841. no handlers, call basicConfig() to add a console handler with a pre-defined
  1842. format.
  1843. """
  1844. if len(root.handlers) == 0:
  1845. basicConfig()
  1846. root.info(msg, *args, **kwargs)
  1847. def debug(msg, *args, **kwargs):
  1848. """
  1849. Log a message with severity 'DEBUG' on the root logger. If the logger has
  1850. no handlers, call basicConfig() to add a console handler with a pre-defined
  1851. format.
  1852. """
  1853. if len(root.handlers) == 0:
  1854. basicConfig()
  1855. root.debug(msg, *args, **kwargs)
  1856. def log(level, msg, *args, **kwargs):
  1857. """
  1858. Log 'msg % args' with the integer severity 'level' on the root logger. If
  1859. the logger has no handlers, call basicConfig() to add a console handler
  1860. with a pre-defined format.
  1861. """
  1862. if len(root.handlers) == 0:
  1863. basicConfig()
  1864. root.log(level, msg, *args, **kwargs)
  1865. def disable(level=CRITICAL):
  1866. """
  1867. Disable all logging calls of severity 'level' and below.
  1868. """
  1869. root.manager.disable = level
  1870. root.manager._clear_cache()
  1871. def shutdown(handlerList=_handlerList):
  1872. """
  1873. Perform any cleanup actions in the logging system (e.g. flushing
  1874. buffers).
  1875. Should be called at application exit.
  1876. """
  1877. for wr in reversed(handlerList[:]):
  1878. #errors might occur, for example, if files are locked
  1879. #we just ignore them if raiseExceptions is not set
  1880. try:
  1881. h = wr()
  1882. if h:
  1883. try:
  1884. h.acquire()
  1885. h.flush()
  1886. h.close()
  1887. except (OSError, ValueError):
  1888. # Ignore errors which might be caused
  1889. # because handlers have been closed but
  1890. # references to them are still around at
  1891. # application exit.
  1892. pass
  1893. finally:
  1894. h.release()
  1895. except: # ignore everything, as we're shutting down
  1896. if raiseExceptions:
  1897. raise
  1898. #else, swallow
  1899. #Let's try and shutdown automatically on application exit...
  1900. import atexit
  1901. atexit.register(shutdown)
  1902. # Null handler
  1903. class NullHandler(Handler):
  1904. """
  1905. This handler does nothing. It's intended to be used to avoid the
  1906. "No handlers could be found for logger XXX" one-off warning. This is
  1907. important for library code, which may contain code to log events. If a user
  1908. of the library does not configure logging, the one-off warning might be
  1909. produced; to avoid this, the library developer simply needs to instantiate
  1910. a NullHandler and add it to the top-level logger of the library module or
  1911. package.
  1912. """
  1913. def handle(self, record):
  1914. """Stub."""
  1915. def emit(self, record):
  1916. """Stub."""
  1917. def createLock(self):
  1918. self.lock = None
  1919. def _at_fork_reinit(self):
  1920. pass
  1921. # Warnings integration
  1922. _warnings_showwarning = None
  1923. def _showwarning(message, category, filename, lineno, file=None, line=None):
  1924. """
  1925. Implementation of showwarnings which redirects to logging, which will first
  1926. check to see if the file parameter is None. If a file is specified, it will
  1927. delegate to the original warnings implementation of showwarning. Otherwise,
  1928. it will call warnings.formatwarning and will log the resulting string to a
  1929. warnings logger named "py.warnings" with level logging.WARNING.
  1930. """
  1931. if file is not None:
  1932. if _warnings_showwarning is not None:
  1933. _warnings_showwarning(message, category, filename, lineno, file, line)
  1934. else:
  1935. s = warnings.formatwarning(message, category, filename, lineno, line)
  1936. logger = getLogger("py.warnings")
  1937. if not logger.handlers:
  1938. logger.addHandler(NullHandler())
  1939. logger.warning("%s", s)
  1940. def captureWarnings(capture):
  1941. """
  1942. If capture is true, redirect all warnings to the logging package.
  1943. If capture is False, ensure that warnings are not redirected to logging
  1944. but to their original destinations.
  1945. """
  1946. global _warnings_showwarning
  1947. if capture:
  1948. if _warnings_showwarning is None:
  1949. _warnings_showwarning = warnings.showwarning
  1950. warnings.showwarning = _showwarning
  1951. else:
  1952. if _warnings_showwarning is not None:
  1953. warnings.showwarning = _warnings_showwarning
  1954. _warnings_showwarning = None