__init__.py 68 KB

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