__init__.py 81 KB

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