__init__.py 60 KB

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