blob: a7bd890e3cc6d2ca95485aa2064a35341494ca1e [file] [log] [blame]
Vinay Sajip02980422015-01-06 11:19:42 +00001# Copyright 2001-2015 by Vinay Sajip. All Rights Reserved.
Guido van Rossum57102f82002-11-13 16:15:58 +00002#
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.
Guido van Rossum57102f82002-11-13 16:15:58 +000016
17"""
18Logging package for Python. Based on PEP 282 and comments thereto in
Vinay Sajip0abf61d2012-02-23 19:45:52 +000019comp.lang.python.
Guido van Rossum57102f82002-11-13 16:15:58 +000020
Vinay Sajip02980422015-01-06 11:19:42 +000021Copyright (C) 2001-2015 Vinay Sajip. All Rights Reserved.
Guido van Rossum57102f82002-11-13 16:15:58 +000022
23To use, simply 'import logging' and log away!
24"""
25
Vinay Sajip1b761142014-04-10 07:12:19 +010026import sys, os, time, io, traceback, warnings, weakref, collections
27
Vinay Sajip6a65c5d2010-10-26 13:16:11 +000028from string import Template
Georg Brandlf9734072008-12-07 15:30:06 +000029
Christian Heimes18c66892008-02-17 13:31:39 +000030__all__ = ['BASIC_FORMAT', 'BufferingFormatter', 'CRITICAL', 'DEBUG', 'ERROR',
Vinay Sajipad5fa2f2009-04-27 13:55:05 +000031 'FATAL', 'FileHandler', 'Filter', 'Formatter', 'Handler', 'INFO',
32 'LogRecord', 'Logger', 'LoggerAdapter', 'NOTSET', 'NullHandler',
33 'StreamHandler', 'WARN', 'WARNING', 'addLevelName', 'basicConfig',
34 'captureWarnings', 'critical', 'debug', 'disable', 'error',
35 'exception', 'fatal', 'getLevelName', 'getLogger', 'getLoggerClass',
Vinay Sajip062d56b2010-10-19 15:26:24 +000036 'info', 'log', 'makeLogRecord', 'setLoggerClass', 'warn', 'warning',
Vinay Sajip5a27d402010-12-10 11:42:57 +000037 'getLogRecordFactory', 'setLogRecordFactory', 'lastResort']
Vinay Sajipb89e7c92005-03-13 09:54:31 +000038
39try:
Guido van Rossum57102f82002-11-13 16:15:58 +000040 import threading
Brett Cannoncd171c82013-07-04 17:43:24 -040041except ImportError: #pragma: no cover
Victor Stinner2a129742011-05-30 23:02:52 +020042 threading = None
Guido van Rossum57102f82002-11-13 16:15:58 +000043
44__author__ = "Vinay Sajip <vinay_sajip@red-dove.com>"
Thomas Wouters477c8d52006-05-27 19:21:47 +000045__status__ = "production"
Vinay Sajip698abe72014-03-14 13:42:19 +000046# The following module attributes are no longer updated.
Vinay Sajipdb81c4c2010-02-25 23:13:06 +000047__version__ = "0.5.1.2"
48__date__ = "07 February 2010"
Guido van Rossum57102f82002-11-13 16:15:58 +000049
50#---------------------------------------------------------------------------
51# Miscellaneous module data
52#---------------------------------------------------------------------------
53
54#
Guido van Rossum57102f82002-11-13 16:15:58 +000055#_startTime is used as the base when calculating the relative time of events
56#
57_startTime = time.time()
58
59#
60#raiseExceptions is used to see if exceptions during handling should be
61#propagated
62#
Vinay Sajip26fe4b72011-04-26 18:43:05 +010063raiseExceptions = True
Guido van Rossum57102f82002-11-13 16:15:58 +000064
Vinay Sajipd364a072006-03-13 22:05:28 +000065#
66# If you don't want threading information in the log, set this to zero
67#
Vinay Sajip26fe4b72011-04-26 18:43:05 +010068logThreads = True
Vinay Sajipd364a072006-03-13 22:05:28 +000069
70#
Jesse Noller9a0fc972009-01-18 21:12:58 +000071# If you don't want multiprocessing information in the log, set this to zero
72#
Vinay Sajip26fe4b72011-04-26 18:43:05 +010073logMultiprocessing = True
Jesse Noller9a0fc972009-01-18 21:12:58 +000074
75#
Vinay Sajipd364a072006-03-13 22:05:28 +000076# If you don't want process information in the log, set this to zero
77#
Vinay Sajip26fe4b72011-04-26 18:43:05 +010078logProcesses = True
Vinay Sajipd364a072006-03-13 22:05:28 +000079
Guido van Rossum57102f82002-11-13 16:15:58 +000080#---------------------------------------------------------------------------
81# Level related stuff
82#---------------------------------------------------------------------------
83#
84# Default levels and level names, these can be replaced with any positive set
85# of values having corresponding names. There is a pseudo-level, NOTSET, which
86# is only really there as a lower limit for user-defined levels. Handlers and
87# loggers are initialized with NOTSET so that they will log all messages, even
88# at user-defined levels.
89#
Vinay Sajipb89e7c92005-03-13 09:54:31 +000090
Guido van Rossum57102f82002-11-13 16:15:58 +000091CRITICAL = 50
92FATAL = CRITICAL
93ERROR = 40
Neal Norwitz6fa635d2003-02-18 14:20:07 +000094WARNING = 30
95WARN = WARNING
Guido van Rossum57102f82002-11-13 16:15:58 +000096INFO = 20
97DEBUG = 10
98NOTSET = 0
99
Vinay Sajip3b84eae2013-05-25 03:20:34 -0700100_levelToName = {
101 CRITICAL: 'CRITICAL',
102 ERROR: 'ERROR',
103 WARNING: 'WARNING',
104 INFO: 'INFO',
105 DEBUG: 'DEBUG',
106 NOTSET: 'NOTSET',
107}
108_nameToLevel = {
109 'CRITICAL': CRITICAL,
110 'ERROR': ERROR,
111 'WARN': WARNING,
112 'WARNING': WARNING,
113 'INFO': INFO,
114 'DEBUG': DEBUG,
115 'NOTSET': NOTSET,
Guido van Rossum57102f82002-11-13 16:15:58 +0000116}
117
118def getLevelName(level):
119 """
120 Return the textual representation of logging level 'level'.
121
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000122 If the level is one of the predefined levels (CRITICAL, ERROR, WARNING,
Guido van Rossum57102f82002-11-13 16:15:58 +0000123 INFO, DEBUG) then you get the corresponding string. If you have
124 associated levels with names using addLevelName then the name you have
Vinay Sajip779e0c92004-07-03 11:47:26 +0000125 associated with 'level' is returned.
126
127 If a numeric value corresponding to one of the defined levels is passed
128 in, the corresponding string representation is returned.
129
130 Otherwise, the string "Level %s" % level is returned.
Guido van Rossum57102f82002-11-13 16:15:58 +0000131 """
Vinay Sajipd1d4fbf2014-09-11 23:06:09 +0100132 # See Issue #22386 for the reason for this convoluted expression
133 return _levelToName.get(level, _nameToLevel.get(level, ("Level %s" % level)))
Guido van Rossum57102f82002-11-13 16:15:58 +0000134
135def addLevelName(level, levelName):
136 """
137 Associate 'levelName' with 'level'.
138
139 This is used when converting levels to text during message formatting.
140 """
141 _acquireLock()
142 try: #unlikely to cause an exception, but you never know...
Vinay Sajip3b84eae2013-05-25 03:20:34 -0700143 _levelToName[level] = levelName
144 _nameToLevel[levelName] = level
Guido van Rossum57102f82002-11-13 16:15:58 +0000145 finally:
146 _releaseLock()
147
Vinay Sajip194bcaf2014-06-12 23:36:33 +0100148if hasattr(sys, '_getframe'):
149 currentframe = lambda: sys._getframe(3)
150else: #pragma: no cover
151 def currentframe():
152 """Return the frame object for the caller's stack frame."""
153 try:
154 raise Exception
155 except Exception:
156 return sys.exc_info()[2].tb_frame.f_back
157
158#
159# _srcfile is used when walking the stack to check when we've got the first
160# caller stack frame, by skipping frames whose filename is that of this
161# module's source. It therefore should contain the filename of this module's
162# source file.
163#
164# Ordinarily we would use __file__ for this, but frozen modules don't always
165# have __file__ set, for some reason (see Issue #21736). Thus, we get the
166# filename from a handy code object from a function defined in this module.
167# (There's no particular reason for picking addLevelName.)
168#
169
170_srcfile = os.path.normcase(addLevelName.__code__.co_filename)
171
172# _srcfile is only used in conjunction with sys._getframe().
173# To provide compatibility with older versions of Python, set _srcfile
174# to None if _getframe() is not available; this value will prevent
175# findCaller() from being called. You can also do this if you want to avoid
176# the overhead of fetching caller information, even when _getframe() is
177# available.
178#if not hasattr(sys, '_getframe'):
179# _srcfile = None
180
181
Vinay Sajipd4fabf42009-07-13 11:28:25 +0000182def _checkLevel(level):
183 if isinstance(level, int):
184 rv = level
185 elif str(level) == level:
Vinay Sajip3b84eae2013-05-25 03:20:34 -0700186 if level not in _nameToLevel:
Vinay Sajipd4fabf42009-07-13 11:28:25 +0000187 raise ValueError("Unknown level: %r" % level)
Vinay Sajip3b84eae2013-05-25 03:20:34 -0700188 rv = _nameToLevel[level]
Vinay Sajipd4fabf42009-07-13 11:28:25 +0000189 else:
190 raise TypeError("Level not an integer or a valid string: %r" % level)
191 return rv
192
Guido van Rossum57102f82002-11-13 16:15:58 +0000193#---------------------------------------------------------------------------
194# Thread-related stuff
195#---------------------------------------------------------------------------
196
197#
198#_lock is used to serialize access to shared data structures in this module.
Benjamin Peterson55549932009-11-25 17:19:56 +0000199#This needs to be an RLock because fileConfig() creates and configures
200#Handlers, and so might arbitrary user threads. Since Handler code updates the
201#shared dictionary _handlers, it needs to acquire the lock. But if configuring,
Guido van Rossum57102f82002-11-13 16:15:58 +0000202#the lock would already have been acquired - so we need an RLock.
203#The same argument applies to Loggers and Manager.loggerDict.
204#
Victor Stinner2a129742011-05-30 23:02:52 +0200205if threading:
Vinay Sajip03f6c112009-11-27 14:03:36 +0000206 _lock = threading.RLock()
Vinay Sajip26fe4b72011-04-26 18:43:05 +0100207else: #pragma: no cover
Vinay Sajip03f6c112009-11-27 14:03:36 +0000208 _lock = None
209
Guido van Rossum57102f82002-11-13 16:15:58 +0000210
211def _acquireLock():
212 """
213 Acquire the module-level lock for serializing access to shared data.
214
215 This should be released with _releaseLock().
216 """
Guido van Rossum57102f82002-11-13 16:15:58 +0000217 if _lock:
218 _lock.acquire()
219
220def _releaseLock():
221 """
222 Release the module-level lock acquired by calling _acquireLock().
223 """
224 if _lock:
225 _lock.release()
226
227#---------------------------------------------------------------------------
228# The logging record
229#---------------------------------------------------------------------------
230
Benjamin Peterson55549932009-11-25 17:19:56 +0000231class LogRecord(object):
Guido van Rossum57102f82002-11-13 16:15:58 +0000232 """
233 A LogRecord instance represents an event being logged.
234
235 LogRecord instances are created every time something is logged. They
236 contain all the information pertinent to the event being logged. The
237 main information passed in is in msg and args, which are combined
238 using str(msg) % args to create the message field of the record. The
239 record also includes information such as when the record was created,
240 the source line where the logging call was made, and any exception
241 information to be logged.
242 """
Vinay Sajiped1992f2006-02-09 08:48:36 +0000243 def __init__(self, name, level, pathname, lineno,
Vinay Sajip61561522010-12-03 11:50:38 +0000244 msg, args, exc_info, func=None, sinfo=None, **kwargs):
Guido van Rossum57102f82002-11-13 16:15:58 +0000245 """
246 Initialize a logging record with interesting information.
247 """
248 ct = time.time()
249 self.name = name
250 self.msg = msg
Vinay Sajip4ed315a2004-10-20 08:39:40 +0000251 #
252 # The following statement allows passing of a dictionary as a sole
253 # argument, so that you can do something like
254 # logging.debug("a %(a)d b %(b)s", {'a':1, 'b':2})
255 # Suggested by Stefan Behnel.
256 # Note that without the test for args[0], we get a problem because
257 # during formatting, we test to see if the arg is present using
258 # 'if self.args:'. If the event being logged is e.g. 'Value is %d'
259 # and if the passed arg fails 'if self.args:' then no formatting
Vinay Sajip0a889532011-10-22 13:34:48 +0100260 # is done. For example, logger.warning('Value is %d', 0) would log
Vinay Sajip4ed315a2004-10-20 08:39:40 +0000261 # 'Value is %d' instead of 'Value is 0'.
262 # For the use case of passing a dictionary, this should not be a
263 # problem.
Vinay Sajip1b761142014-04-10 07:12:19 +0100264 # Issue #21172: a request was made to relax the isinstance check
265 # to hasattr(args[0], '__getitem__'). However, the docs on string
266 # formatting still seem to suggest a mapping object is required.
267 # Thus, while not removing the isinstance check, it does now look
268 # for collections.Mapping rather than, as before, dict.
269 if (args and len(args) == 1 and isinstance(args[0], collections.Mapping)
270 and args[0]):
Vinay Sajip4ed315a2004-10-20 08:39:40 +0000271 args = args[0]
Guido van Rossum57102f82002-11-13 16:15:58 +0000272 self.args = args
273 self.levelname = getLevelName(level)
274 self.levelno = level
275 self.pathname = pathname
276 try:
277 self.filename = os.path.basename(pathname)
278 self.module = os.path.splitext(self.filename)[0]
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000279 except (TypeError, ValueError, AttributeError):
Guido van Rossum57102f82002-11-13 16:15:58 +0000280 self.filename = pathname
281 self.module = "Unknown module"
282 self.exc_info = exc_info
Vinay Sajiped6bb142004-02-20 13:18:36 +0000283 self.exc_text = None # used to cache the traceback text
Vinay Sajip8593ae62010-11-14 21:33:04 +0000284 self.stack_info = sinfo
Guido van Rossum57102f82002-11-13 16:15:58 +0000285 self.lineno = lineno
Vinay Sajiped1992f2006-02-09 08:48:36 +0000286 self.funcName = func
Guido van Rossum57102f82002-11-13 16:15:58 +0000287 self.created = ct
Guido van Rossume2a383d2007-01-15 16:59:06 +0000288 self.msecs = (ct - int(ct)) * 1000
Guido van Rossum57102f82002-11-13 16:15:58 +0000289 self.relativeCreated = (self.created - _startTime) * 1000
Victor Stinner2a129742011-05-30 23:02:52 +0200290 if logThreads and threading:
291 self.thread = threading.get_ident()
Benjamin Peterson72753702008-08-18 18:09:21 +0000292 self.threadName = threading.current_thread().name
Vinay Sajip26fe4b72011-04-26 18:43:05 +0100293 else: # pragma: no cover
Guido van Rossum57102f82002-11-13 16:15:58 +0000294 self.thread = None
Vinay Sajip4a704862005-03-31 20:16:55 +0000295 self.threadName = None
Vinay Sajip26fe4b72011-04-26 18:43:05 +0100296 if not logMultiprocessing: # pragma: no cover
Jesse Noller9a0fc972009-01-18 21:12:58 +0000297 self.processName = None
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000298 else:
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000299 self.processName = 'MainProcess'
300 mp = sys.modules.get('multiprocessing')
301 if mp is not None:
302 # Errors may occur if multiprocessing has not finished loading
303 # yet - e.g. if a custom import hook causes third-party code
304 # to run when multiprocessing calls import. See issue 8200
305 # for an example
306 try:
307 self.processName = mp.current_process().name
Vinay Sajip9b727ec2012-01-25 17:49:45 +0000308 except Exception: #pragma: no cover
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000309 pass
Vinay Sajipd364a072006-03-13 22:05:28 +0000310 if logProcesses and hasattr(os, 'getpid'):
Jack Jansen4c641d02003-02-21 22:29:45 +0000311 self.process = os.getpid()
312 else:
313 self.process = None
Guido van Rossum57102f82002-11-13 16:15:58 +0000314
315 def __str__(self):
316 return '<LogRecord: %s, %s, %s, %s, "%s">'%(self.name, self.levelno,
317 self.pathname, self.lineno, self.msg)
318
Vinay Sajip02980422015-01-06 11:19:42 +0000319 __repr__ = __str__
320
Guido van Rossum57102f82002-11-13 16:15:58 +0000321 def getMessage(self):
322 """
323 Return the message for this LogRecord.
324
325 Return the message for this LogRecord after merging any user-supplied
326 arguments with the message.
327 """
Vinay Sajipdc5097f2010-08-31 07:52:17 +0000328 msg = str(self.msg)
Guido van Rossum57102f82002-11-13 16:15:58 +0000329 if self.args:
330 msg = msg % self.args
331 return msg
332
Vinay Sajip062d56b2010-10-19 15:26:24 +0000333#
334# Determine which class to use when instantiating log records.
335#
Vinay Sajip61561522010-12-03 11:50:38 +0000336_logRecordFactory = LogRecord
Vinay Sajip062d56b2010-10-19 15:26:24 +0000337
Vinay Sajip61561522010-12-03 11:50:38 +0000338def setLogRecordFactory(factory):
Vinay Sajip062d56b2010-10-19 15:26:24 +0000339 """
Vinay Sajipfad058f2010-12-03 13:01:11 +0000340 Set the factory to be used when instantiating a log record.
Vinay Sajip062d56b2010-10-19 15:26:24 +0000341
Vinay Sajip61561522010-12-03 11:50:38 +0000342 :param factory: A callable which will be called to instantiate
343 a log record.
344 """
345 global _logRecordFactory
346 _logRecordFactory = factory
347
348def getLogRecordFactory():
Vinay Sajip062d56b2010-10-19 15:26:24 +0000349 """
Vinay Sajipfad058f2010-12-03 13:01:11 +0000350 Return the factory to be used when instantiating a log record.
Vinay Sajip062d56b2010-10-19 15:26:24 +0000351 """
352
Vinay Sajip61561522010-12-03 11:50:38 +0000353 return _logRecordFactory
Vinay Sajip062d56b2010-10-19 15:26:24 +0000354
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000355def makeLogRecord(dict):
356 """
357 Make a LogRecord whose attributes are defined by the specified dictionary,
358 This function is useful for converting a logging event received over
359 a socket connection (which is sent as a dictionary) into a LogRecord
360 instance.
361 """
Vinay Sajip61561522010-12-03 11:50:38 +0000362 rv = _logRecordFactory(None, None, "", 0, "", (), None, None)
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000363 rv.__dict__.update(dict)
364 return rv
365
Guido van Rossum57102f82002-11-13 16:15:58 +0000366#---------------------------------------------------------------------------
367# Formatter classes and functions
368#---------------------------------------------------------------------------
369
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000370class PercentStyle(object):
371
372 default_format = '%(message)s'
373 asctime_format = '%(asctime)s'
Vinay Sajip10914b72011-02-26 14:15:48 +0000374 asctime_search = '%(asctime)'
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000375
376 def __init__(self, fmt):
377 self._fmt = fmt or self.default_format
378
379 def usesTime(self):
Vinay Sajip10914b72011-02-26 14:15:48 +0000380 return self._fmt.find(self.asctime_search) >= 0
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000381
382 def format(self, record):
383 return self._fmt % record.__dict__
384
385class StrFormatStyle(PercentStyle):
386 default_format = '{message}'
387 asctime_format = '{asctime}'
Vinay Sajip10914b72011-02-26 14:15:48 +0000388 asctime_search = '{asctime'
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000389
390 def format(self, record):
391 return self._fmt.format(**record.__dict__)
392
393
394class StringTemplateStyle(PercentStyle):
395 default_format = '${message}'
396 asctime_format = '${asctime}'
Vinay Sajip89807a52011-02-26 16:06:02 +0000397 asctime_search = '${asctime}'
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000398
399 def __init__(self, fmt):
400 self._fmt = fmt or self.default_format
401 self._tpl = Template(self._fmt)
402
403 def usesTime(self):
404 fmt = self._fmt
405 return fmt.find('$asctime') >= 0 or fmt.find(self.asctime_format) >= 0
406
407 def format(self, record):
408 return self._tpl.substitute(**record.__dict__)
409
Vinay Sajip1fd12022014-01-13 21:59:56 +0000410BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s"
411
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000412_STYLES = {
Vinay Sajip1fd12022014-01-13 21:59:56 +0000413 '%': (PercentStyle, BASIC_FORMAT),
414 '{': (StrFormatStyle, '{levelname}:{name}:{message}'),
415 '$': (StringTemplateStyle, '${levelname}:${name}:${message}'),
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000416}
417
Benjamin Peterson55549932009-11-25 17:19:56 +0000418class Formatter(object):
Guido van Rossum57102f82002-11-13 16:15:58 +0000419 """
420 Formatter instances are used to convert a LogRecord to text.
421
422 Formatters need to know how a LogRecord is constructed. They are
423 responsible for converting a LogRecord to (usually) a string which can
424 be interpreted by either a human or an external system. The base Formatter
425 allows a formatting string to be specified. If none is supplied, the
Vinay Sajip2a20dfc2010-10-20 20:05:38 +0000426 default value of "%s(message)" is used.
Guido van Rossum57102f82002-11-13 16:15:58 +0000427
428 The Formatter can be initialized with a format string which makes use of
429 knowledge of the LogRecord attributes - e.g. the default value mentioned
430 above makes use of the fact that the user's message and arguments are pre-
431 formatted into a LogRecord's message attribute. Currently, the useful
432 attributes in a LogRecord are described by:
433
434 %(name)s Name of the logger (logging channel)
435 %(levelno)s Numeric logging level for the message (DEBUG, INFO,
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000436 WARNING, ERROR, CRITICAL)
Guido van Rossum57102f82002-11-13 16:15:58 +0000437 %(levelname)s Text logging level for the message ("DEBUG", "INFO",
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000438 "WARNING", "ERROR", "CRITICAL")
Guido van Rossum57102f82002-11-13 16:15:58 +0000439 %(pathname)s Full pathname of the source file where the logging
440 call was issued (if available)
441 %(filename)s Filename portion of pathname
442 %(module)s Module (name portion of filename)
443 %(lineno)d Source line number where the logging call was issued
444 (if available)
Vinay Sajiped1992f2006-02-09 08:48:36 +0000445 %(funcName)s Function name
Guido van Rossum57102f82002-11-13 16:15:58 +0000446 %(created)f Time when the LogRecord was created (time.time()
447 return value)
448 %(asctime)s Textual time when the LogRecord was created
449 %(msecs)d Millisecond portion of the creation time
450 %(relativeCreated)d Time in milliseconds when the LogRecord was created,
451 relative to the time the logging module was loaded
452 (typically at application startup time)
453 %(thread)d Thread ID (if available)
Vinay Sajip4a704862005-03-31 20:16:55 +0000454 %(threadName)s Thread name (if available)
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000455 %(process)d Process ID (if available)
Guido van Rossum57102f82002-11-13 16:15:58 +0000456 %(message)s The result of record.getMessage(), computed just as
457 the record is emitted
458 """
459
460 converter = time.localtime
461
Vinay Sajipa39c5712010-10-25 13:57:39 +0000462 def __init__(self, fmt=None, datefmt=None, style='%'):
Guido van Rossum57102f82002-11-13 16:15:58 +0000463 """
464 Initialize the formatter with specified format strings.
465
466 Initialize the formatter either with the specified format string, or a
467 default as described above. Allow for specialized date formatting with
468 the optional datefmt argument (if omitted, you get the ISO8601 format).
Vinay Sajipa39c5712010-10-25 13:57:39 +0000469
470 Use a style parameter of '%', '{' or '$' to specify that you want to
471 use one of %-formatting, :meth:`str.format` (``{}``) formatting or
472 :class:`string.Template` formatting in your format string.
473
Georg Brandl8c16cb92016-02-25 20:17:45 +0100474 .. versionchanged:: 3.2
Vinay Sajipa39c5712010-10-25 13:57:39 +0000475 Added the ``style`` parameter.
Guido van Rossum57102f82002-11-13 16:15:58 +0000476 """
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000477 if style not in _STYLES:
478 raise ValueError('Style must be one of: %s' % ','.join(
479 _STYLES.keys()))
Vinay Sajip1fd12022014-01-13 21:59:56 +0000480 self._style = _STYLES[style][0](fmt)
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000481 self._fmt = self._style._fmt
Guido van Rossum57102f82002-11-13 16:15:58 +0000482 self.datefmt = datefmt
483
Vinay Sajipae5740f2011-06-09 18:42:19 +0100484 default_time_format = '%Y-%m-%d %H:%M:%S'
485 default_msec_format = '%s,%03d'
486
Guido van Rossum57102f82002-11-13 16:15:58 +0000487 def formatTime(self, record, datefmt=None):
488 """
489 Return the creation time of the specified LogRecord as formatted text.
490
491 This method should be called from format() by a formatter which
492 wants to make use of a formatted time. This method can be overridden
493 in formatters to provide for any specific requirement, but the
494 basic behaviour is as follows: if datefmt (a string) is specified,
495 it is used with time.strftime() to format the creation time of the
496 record. Otherwise, the ISO8601 format is used. The resulting
497 string is returned. This function uses a user-configurable function
498 to convert the creation time to a tuple. By default, time.localtime()
499 is used; to change this for a particular formatter instance, set the
500 'converter' attribute to a function with the same signature as
501 time.localtime() or time.gmtime(). To change it for all formatters,
502 for example if you want all logging times to be shown in GMT,
503 set the 'converter' attribute in the Formatter class.
504 """
505 ct = self.converter(record.created)
506 if datefmt:
507 s = time.strftime(datefmt, ct)
508 else:
Vinay Sajipae5740f2011-06-09 18:42:19 +0100509 t = time.strftime(self.default_time_format, ct)
510 s = self.default_msec_format % (t, record.msecs)
Guido van Rossum57102f82002-11-13 16:15:58 +0000511 return s
512
513 def formatException(self, ei):
514 """
515 Format and return the specified exception information as a string.
516
517 This default implementation just uses
518 traceback.print_exception()
519 """
Guido van Rossum34d19282007-08-09 01:03:29 +0000520 sio = io.StringIO()
Vinay Sajip40d9a4e2010-08-30 18:10:03 +0000521 tb = ei[2]
522 # See issues #9427, #1553375. Commented out for now.
523 #if getattr(self, 'fullstack', False):
524 # traceback.print_stack(tb.tb_frame.f_back, file=sio)
525 traceback.print_exception(ei[0], ei[1], tb, None, sio)
Guido van Rossum57102f82002-11-13 16:15:58 +0000526 s = sio.getvalue()
527 sio.close()
Guido van Rossum486364b2007-06-30 05:01:58 +0000528 if s[-1:] == "\n":
Guido van Rossum57102f82002-11-13 16:15:58 +0000529 s = s[:-1]
530 return s
531
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000532 def usesTime(self):
533 """
534 Check if the format uses the creation time of the record.
535 """
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000536 return self._style.usesTime()
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000537
Vinay Sajipd0557bf2010-10-25 15:25:24 +0000538 def formatMessage(self, record):
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000539 return self._style.format(record)
Vinay Sajipd0557bf2010-10-25 15:25:24 +0000540
Vinay Sajip8593ae62010-11-14 21:33:04 +0000541 def formatStack(self, stack_info):
542 """
543 This method is provided as an extension point for specialized
544 formatting of stack information.
545
546 The input data is a string as returned from a call to
547 :func:`traceback.print_stack`, but with the last trailing newline
548 removed.
549
550 The base implementation just returns the value passed in.
551 """
552 return stack_info
553
Guido van Rossum57102f82002-11-13 16:15:58 +0000554 def format(self, record):
555 """
556 Format the specified record as text.
557
558 The record's attribute dictionary is used as the operand to a
559 string formatting operation which yields the returned string.
560 Before formatting the dictionary, a couple of preparatory steps
561 are carried out. The message attribute of the record is computed
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000562 using LogRecord.getMessage(). If the formatting string uses the
563 time (as determined by a call to usesTime(), formatTime() is
564 called to format the event time. If there is exception information,
565 it is formatted using formatException() and appended to the message.
Guido van Rossum57102f82002-11-13 16:15:58 +0000566 """
567 record.message = record.getMessage()
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000568 if self.usesTime():
Guido van Rossum57102f82002-11-13 16:15:58 +0000569 record.asctime = self.formatTime(record, self.datefmt)
Vinay Sajipd0557bf2010-10-25 15:25:24 +0000570 s = self.formatMessage(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000571 if record.exc_info:
Vinay Sajiped6bb142004-02-20 13:18:36 +0000572 # Cache the traceback text to avoid converting it multiple times
573 # (it's constant anyway)
574 if not record.exc_text:
575 record.exc_text = self.formatException(record.exc_info)
576 if record.exc_text:
Guido van Rossum486364b2007-06-30 05:01:58 +0000577 if s[-1:] != "\n":
Guido van Rossum57102f82002-11-13 16:15:58 +0000578 s = s + "\n"
Vinay Sajiped6bb142004-02-20 13:18:36 +0000579 s = s + record.exc_text
Vinay Sajip8593ae62010-11-14 21:33:04 +0000580 if record.stack_info:
581 if s[-1:] != "\n":
582 s = s + "\n"
583 s = s + self.formatStack(record.stack_info)
Guido van Rossum57102f82002-11-13 16:15:58 +0000584 return s
585
586#
587# The default formatter to use when no other is specified
588#
589_defaultFormatter = Formatter()
590
Benjamin Peterson55549932009-11-25 17:19:56 +0000591class BufferingFormatter(object):
Guido van Rossum57102f82002-11-13 16:15:58 +0000592 """
593 A formatter suitable for formatting a number of records.
594 """
595 def __init__(self, linefmt=None):
596 """
597 Optionally specify a formatter which will be used to format each
598 individual record.
599 """
600 if linefmt:
601 self.linefmt = linefmt
602 else:
603 self.linefmt = _defaultFormatter
604
605 def formatHeader(self, records):
606 """
607 Return the header string for the specified records.
608 """
609 return ""
610
611 def formatFooter(self, records):
612 """
613 Return the footer string for the specified records.
614 """
615 return ""
616
617 def format(self, records):
618 """
619 Format the specified records and return the result as a string.
620 """
621 rv = ""
622 if len(records) > 0:
623 rv = rv + self.formatHeader(records)
624 for record in records:
625 rv = rv + self.linefmt.format(record)
626 rv = rv + self.formatFooter(records)
627 return rv
628
629#---------------------------------------------------------------------------
630# Filter classes and functions
631#---------------------------------------------------------------------------
632
Benjamin Peterson55549932009-11-25 17:19:56 +0000633class Filter(object):
Guido van Rossum57102f82002-11-13 16:15:58 +0000634 """
635 Filter instances are used to perform arbitrary filtering of LogRecords.
636
637 Loggers and Handlers can optionally use Filter instances to filter
638 records as desired. The base filter class only allows events which are
639 below a certain point in the logger hierarchy. For example, a filter
640 initialized with "A.B" will allow events logged by loggers "A.B",
641 "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
642 initialized with the empty string, all events are passed.
643 """
644 def __init__(self, name=''):
645 """
646 Initialize a filter.
647
648 Initialize with the name of the logger which, together with its
649 children, will have its events allowed through the filter. If no
650 name is specified, allow every event.
651 """
652 self.name = name
653 self.nlen = len(name)
654
655 def filter(self, record):
656 """
657 Determine if the specified record is to be logged.
658
659 Is the specified record to be logged? Returns 0 for no, nonzero for
660 yes. If deemed appropriate, the record may be modified in-place.
661 """
662 if self.nlen == 0:
Vinay Sajip26fe4b72011-04-26 18:43:05 +0100663 return True
Guido van Rossum57102f82002-11-13 16:15:58 +0000664 elif self.name == record.name:
Vinay Sajip26fe4b72011-04-26 18:43:05 +0100665 return True
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000666 elif record.name.find(self.name, 0, self.nlen) != 0:
Vinay Sajip26fe4b72011-04-26 18:43:05 +0100667 return False
Guido van Rossum57102f82002-11-13 16:15:58 +0000668 return (record.name[self.nlen] == ".")
669
Benjamin Peterson55549932009-11-25 17:19:56 +0000670class Filterer(object):
Guido van Rossum57102f82002-11-13 16:15:58 +0000671 """
672 A base class for loggers and handlers which allows them to share
673 common code.
674 """
675 def __init__(self):
676 """
677 Initialize the list of filters to be an empty list.
678 """
679 self.filters = []
680
681 def addFilter(self, filter):
682 """
683 Add the specified filter to this handler.
684 """
685 if not (filter in self.filters):
686 self.filters.append(filter)
687
688 def removeFilter(self, filter):
689 """
690 Remove the specified filter from this handler.
691 """
692 if filter in self.filters:
693 self.filters.remove(filter)
694
695 def filter(self, record):
696 """
697 Determine if a record is loggable by consulting all the filters.
698
699 The default is to allow the record to be logged; any filter can veto
700 this and the record is then dropped. Returns a zero value if a record
701 is to be dropped, else non-zero.
Vinay Sajip6dbed2e2010-10-19 20:53:01 +0000702
Georg Brandl8c16cb92016-02-25 20:17:45 +0100703 .. versionchanged:: 3.2
Vinay Sajip6dbed2e2010-10-19 20:53:01 +0000704
705 Allow filters to be just callables.
Guido van Rossum57102f82002-11-13 16:15:58 +0000706 """
Vinay Sajip312cc0d2011-04-30 21:51:51 +0100707 rv = True
Guido van Rossum57102f82002-11-13 16:15:58 +0000708 for f in self.filters:
Vinay Sajip6dbed2e2010-10-19 20:53:01 +0000709 if hasattr(f, 'filter'):
710 result = f.filter(record)
Vinay Sajip6dbed2e2010-10-19 20:53:01 +0000711 else:
Vinay Sajipfc082ca2010-10-19 21:13:49 +0000712 result = f(record) # assume callable - will raise if not
Vinay Sajip6dbed2e2010-10-19 20:53:01 +0000713 if not result:
Vinay Sajip312cc0d2011-04-30 21:51:51 +0100714 rv = False
Guido van Rossum57102f82002-11-13 16:15:58 +0000715 break
716 return rv
717
718#---------------------------------------------------------------------------
719# Handler classes and functions
720#---------------------------------------------------------------------------
721
Benjamin Peterson55549932009-11-25 17:19:56 +0000722_handlers = weakref.WeakValueDictionary() #map of handler names to handlers
Vinay Sajip0ee9ba22005-09-08 18:14:16 +0000723_handlerList = [] # added to allow handlers to be removed in reverse of order initialized
Guido van Rossum57102f82002-11-13 16:15:58 +0000724
Benjamin Peterson55549932009-11-25 17:19:56 +0000725def _removeHandlerRef(wr):
726 """
727 Remove a handler reference from the internal cleanup list.
728 """
Vinay Sajipde6e9d62010-08-23 17:50:30 +0000729 # This function can be called during module teardown, when globals are
Vinay Sajip156307b2014-04-04 10:51:49 +0100730 # set to None. It can also be called from another thread. So we need to
731 # pre-emptively grab the necessary globals and check if they're None,
732 # to prevent race conditions and failures during interpreter shutdown.
733 acquire, release, handlers = _acquireLock, _releaseLock, _handlerList
734 if acquire and release and handlers:
735 acquire()
Vinay Sajipde6e9d62010-08-23 17:50:30 +0000736 try:
Vinay Sajip156307b2014-04-04 10:51:49 +0100737 if wr in handlers:
738 handlers.remove(wr)
Vinay Sajipde6e9d62010-08-23 17:50:30 +0000739 finally:
Vinay Sajip156307b2014-04-04 10:51:49 +0100740 release()
Benjamin Peterson55549932009-11-25 17:19:56 +0000741
742def _addHandlerRef(handler):
743 """
744 Add a handler to the internal cleanup list using a weak reference.
745 """
746 _acquireLock()
747 try:
748 _handlerList.append(weakref.ref(handler, _removeHandlerRef))
749 finally:
750 _releaseLock()
751
Guido van Rossum57102f82002-11-13 16:15:58 +0000752class Handler(Filterer):
753 """
754 Handler instances dispatch logging events to specific destinations.
755
756 The base handler class. Acts as a placeholder which defines the Handler
757 interface. Handlers can optionally use Formatter instances to format
758 records as desired. By default, no formatter is specified; in this case,
759 the 'raw' message as determined by record.message is logged.
760 """
761 def __init__(self, level=NOTSET):
762 """
763 Initializes the instance - basically setting the formatter to None
764 and the filter list to empty.
765 """
766 Filterer.__init__(self)
Benjamin Peterson55549932009-11-25 17:19:56 +0000767 self._name = None
Vinay Sajipd4fabf42009-07-13 11:28:25 +0000768 self.level = _checkLevel(level)
Guido van Rossum57102f82002-11-13 16:15:58 +0000769 self.formatter = None
Benjamin Peterson55549932009-11-25 17:19:56 +0000770 # Add the handler to the global _handlerList (for cleanup on shutdown)
771 _addHandlerRef(self)
772 self.createLock()
773
774 def get_name(self):
775 return self._name
776
777 def set_name(self, name):
Guido van Rossum57102f82002-11-13 16:15:58 +0000778 _acquireLock()
Benjamin Peterson55549932009-11-25 17:19:56 +0000779 try:
780 if self._name in _handlers:
781 del _handlers[self._name]
782 self._name = name
783 if name:
784 _handlers[name] = self
Guido van Rossum57102f82002-11-13 16:15:58 +0000785 finally:
786 _releaseLock()
Benjamin Peterson55549932009-11-25 17:19:56 +0000787
788 name = property(get_name, set_name)
Guido van Rossum57102f82002-11-13 16:15:58 +0000789
790 def createLock(self):
791 """
792 Acquire a thread lock for serializing access to the underlying I/O.
793 """
Victor Stinner2a129742011-05-30 23:02:52 +0200794 if threading:
Vinay Sajip4a704862005-03-31 20:16:55 +0000795 self.lock = threading.RLock()
Vinay Sajip26fe4b72011-04-26 18:43:05 +0100796 else: #pragma: no cover
Guido van Rossum57102f82002-11-13 16:15:58 +0000797 self.lock = None
798
799 def acquire(self):
800 """
801 Acquire the I/O thread lock.
802 """
803 if self.lock:
804 self.lock.acquire()
805
806 def release(self):
807 """
808 Release the I/O thread lock.
809 """
810 if self.lock:
811 self.lock.release()
812
813 def setLevel(self, level):
814 """
Gregory P. Smithe85488c2011-12-17 12:36:34 -0800815 Set the logging level of this handler. level must be an int or a str.
Guido van Rossum57102f82002-11-13 16:15:58 +0000816 """
Vinay Sajipd4fabf42009-07-13 11:28:25 +0000817 self.level = _checkLevel(level)
Guido van Rossum57102f82002-11-13 16:15:58 +0000818
819 def format(self, record):
820 """
821 Format the specified record.
822
823 If a formatter is set, use it. Otherwise, use the default formatter
824 for the module.
825 """
826 if self.formatter:
827 fmt = self.formatter
828 else:
829 fmt = _defaultFormatter
830 return fmt.format(record)
831
832 def emit(self, record):
833 """
834 Do whatever it takes to actually log the specified logging record.
835
836 This version is intended to be implemented by subclasses and so
837 raises a NotImplementedError.
838 """
Collin Winterce36ad82007-08-30 01:19:48 +0000839 raise NotImplementedError('emit must be implemented '
840 'by Handler subclasses')
Guido van Rossum57102f82002-11-13 16:15:58 +0000841
842 def handle(self, record):
843 """
844 Conditionally emit the specified logging record.
845
846 Emission depends on filters which may have been added to the handler.
847 Wrap the actual emission of the record with acquisition/release of
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000848 the I/O thread lock. Returns whether the filter passed the record for
849 emission.
Guido van Rossum57102f82002-11-13 16:15:58 +0000850 """
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000851 rv = self.filter(record)
852 if rv:
Guido van Rossum57102f82002-11-13 16:15:58 +0000853 self.acquire()
854 try:
855 self.emit(record)
856 finally:
857 self.release()
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000858 return rv
Guido van Rossum57102f82002-11-13 16:15:58 +0000859
860 def setFormatter(self, fmt):
861 """
862 Set the formatter for this handler.
863 """
864 self.formatter = fmt
865
866 def flush(self):
867 """
868 Ensure all logging output has been flushed.
869
870 This version does nothing and is intended to be implemented by
871 subclasses.
872 """
873 pass
874
875 def close(self):
876 """
877 Tidy up any resources used by the handler.
878
Benjamin Peterson55549932009-11-25 17:19:56 +0000879 This version removes the handler from an internal map of handlers,
880 _handlers, which is used for handler lookup by name. Subclasses
Vinay Sajiped6bb142004-02-20 13:18:36 +0000881 should ensure that this gets called from overridden close()
882 methods.
Guido van Rossum57102f82002-11-13 16:15:58 +0000883 """
Vinay Sajiped6bb142004-02-20 13:18:36 +0000884 #get the module data lock, as we're updating a shared structure.
885 _acquireLock()
886 try: #unlikely to raise an exception, but you never know...
Benjamin Peterson55549932009-11-25 17:19:56 +0000887 if self._name and self._name in _handlers:
888 del _handlers[self._name]
Vinay Sajiped6bb142004-02-20 13:18:36 +0000889 finally:
890 _releaseLock()
Guido van Rossum57102f82002-11-13 16:15:58 +0000891
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000892 def handleError(self, record):
Guido van Rossum57102f82002-11-13 16:15:58 +0000893 """
894 Handle errors which occur during an emit() call.
895
896 This method should be called from handlers when an exception is
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000897 encountered during an emit() call. If raiseExceptions is false,
Guido van Rossum57102f82002-11-13 16:15:58 +0000898 exceptions get silently ignored. This is what is mostly wanted
899 for a logging system - most users will not care about errors in
900 the logging system, they are more interested in application errors.
901 You could, however, replace this with a custom handler if you wish.
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000902 The record which was being processed is passed in to this method.
Guido van Rossum57102f82002-11-13 16:15:58 +0000903 """
Vinay Sajip889bb292012-01-20 11:23:02 +0000904 if raiseExceptions and sys.stderr: # see issue 13807
Vinay Sajipd06d5402012-10-31 23:49:19 +0000905 t, v, tb = sys.exc_info()
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000906 try:
Vinay Sajipd06d5402012-10-31 23:49:19 +0000907 sys.stderr.write('--- Logging error ---\n')
908 traceback.print_exception(t, v, tb, None, sys.stderr)
909 sys.stderr.write('Call stack:\n')
910 # Walk the stack frame up until we're out of logging,
911 # so as to print the calling context.
912 frame = tb.tb_frame
913 while (frame and os.path.dirname(frame.f_code.co_filename) ==
914 __path__[0]):
915 frame = frame.f_back
916 if frame:
917 traceback.print_stack(frame, file=sys.stderr)
918 else:
919 # couldn't find the right stack frame, for some reason
920 sys.stderr.write('Logged from file %s, line %s\n' % (
921 record.filename, record.lineno))
Vinay Sajip3f582772013-08-08 18:28:53 +0100922 # Issue 18671: output logging message and arguments
Vinay Sajip698abe72014-03-14 13:42:19 +0000923 try:
924 sys.stderr.write('Message: %r\n'
925 'Arguments: %s\n' % (record.msg,
926 record.args))
927 except Exception:
928 sys.stderr.write('Unable to print the message and arguments'
929 ' - possible formatting error.\nUse the'
930 ' traceback above to help find the error.\n'
931 )
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200932 except OSError: #pragma: no cover
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000933 pass # see issue 5971
934 finally:
Vinay Sajipd06d5402012-10-31 23:49:19 +0000935 del t, v, tb
Guido van Rossum57102f82002-11-13 16:15:58 +0000936
937class StreamHandler(Handler):
938 """
939 A handler class which writes logging records, appropriately formatted,
940 to a stream. Note that this class does not close the stream, as
941 sys.stdout or sys.stderr may be used.
942 """
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000943
Vinay Sajip2a20dfc2010-10-20 20:05:38 +0000944 terminator = '\n'
945
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000946 def __init__(self, stream=None):
Guido van Rossum57102f82002-11-13 16:15:58 +0000947 """
948 Initialize the handler.
949
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000950 If stream is not specified, sys.stderr is used.
Guido van Rossum57102f82002-11-13 16:15:58 +0000951 """
952 Handler.__init__(self)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000953 if stream is None:
954 stream = sys.stderr
955 self.stream = stream
Guido van Rossum57102f82002-11-13 16:15:58 +0000956
957 def flush(self):
958 """
959 Flushes the stream.
960 """
Vinay Sajipf0509032012-02-23 20:49:08 +0000961 self.acquire()
962 try:
Vinay Sajip0abf61d2012-02-23 19:45:52 +0000963 if self.stream and hasattr(self.stream, "flush"):
964 self.stream.flush()
Vinay Sajipf0509032012-02-23 20:49:08 +0000965 finally:
966 self.release()
Guido van Rossum57102f82002-11-13 16:15:58 +0000967
968 def emit(self, record):
969 """
970 Emit a record.
971
972 If a formatter is specified, it is used to format the record.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000973 The record is then written to the stream with a trailing newline. If
974 exception information is present, it is formatted using
975 traceback.print_exception and appended to the stream. If the stream
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000976 has an 'encoding' attribute, it is used to determine how to do the
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000977 output to the stream.
Guido van Rossum57102f82002-11-13 16:15:58 +0000978 """
979 try:
980 msg = self.format(record)
Benjamin Petersonf91df042009-02-13 02:50:59 +0000981 stream = self.stream
Vinay Sajip2a20dfc2010-10-20 20:05:38 +0000982 stream.write(msg)
983 stream.write(self.terminator)
Guido van Rossum57102f82002-11-13 16:15:58 +0000984 self.flush()
Vinay Sajip8cf4eb12012-10-09 08:06:13 +0100985 except Exception:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000986 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000987
988class FileHandler(StreamHandler):
989 """
990 A handler class which writes formatted logging records to disk files.
991 """
Vinay Sajip26fe4b72011-04-26 18:43:05 +0100992 def __init__(self, filename, mode='a', encoding=None, delay=False):
Guido van Rossum57102f82002-11-13 16:15:58 +0000993 """
994 Open the specified file and use it as the stream for logging.
995 """
Vinay Sajip4bbab2b2004-07-08 10:22:35 +0000996 #keep the absolute path, otherwise derived classes which use this
997 #may come a cropper when the current directory changes
998 self.baseFilename = os.path.abspath(filename)
Guido van Rossum57102f82002-11-13 16:15:58 +0000999 self.mode = mode
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001000 self.encoding = encoding
Vinay Sajip43c6ef12013-09-06 10:25:31 +01001001 self.delay = delay
Christian Heimese7a15bb2008-01-24 16:21:45 +00001002 if delay:
Vinay Sajip6268cbc2009-01-21 00:19:28 +00001003 #We don't open the stream, but we still need to call the
1004 #Handler constructor to set level, formatter, lock etc.
1005 Handler.__init__(self)
Christian Heimese7a15bb2008-01-24 16:21:45 +00001006 self.stream = None
1007 else:
Vinay Sajip6268cbc2009-01-21 00:19:28 +00001008 StreamHandler.__init__(self, self._open())
Guido van Rossum57102f82002-11-13 16:15:58 +00001009
1010 def close(self):
1011 """
1012 Closes the stream.
1013 """
Vinay Sajipf0509032012-02-23 20:49:08 +00001014 self.acquire()
1015 try:
Serhiy Storchaka7e7a3db2015-04-10 13:24:41 +03001016 try:
1017 if self.stream:
1018 try:
1019 self.flush()
1020 finally:
1021 stream = self.stream
1022 self.stream = None
1023 if hasattr(stream, "close"):
1024 stream.close()
1025 finally:
1026 # Issue #19523: call unconditionally to
1027 # prevent a handler leak when delay is set
1028 StreamHandler.close(self)
Vinay Sajipf0509032012-02-23 20:49:08 +00001029 finally:
1030 self.release()
Guido van Rossum57102f82002-11-13 16:15:58 +00001031
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001032 def _open(self):
1033 """
1034 Open the current base file with the (original) mode and encoding.
1035 Return the resulting stream.
1036 """
Florent Xicluna5252f9f2011-11-07 19:43:05 +01001037 return open(self.baseFilename, self.mode, encoding=self.encoding)
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001038
Christian Heimese7a15bb2008-01-24 16:21:45 +00001039 def emit(self, record):
1040 """
1041 Emit a record.
1042
1043 If the stream was not opened because 'delay' was specified in the
1044 constructor, open it before calling the superclass's emit.
1045 """
1046 if self.stream is None:
Vinay Sajip6268cbc2009-01-21 00:19:28 +00001047 self.stream = self._open()
Christian Heimese7a15bb2008-01-24 16:21:45 +00001048 StreamHandler.emit(self, record)
1049
Vinay Sajip5a27d402010-12-10 11:42:57 +00001050class _StderrHandler(StreamHandler):
1051 """
1052 This class is like a StreamHandler using sys.stderr, but always uses
1053 whatever sys.stderr is currently set to rather than the value of
1054 sys.stderr at handler construction time.
1055 """
1056 def __init__(self, level=NOTSET):
1057 """
1058 Initialize the handler.
1059 """
1060 Handler.__init__(self, level)
1061
1062 @property
1063 def stream(self):
1064 return sys.stderr
1065
1066
1067_defaultLastResort = _StderrHandler(WARNING)
1068lastResort = _defaultLastResort
1069
Guido van Rossum57102f82002-11-13 16:15:58 +00001070#---------------------------------------------------------------------------
1071# Manager classes and functions
1072#---------------------------------------------------------------------------
1073
Benjamin Peterson55549932009-11-25 17:19:56 +00001074class PlaceHolder(object):
Guido van Rossum57102f82002-11-13 16:15:58 +00001075 """
1076 PlaceHolder instances are used in the Manager logger hierarchy to take
Vinay Sajip3f742842004-02-28 16:07:46 +00001077 the place of nodes for which no loggers have been defined. This class is
1078 intended for internal use only and not as part of the public API.
Guido van Rossum57102f82002-11-13 16:15:58 +00001079 """
1080 def __init__(self, alogger):
1081 """
1082 Initialize with the specified logger being a child of this placeholder.
1083 """
Vinay Sajip239322b2005-10-14 09:36:35 +00001084 self.loggerMap = { alogger : None }
Guido van Rossum57102f82002-11-13 16:15:58 +00001085
1086 def append(self, alogger):
1087 """
1088 Add the specified logger as a child of this placeholder.
1089 """
Guido van Rossum93662412006-08-19 16:09:41 +00001090 if alogger not in self.loggerMap:
Vinay Sajip239322b2005-10-14 09:36:35 +00001091 self.loggerMap[alogger] = None
Guido van Rossum57102f82002-11-13 16:15:58 +00001092
1093#
1094# Determine which class to use when instantiating loggers.
1095#
Guido van Rossum57102f82002-11-13 16:15:58 +00001096
1097def setLoggerClass(klass):
1098 """
1099 Set the class to be used when instantiating a logger. The class should
1100 define __init__() such that only a name argument is required, and the
1101 __init__() should call Logger.__init__()
1102 """
1103 if klass != Logger:
Guido van Rossum57102f82002-11-13 16:15:58 +00001104 if not issubclass(klass, Logger):
Collin Winterce36ad82007-08-30 01:19:48 +00001105 raise TypeError("logger not derived from logging.Logger: "
1106 + klass.__name__)
Guido van Rossum57102f82002-11-13 16:15:58 +00001107 global _loggerClass
1108 _loggerClass = klass
1109
Vinay Sajipb9591172004-09-22 12:39:26 +00001110def getLoggerClass():
1111 """
1112 Return the class to be used when instantiating a logger.
1113 """
Vinay Sajipb9591172004-09-22 12:39:26 +00001114 return _loggerClass
1115
Benjamin Peterson55549932009-11-25 17:19:56 +00001116class Manager(object):
Guido van Rossum57102f82002-11-13 16:15:58 +00001117 """
1118 There is [under normal circumstances] just one Manager instance, which
1119 holds the hierarchy of loggers.
1120 """
Neal Norwitzd1cade02002-11-15 23:31:28 +00001121 def __init__(self, rootnode):
Guido van Rossum57102f82002-11-13 16:15:58 +00001122 """
1123 Initialize the manager with the root node of the logger hierarchy.
1124 """
Neal Norwitzd1cade02002-11-15 23:31:28 +00001125 self.root = rootnode
Guido van Rossum57102f82002-11-13 16:15:58 +00001126 self.disable = 0
Vinay Sajip5a27d402010-12-10 11:42:57 +00001127 self.emittedNoHandlerWarning = False
Guido van Rossum57102f82002-11-13 16:15:58 +00001128 self.loggerDict = {}
Vinay Sajipdb81c4c2010-02-25 23:13:06 +00001129 self.loggerClass = None
Vinay Sajip61561522010-12-03 11:50:38 +00001130 self.logRecordFactory = None
Guido van Rossum57102f82002-11-13 16:15:58 +00001131
1132 def getLogger(self, name):
1133 """
1134 Get a logger with the specified name (channel name), creating it
Vinay Sajipb9591172004-09-22 12:39:26 +00001135 if it doesn't yet exist. This name is a dot-separated hierarchical
1136 name, such as "a", "a.b", "a.b.c" or similar.
Guido van Rossum57102f82002-11-13 16:15:58 +00001137
1138 If a PlaceHolder existed for the specified name [i.e. the logger
1139 didn't exist but a child of it did], replace it with the created
1140 logger and fix up the parent/child references which pointed to the
1141 placeholder to now point to the logger.
1142 """
1143 rv = None
Vinay Sajip61b787e2011-11-07 08:53:03 +00001144 if not isinstance(name, str):
Vinay Sajip3bd56382011-11-07 10:15:08 +00001145 raise TypeError('A logger name must be a string')
Guido van Rossum57102f82002-11-13 16:15:58 +00001146 _acquireLock()
1147 try:
Guido van Rossum93662412006-08-19 16:09:41 +00001148 if name in self.loggerDict:
Guido van Rossum57102f82002-11-13 16:15:58 +00001149 rv = self.loggerDict[name]
1150 if isinstance(rv, PlaceHolder):
1151 ph = rv
Vinay Sajipdb81c4c2010-02-25 23:13:06 +00001152 rv = (self.loggerClass or _loggerClass)(name)
Guido van Rossum57102f82002-11-13 16:15:58 +00001153 rv.manager = self
1154 self.loggerDict[name] = rv
1155 self._fixupChildren(ph, rv)
1156 self._fixupParents(rv)
1157 else:
Vinay Sajipdb81c4c2010-02-25 23:13:06 +00001158 rv = (self.loggerClass or _loggerClass)(name)
Guido van Rossum57102f82002-11-13 16:15:58 +00001159 rv.manager = self
1160 self.loggerDict[name] = rv
1161 self._fixupParents(rv)
1162 finally:
1163 _releaseLock()
1164 return rv
1165
Vinay Sajipdb81c4c2010-02-25 23:13:06 +00001166 def setLoggerClass(self, klass):
1167 """
1168 Set the class to be used when instantiating a logger with this Manager.
1169 """
1170 if klass != Logger:
1171 if not issubclass(klass, Logger):
1172 raise TypeError("logger not derived from logging.Logger: "
1173 + klass.__name__)
1174 self.loggerClass = klass
1175
Vinay Sajip61561522010-12-03 11:50:38 +00001176 def setLogRecordFactory(self, factory):
Vinay Sajip6fac8172010-10-19 20:44:14 +00001177 """
Vinay Sajipfad058f2010-12-03 13:01:11 +00001178 Set the factory to be used when instantiating a log record with this
Vinay Sajip6fac8172010-10-19 20:44:14 +00001179 Manager.
1180 """
Vinay Sajip61561522010-12-03 11:50:38 +00001181 self.logRecordFactory = factory
Vinay Sajip6fac8172010-10-19 20:44:14 +00001182
Guido van Rossum57102f82002-11-13 16:15:58 +00001183 def _fixupParents(self, alogger):
1184 """
1185 Ensure that there are either loggers or placeholders all the way
1186 from the specified logger to the root of the logger hierarchy.
1187 """
1188 name = alogger.name
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001189 i = name.rfind(".")
Guido van Rossum57102f82002-11-13 16:15:58 +00001190 rv = None
1191 while (i > 0) and not rv:
1192 substr = name[:i]
Guido van Rossum93662412006-08-19 16:09:41 +00001193 if substr not in self.loggerDict:
Guido van Rossum57102f82002-11-13 16:15:58 +00001194 self.loggerDict[substr] = PlaceHolder(alogger)
1195 else:
1196 obj = self.loggerDict[substr]
1197 if isinstance(obj, Logger):
1198 rv = obj
1199 else:
1200 assert isinstance(obj, PlaceHolder)
1201 obj.append(alogger)
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001202 i = name.rfind(".", 0, i - 1)
Guido van Rossum57102f82002-11-13 16:15:58 +00001203 if not rv:
1204 rv = self.root
1205 alogger.parent = rv
1206
1207 def _fixupChildren(self, ph, alogger):
1208 """
1209 Ensure that children of the placeholder ph are connected to the
1210 specified logger.
1211 """
Thomas Wouters89f507f2006-12-13 04:49:30 +00001212 name = alogger.name
1213 namelen = len(name)
Vinay Sajip239322b2005-10-14 09:36:35 +00001214 for c in ph.loggerMap.keys():
Thomas Wouters89f507f2006-12-13 04:49:30 +00001215 #The if means ... if not c.parent.name.startswith(nm)
1216 if c.parent.name[:namelen] != name:
Guido van Rossum57102f82002-11-13 16:15:58 +00001217 alogger.parent = c.parent
1218 c.parent = alogger
1219
1220#---------------------------------------------------------------------------
1221# Logger classes and functions
1222#---------------------------------------------------------------------------
1223
1224class Logger(Filterer):
1225 """
1226 Instances of the Logger class represent a single logging channel. A
1227 "logging channel" indicates an area of an application. Exactly how an
1228 "area" is defined is up to the application developer. Since an
1229 application can have any number of areas, logging channels are identified
1230 by a unique string. Application areas can be nested (e.g. an area
1231 of "input processing" might include sub-areas "read CSV files", "read
1232 XLS files" and "read Gnumeric files"). To cater for this natural nesting,
1233 channel names are organized into a namespace hierarchy where levels are
1234 separated by periods, much like the Java or Python package namespace. So
1235 in the instance given above, channel names might be "input" for the upper
1236 level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels.
1237 There is no arbitrary limit to the depth of nesting.
1238 """
1239 def __init__(self, name, level=NOTSET):
1240 """
1241 Initialize the logger with a name and an optional level.
1242 """
1243 Filterer.__init__(self)
1244 self.name = name
Vinay Sajipd4fabf42009-07-13 11:28:25 +00001245 self.level = _checkLevel(level)
Guido van Rossum57102f82002-11-13 16:15:58 +00001246 self.parent = None
Vinay Sajip312cc0d2011-04-30 21:51:51 +01001247 self.propagate = True
Guido van Rossum57102f82002-11-13 16:15:58 +00001248 self.handlers = []
Vinay Sajip312cc0d2011-04-30 21:51:51 +01001249 self.disabled = False
Guido van Rossum57102f82002-11-13 16:15:58 +00001250
1251 def setLevel(self, level):
1252 """
Gregory P. Smithe85488c2011-12-17 12:36:34 -08001253 Set the logging level of this logger. level must be an int or a str.
Guido van Rossum57102f82002-11-13 16:15:58 +00001254 """
Vinay Sajipd4fabf42009-07-13 11:28:25 +00001255 self.level = _checkLevel(level)
Guido van Rossum57102f82002-11-13 16:15:58 +00001256
Guido van Rossum57102f82002-11-13 16:15:58 +00001257 def debug(self, msg, *args, **kwargs):
1258 """
1259 Log 'msg % args' with severity 'DEBUG'.
1260
1261 To pass exception information, use the keyword argument exc_info with
1262 a true value, e.g.
1263
1264 logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
1265 """
Guido van Rossum04110fb2007-08-24 16:32:05 +00001266 if self.isEnabledFor(DEBUG):
Neal Norwitzd9108552006-03-17 08:00:19 +00001267 self._log(DEBUG, msg, args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001268
1269 def info(self, msg, *args, **kwargs):
1270 """
1271 Log 'msg % args' with severity 'INFO'.
1272
1273 To pass exception information, use the keyword argument exc_info with
1274 a true value, e.g.
1275
1276 logger.info("Houston, we have a %s", "interesting problem", exc_info=1)
1277 """
Guido van Rossum04110fb2007-08-24 16:32:05 +00001278 if self.isEnabledFor(INFO):
Neal Norwitzd9108552006-03-17 08:00:19 +00001279 self._log(INFO, msg, args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001280
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001281 def warning(self, msg, *args, **kwargs):
Guido van Rossum57102f82002-11-13 16:15:58 +00001282 """
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001283 Log 'msg % args' with severity 'WARNING'.
Guido van Rossum57102f82002-11-13 16:15:58 +00001284
1285 To pass exception information, use the keyword argument exc_info with
1286 a true value, e.g.
1287
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001288 logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)
Guido van Rossum57102f82002-11-13 16:15:58 +00001289 """
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001290 if self.isEnabledFor(WARNING):
Neal Norwitzd9108552006-03-17 08:00:19 +00001291 self._log(WARNING, msg, args, **kwargs)
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001292
Vinay Sajip04d5bc02011-10-21 07:33:42 +01001293 def warn(self, msg, *args, **kwargs):
1294 warnings.warn("The 'warn' method is deprecated, "
Vinay Sajip0a889532011-10-22 13:34:48 +01001295 "use 'warning' instead", DeprecationWarning, 2)
Vinay Sajip04d5bc02011-10-21 07:33:42 +01001296 self.warning(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001297
1298 def error(self, msg, *args, **kwargs):
1299 """
1300 Log 'msg % args' with severity 'ERROR'.
1301
1302 To pass exception information, use the keyword argument exc_info with
1303 a true value, e.g.
1304
1305 logger.error("Houston, we have a %s", "major problem", exc_info=1)
1306 """
Guido van Rossum57102f82002-11-13 16:15:58 +00001307 if self.isEnabledFor(ERROR):
Neal Norwitzd9108552006-03-17 08:00:19 +00001308 self._log(ERROR, msg, args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001309
Vinay Sajip02a8f9e2014-09-14 21:29:11 +01001310 def exception(self, msg, *args, exc_info=True, **kwargs):
Guido van Rossum57102f82002-11-13 16:15:58 +00001311 """
1312 Convenience method for logging an ERROR with exception information.
1313 """
Vinay Sajip02a8f9e2014-09-14 21:29:11 +01001314 self.error(msg, *args, exc_info=exc_info, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001315
1316 def critical(self, msg, *args, **kwargs):
1317 """
1318 Log 'msg % args' with severity 'CRITICAL'.
1319
1320 To pass exception information, use the keyword argument exc_info with
1321 a true value, e.g.
1322
1323 logger.critical("Houston, we have a %s", "major disaster", exc_info=1)
1324 """
Guido van Rossum04110fb2007-08-24 16:32:05 +00001325 if self.isEnabledFor(CRITICAL):
Neal Norwitzd9108552006-03-17 08:00:19 +00001326 self._log(CRITICAL, msg, args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001327
1328 fatal = critical
1329
1330 def log(self, level, msg, *args, **kwargs):
1331 """
Vinay Sajipeb477d02004-08-04 08:38:08 +00001332 Log 'msg % args' with the integer severity 'level'.
Guido van Rossum57102f82002-11-13 16:15:58 +00001333
1334 To pass exception information, use the keyword argument exc_info with
1335 a true value, e.g.
1336
1337 logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
1338 """
Guido van Rossum13257902007-06-07 23:15:56 +00001339 if not isinstance(level, int):
Vinay Sajip779e0c92004-07-03 11:47:26 +00001340 if raiseExceptions:
Collin Winterce36ad82007-08-30 01:19:48 +00001341 raise TypeError("level must be an integer")
Vinay Sajip779e0c92004-07-03 11:47:26 +00001342 else:
1343 return
Guido van Rossum57102f82002-11-13 16:15:58 +00001344 if self.isEnabledFor(level):
Neal Norwitzd9108552006-03-17 08:00:19 +00001345 self._log(level, msg, args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001346
Vinay Sajip8593ae62010-11-14 21:33:04 +00001347 def findCaller(self, stack_info=False):
Guido van Rossum57102f82002-11-13 16:15:58 +00001348 """
1349 Find the stack frame of the caller so that we can note the source
Vinay Sajip829dc512005-02-18 11:53:32 +00001350 file name, line number and function name.
Guido van Rossum57102f82002-11-13 16:15:58 +00001351 """
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001352 f = currentframe()
1353 #On some versions of IronPython, currentframe() returns None if
1354 #IronPython isn't run with -X:Frames.
1355 if f is not None:
1356 f = f.f_back
Vinay Sajip8593ae62010-11-14 21:33:04 +00001357 rv = "(unknown file)", 0, "(unknown function)", None
Thomas Woutersa9773292006-04-21 09:43:23 +00001358 while hasattr(f, "f_code"):
Jeremy Hylton250684d2003-01-23 18:29:29 +00001359 co = f.f_code
1360 filename = os.path.normcase(co.co_filename)
1361 if filename == _srcfile:
1362 f = f.f_back
1363 continue
Vinay Sajip8593ae62010-11-14 21:33:04 +00001364 sinfo = None
1365 if stack_info:
1366 sio = io.StringIO()
1367 sio.write('Stack (most recent call last):\n')
1368 traceback.print_stack(f, file=sio)
1369 sinfo = sio.getvalue()
1370 if sinfo[-1] == '\n':
1371 sinfo = sinfo[:-1]
1372 sio.close()
1373 rv = (co.co_filename, f.f_lineno, co.co_name, sinfo)
Thomas Woutersa9773292006-04-21 09:43:23 +00001374 break
1375 return rv
Guido van Rossum57102f82002-11-13 16:15:58 +00001376
Vinay Sajip8593ae62010-11-14 21:33:04 +00001377 def makeRecord(self, name, level, fn, lno, msg, args, exc_info,
1378 func=None, extra=None, sinfo=None):
Guido van Rossum57102f82002-11-13 16:15:58 +00001379 """
1380 A factory method which can be overridden in subclasses to create
1381 specialized LogRecords.
1382 """
Vinay Sajip61561522010-12-03 11:50:38 +00001383 rv = _logRecordFactory(name, level, fn, lno, msg, args, exc_info, func,
Vinay Sajip8593ae62010-11-14 21:33:04 +00001384 sinfo)
Christian Heimes04c420f2008-01-18 18:40:46 +00001385 if extra is not None:
Vinay Sajip260ce432006-02-09 08:34:14 +00001386 for key in extra:
1387 if (key in ["message", "asctime"]) or (key in rv.__dict__):
1388 raise KeyError("Attempt to overwrite %r in LogRecord" % key)
1389 rv.__dict__[key] = extra[key]
1390 return rv
Guido van Rossum57102f82002-11-13 16:15:58 +00001391
Vinay Sajip8593ae62010-11-14 21:33:04 +00001392 def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False):
Guido van Rossum57102f82002-11-13 16:15:58 +00001393 """
1394 Low-level logging routine which creates a LogRecord and then calls
1395 all the handlers of this logger to handle the record.
1396 """
Vinay Sajip8593ae62010-11-14 21:33:04 +00001397 sinfo = None
Jeremy Hylton250684d2003-01-23 18:29:29 +00001398 if _srcfile:
Andrew Svetlov737fb892012-12-18 21:14:22 +02001399 #IronPython doesn't track Python frames, so findCaller raises an
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001400 #exception on some versions of IronPython. We trap it here so that
1401 #IronPython can use logging.
Vinay Sajipb672b6d2009-02-19 12:36:11 +00001402 try:
Vinay Sajip8593ae62010-11-14 21:33:04 +00001403 fn, lno, func, sinfo = self.findCaller(stack_info)
Vinay Sajip26fe4b72011-04-26 18:43:05 +01001404 except ValueError: # pragma: no cover
Vinay Sajipb672b6d2009-02-19 12:36:11 +00001405 fn, lno, func = "(unknown file)", 0, "(unknown function)"
Vinay Sajip26fe4b72011-04-26 18:43:05 +01001406 else: # pragma: no cover
Vinay Sajip829dc512005-02-18 11:53:32 +00001407 fn, lno, func = "(unknown file)", 0, "(unknown function)"
Guido van Rossum57102f82002-11-13 16:15:58 +00001408 if exc_info:
Vinay Sajip02a8f9e2014-09-14 21:29:11 +01001409 if isinstance(exc_info, BaseException):
1410 exc_info = (type(exc_info), exc_info, exc_info.__traceback__)
1411 elif not isinstance(exc_info, tuple):
Vinay Sajiped6bb142004-02-20 13:18:36 +00001412 exc_info = sys.exc_info()
Vinay Sajip8593ae62010-11-14 21:33:04 +00001413 record = self.makeRecord(self.name, level, fn, lno, msg, args,
1414 exc_info, func, extra, sinfo)
Guido van Rossum57102f82002-11-13 16:15:58 +00001415 self.handle(record)
1416
1417 def handle(self, record):
1418 """
1419 Call the handlers for the specified record.
1420
1421 This method is used for unpickled records received from a socket, as
1422 well as those created locally. Logger-level filtering is applied.
1423 """
1424 if (not self.disabled) and self.filter(record):
1425 self.callHandlers(record)
1426
1427 def addHandler(self, hdlr):
1428 """
1429 Add the specified handler to this logger.
1430 """
Vinay Sajip32fb6a82010-09-25 17:42:36 +00001431 _acquireLock()
1432 try:
1433 if not (hdlr in self.handlers):
1434 self.handlers.append(hdlr)
1435 finally:
1436 _releaseLock()
Guido van Rossum57102f82002-11-13 16:15:58 +00001437
1438 def removeHandler(self, hdlr):
1439 """
1440 Remove the specified handler from this logger.
1441 """
Vinay Sajip32fb6a82010-09-25 17:42:36 +00001442 _acquireLock()
1443 try:
1444 if hdlr in self.handlers:
Vinay Sajip116f16e2005-09-16 10:33:40 +00001445 self.handlers.remove(hdlr)
Vinay Sajip32fb6a82010-09-25 17:42:36 +00001446 finally:
1447 _releaseLock()
Guido van Rossum57102f82002-11-13 16:15:58 +00001448
Vinay Sajipb4a08092010-09-20 09:55:00 +00001449 def hasHandlers(self):
1450 """
1451 See if this logger has any handlers configured.
1452
1453 Loop through all handlers for this logger and its parents in the
1454 logger hierarchy. Return True if a handler was found, else False.
1455 Stop searching up the hierarchy whenever a logger with the "propagate"
1456 attribute set to zero is found - that will be the last logger which
1457 is checked for the existence of handlers.
1458 """
1459 c = self
1460 rv = False
1461 while c:
1462 if c.handlers:
1463 rv = True
1464 break
1465 if not c.propagate:
1466 break
1467 else:
1468 c = c.parent
1469 return rv
1470
Guido van Rossum57102f82002-11-13 16:15:58 +00001471 def callHandlers(self, record):
1472 """
1473 Pass a record to all relevant handlers.
1474
1475 Loop through all handlers for this logger and its parents in the
1476 logger hierarchy. If no handler was found, output a one-off error
1477 message to sys.stderr. Stop searching up the hierarchy whenever a
1478 logger with the "propagate" attribute set to zero is found - that
1479 will be the last logger whose handlers are called.
1480 """
1481 c = self
1482 found = 0
1483 while c:
1484 for hdlr in c.handlers:
1485 found = found + 1
1486 if record.levelno >= hdlr.level:
1487 hdlr.handle(record)
1488 if not c.propagate:
1489 c = None #break out
1490 else:
1491 c = c.parent
Vinay Sajip5a27d402010-12-10 11:42:57 +00001492 if (found == 0):
1493 if lastResort:
Vinay Sajip45dedaa2011-07-25 19:53:28 +01001494 if record.levelno >= lastResort.level:
1495 lastResort.handle(record)
Vinay Sajip5a27d402010-12-10 11:42:57 +00001496 elif raiseExceptions and not self.manager.emittedNoHandlerWarning:
1497 sys.stderr.write("No handlers could be found for logger"
1498 " \"%s\"\n" % self.name)
1499 self.manager.emittedNoHandlerWarning = True
Guido van Rossum57102f82002-11-13 16:15:58 +00001500
1501 def getEffectiveLevel(self):
1502 """
1503 Get the effective level for this logger.
1504
1505 Loop through this logger and its parents in the logger hierarchy,
1506 looking for a non-zero logging level. Return the first one found.
1507 """
1508 logger = self
1509 while logger:
1510 if logger.level:
1511 return logger.level
1512 logger = logger.parent
1513 return NOTSET
1514
1515 def isEnabledFor(self, level):
1516 """
1517 Is this logger enabled for level 'level'?
1518 """
1519 if self.manager.disable >= level:
Vinay Sajip26fe4b72011-04-26 18:43:05 +01001520 return False
Guido van Rossum57102f82002-11-13 16:15:58 +00001521 return level >= self.getEffectiveLevel()
1522
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001523 def getChild(self, suffix):
1524 """
1525 Get a logger which is a descendant to this one.
1526
1527 This is a convenience method, such that
1528
1529 logging.getLogger('abc').getChild('def.ghi')
1530
1531 is the same as
1532
1533 logging.getLogger('abc.def.ghi')
1534
1535 It's useful, for example, when the parent logger is named using
1536 __name__ rather than a literal string.
1537 """
1538 if self.root is not self:
1539 suffix = '.'.join((self.name, suffix))
1540 return self.manager.getLogger(suffix)
1541
Guido van Rossum57102f82002-11-13 16:15:58 +00001542class RootLogger(Logger):
1543 """
1544 A root logger is not that different to any other logger, except that
1545 it must have a logging level and there is only one instance of it in
1546 the hierarchy.
1547 """
1548 def __init__(self, level):
1549 """
1550 Initialize the logger with the name "root".
1551 """
1552 Logger.__init__(self, "root", level)
1553
1554_loggerClass = Logger
1555
Benjamin Peterson55549932009-11-25 17:19:56 +00001556class LoggerAdapter(object):
Christian Heimes04c420f2008-01-18 18:40:46 +00001557 """
1558 An adapter for loggers which makes it easier to specify contextual
1559 information in logging output.
1560 """
1561
1562 def __init__(self, logger, extra):
1563 """
1564 Initialize the adapter with a logger and a dict-like object which
1565 provides contextual information. This constructor signature allows
1566 easy stacking of LoggerAdapters, if so desired.
1567
1568 You can effectively pass keyword arguments as shown in the
1569 following example:
1570
1571 adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2"))
1572 """
1573 self.logger = logger
1574 self.extra = extra
1575
1576 def process(self, msg, kwargs):
1577 """
1578 Process the logging message and keyword arguments passed in to
1579 a logging call to insert contextual information. You can either
1580 manipulate the message itself, the keyword args or both. Return
1581 the message and kwargs modified (or not) to suit your needs.
1582
1583 Normally, you'll only need to override this one method in a
1584 LoggerAdapter subclass for your specific needs.
1585 """
1586 kwargs["extra"] = self.extra
1587 return msg, kwargs
1588
Vinay Sajip212b5902010-09-21 11:31:32 +00001589 #
1590 # Boilerplate convenience methods
1591 #
Christian Heimes04c420f2008-01-18 18:40:46 +00001592 def debug(self, msg, *args, **kwargs):
1593 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001594 Delegate a debug call to the underlying logger.
Christian Heimes04c420f2008-01-18 18:40:46 +00001595 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001596 self.log(DEBUG, msg, *args, **kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00001597
1598 def info(self, msg, *args, **kwargs):
1599 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001600 Delegate an info call to the underlying logger.
Christian Heimes04c420f2008-01-18 18:40:46 +00001601 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001602 self.log(INFO, msg, *args, **kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00001603
1604 def warning(self, msg, *args, **kwargs):
1605 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001606 Delegate a warning call to the underlying logger.
Christian Heimes04c420f2008-01-18 18:40:46 +00001607 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001608 self.log(WARNING, msg, *args, **kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00001609
Vinay Sajip04d5bc02011-10-21 07:33:42 +01001610 def warn(self, msg, *args, **kwargs):
1611 warnings.warn("The 'warn' method is deprecated, "
Vinay Sajip0a889532011-10-22 13:34:48 +01001612 "use 'warning' instead", DeprecationWarning, 2)
Vinay Sajip04d5bc02011-10-21 07:33:42 +01001613 self.warning(msg, *args, **kwargs)
Vinay Sajipc84f0162010-09-21 11:25:39 +00001614
Christian Heimes04c420f2008-01-18 18:40:46 +00001615 def error(self, msg, *args, **kwargs):
1616 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001617 Delegate an error call to the underlying logger.
Christian Heimes04c420f2008-01-18 18:40:46 +00001618 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001619 self.log(ERROR, msg, *args, **kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00001620
Vinay Sajip02a8f9e2014-09-14 21:29:11 +01001621 def exception(self, msg, *args, exc_info=True, **kwargs):
Christian Heimes04c420f2008-01-18 18:40:46 +00001622 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001623 Delegate an exception call to the underlying logger.
Christian Heimes04c420f2008-01-18 18:40:46 +00001624 """
Vinay Sajip02a8f9e2014-09-14 21:29:11 +01001625 self.log(ERROR, msg, *args, exc_info=exc_info, **kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00001626
1627 def critical(self, msg, *args, **kwargs):
1628 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001629 Delegate a critical call to the underlying logger.
Christian Heimes04c420f2008-01-18 18:40:46 +00001630 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001631 self.log(CRITICAL, msg, *args, **kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00001632
1633 def log(self, level, msg, *args, **kwargs):
1634 """
1635 Delegate a log call to the underlying logger, after adding
1636 contextual information from this adapter instance.
1637 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001638 if self.isEnabledFor(level):
1639 msg, kwargs = self.process(msg, kwargs)
1640 self.logger._log(level, msg, args, **kwargs)
1641
1642 def isEnabledFor(self, level):
1643 """
1644 Is this logger enabled for level 'level'?
1645 """
1646 if self.logger.manager.disable >= level:
1647 return False
1648 return level >= self.getEffectiveLevel()
Christian Heimes04c420f2008-01-18 18:40:46 +00001649
Vinay Sajipc84f0162010-09-21 11:25:39 +00001650 def setLevel(self, level):
1651 """
1652 Set the specified level on the underlying logger.
1653 """
1654 self.logger.setLevel(level)
1655
Vinay Sajipc84f0162010-09-21 11:25:39 +00001656 def getEffectiveLevel(self):
1657 """
1658 Get the effective level for the underlying logger.
1659 """
1660 return self.logger.getEffectiveLevel()
1661
Vinay Sajip61c3f0d2010-09-20 10:13:13 +00001662 def hasHandlers(self):
1663 """
1664 See if the underlying logger has any handlers.
1665 """
1666 return self.logger.hasHandlers()
1667
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001668root = RootLogger(WARNING)
Guido van Rossum57102f82002-11-13 16:15:58 +00001669Logger.root = root
1670Logger.manager = Manager(Logger.root)
1671
1672#---------------------------------------------------------------------------
1673# Configuration classes and functions
1674#---------------------------------------------------------------------------
1675
Vinay Sajip779e0c92004-07-03 11:47:26 +00001676def basicConfig(**kwargs):
Guido van Rossum57102f82002-11-13 16:15:58 +00001677 """
Vinay Sajip779e0c92004-07-03 11:47:26 +00001678 Do basic configuration for the logging system.
1679
1680 This function does nothing if the root logger already has handlers
1681 configured. It is a convenience method intended for use by simple scripts
1682 to do one-shot configuration of the logging package.
1683
1684 The default behaviour is to create a StreamHandler which writes to
1685 sys.stderr, set a formatter using the BASIC_FORMAT format string, and
1686 add the handler to the root logger.
1687
1688 A number of optional keyword arguments may be specified, which can alter
1689 the default behaviour.
1690
1691 filename Specifies that a FileHandler be created, using the specified
1692 filename, rather than a StreamHandler.
1693 filemode Specifies the mode to open the file, if filename is specified
Vinay Sajipb89e7c92005-03-13 09:54:31 +00001694 (if filemode is unspecified, it defaults to 'a').
Vinay Sajip779e0c92004-07-03 11:47:26 +00001695 format Use the specified format string for the handler.
1696 datefmt Use the specified date/time format.
Vinay Sajipc5b27302010-10-31 14:59:16 +00001697 style If a format string is specified, use this to specify the
1698 type of format string (possible values '%', '{', '$', for
1699 %-formatting, :meth:`str.format` and :class:`string.Template`
1700 - defaults to '%').
Vinay Sajip779e0c92004-07-03 11:47:26 +00001701 level Set the root logger level to the specified level.
1702 stream Use the specified stream to initialize the StreamHandler. Note
1703 that this argument is incompatible with 'filename' - if both
1704 are present, 'stream' is ignored.
Vinay Sajip4a0a31d2011-04-11 08:42:07 +01001705 handlers If specified, this should be an iterable of already created
1706 handlers, which will be added to the root handler. Any handler
1707 in the list which does not have a formatter assigned will be
1708 assigned the formatter created in this function.
Vinay Sajip779e0c92004-07-03 11:47:26 +00001709
1710 Note that you could specify a stream created using open(filename, mode)
1711 rather than passing the filename and mode in. However, it should be
1712 remembered that StreamHandler does not close its stream (since it may be
1713 using sys.stdout or sys.stderr), whereas FileHandler closes its stream
1714 when the handler is closed.
Vinay Sajipc5b27302010-10-31 14:59:16 +00001715
Vinay Sajip4a0a31d2011-04-11 08:42:07 +01001716 .. versionchanged:: 3.2
Vinay Sajipc5b27302010-10-31 14:59:16 +00001717 Added the ``style`` parameter.
Vinay Sajipa3359ee2011-04-11 08:43:52 +01001718
Vinay Sajip4a0a31d2011-04-11 08:42:07 +01001719 .. versionchanged:: 3.3
1720 Added the ``handlers`` parameter. A ``ValueError`` is now thrown for
1721 incompatible arguments (e.g. ``handlers`` specified together with
1722 ``filename``/``filemode``, or ``filename``/``filemode`` specified
1723 together with ``stream``, or ``handlers`` specified together with
1724 ``stream``.
Guido van Rossum57102f82002-11-13 16:15:58 +00001725 """
Vinay Sajip2314fc72010-09-10 08:25:13 +00001726 # Add thread safety in case someone mistakenly calls
1727 # basicConfig() from multiple threads
1728 _acquireLock()
1729 try:
1730 if len(root.handlers) == 0:
Vinay Sajip5abca702015-01-23 19:52:21 +00001731 handlers = kwargs.pop("handlers", None)
Vinay Sajip4a0a31d2011-04-11 08:42:07 +01001732 if handlers is None:
1733 if "stream" in kwargs and "filename" in kwargs:
1734 raise ValueError("'stream' and 'filename' should not be "
1735 "specified together")
Vinay Sajip2314fc72010-09-10 08:25:13 +00001736 else:
Vinay Sajip4a0a31d2011-04-11 08:42:07 +01001737 if "stream" in kwargs or "filename" in kwargs:
1738 raise ValueError("'stream' or 'filename' should not be "
1739 "specified together with 'handlers'")
1740 if handlers is None:
Vinay Sajip5abca702015-01-23 19:52:21 +00001741 filename = kwargs.pop("filename", None)
Vinay Sajipd55436a2015-03-18 08:47:58 +00001742 mode = kwargs.pop("filemode", 'a')
Vinay Sajip4a0a31d2011-04-11 08:42:07 +01001743 if filename:
Vinay Sajip4a0a31d2011-04-11 08:42:07 +01001744 h = FileHandler(filename, mode)
1745 else:
Vinay Sajip5abca702015-01-23 19:52:21 +00001746 stream = kwargs.pop("stream", None)
Vinay Sajip4a0a31d2011-04-11 08:42:07 +01001747 h = StreamHandler(stream)
1748 handlers = [h]
Vinay Sajip5abca702015-01-23 19:52:21 +00001749 dfs = kwargs.pop("datefmt", None)
1750 style = kwargs.pop("style", '%')
Vinay Sajip1fd12022014-01-13 21:59:56 +00001751 if style not in _STYLES:
1752 raise ValueError('Style must be one of: %s' % ','.join(
1753 _STYLES.keys()))
Vinay Sajip5abca702015-01-23 19:52:21 +00001754 fs = kwargs.pop("format", _STYLES[style][1])
Vinay Sajipc5b27302010-10-31 14:59:16 +00001755 fmt = Formatter(fs, dfs, style)
Vinay Sajip4a0a31d2011-04-11 08:42:07 +01001756 for h in handlers:
1757 if h.formatter is None:
1758 h.setFormatter(fmt)
1759 root.addHandler(h)
Vinay Sajip5abca702015-01-23 19:52:21 +00001760 level = kwargs.pop("level", None)
Vinay Sajip2314fc72010-09-10 08:25:13 +00001761 if level is not None:
1762 root.setLevel(level)
Vinay Sajip5abca702015-01-23 19:52:21 +00001763 if kwargs:
1764 keys = ', '.join(kwargs.keys())
1765 raise ValueError('Unrecognised argument(s): %s' % keys)
Vinay Sajip2314fc72010-09-10 08:25:13 +00001766 finally:
1767 _releaseLock()
Guido van Rossum57102f82002-11-13 16:15:58 +00001768
1769#---------------------------------------------------------------------------
1770# Utility functions at module level.
1771# Basically delegate everything to the root logger.
1772#---------------------------------------------------------------------------
1773
1774def getLogger(name=None):
1775 """
1776 Return a logger with the specified name, creating it if necessary.
1777
1778 If no name is specified, return the root logger.
1779 """
1780 if name:
1781 return Logger.manager.getLogger(name)
1782 else:
1783 return root
1784
Guido van Rossum57102f82002-11-13 16:15:58 +00001785def critical(msg, *args, **kwargs):
1786 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001787 Log a message with severity 'CRITICAL' on the root logger. If the logger
1788 has no handlers, call basicConfig() to add a console handler with a
1789 pre-defined format.
Guido van Rossum57102f82002-11-13 16:15:58 +00001790 """
1791 if len(root.handlers) == 0:
1792 basicConfig()
Neal Norwitzd9108552006-03-17 08:00:19 +00001793 root.critical(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001794
1795fatal = critical
1796
1797def error(msg, *args, **kwargs):
1798 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001799 Log a message with severity 'ERROR' on the root logger. If the logger has
1800 no handlers, call basicConfig() to add a console handler with a pre-defined
1801 format.
Guido van Rossum57102f82002-11-13 16:15:58 +00001802 """
1803 if len(root.handlers) == 0:
1804 basicConfig()
Neal Norwitzd9108552006-03-17 08:00:19 +00001805 root.error(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001806
Vinay Sajip02a8f9e2014-09-14 21:29:11 +01001807def exception(msg, *args, exc_info=True, **kwargs):
Guido van Rossum57102f82002-11-13 16:15:58 +00001808 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001809 Log a message with severity 'ERROR' on the root logger, with exception
1810 information. If the logger has no handlers, basicConfig() is called to add
1811 a console handler with a pre-defined format.
Guido van Rossum57102f82002-11-13 16:15:58 +00001812 """
Vinay Sajip02a8f9e2014-09-14 21:29:11 +01001813 error(msg, *args, exc_info=exc_info, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001814
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001815def warning(msg, *args, **kwargs):
Guido van Rossum57102f82002-11-13 16:15:58 +00001816 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001817 Log a message with severity 'WARNING' on the root logger. If the logger has
1818 no handlers, call basicConfig() to add a console handler with a pre-defined
1819 format.
Guido van Rossum57102f82002-11-13 16:15:58 +00001820 """
1821 if len(root.handlers) == 0:
1822 basicConfig()
Neal Norwitzd9108552006-03-17 08:00:19 +00001823 root.warning(msg, *args, **kwargs)
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001824
Vinay Sajip04d5bc02011-10-21 07:33:42 +01001825def warn(msg, *args, **kwargs):
1826 warnings.warn("The 'warn' function is deprecated, "
Vinay Sajip0a889532011-10-22 13:34:48 +01001827 "use 'warning' instead", DeprecationWarning, 2)
Vinay Sajip04d5bc02011-10-21 07:33:42 +01001828 warning(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001829
1830def info(msg, *args, **kwargs):
1831 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001832 Log a message with severity 'INFO' on the root logger. If the logger has
1833 no handlers, call basicConfig() to add a console handler with a pre-defined
1834 format.
Guido van Rossum57102f82002-11-13 16:15:58 +00001835 """
1836 if len(root.handlers) == 0:
1837 basicConfig()
Neal Norwitzd9108552006-03-17 08:00:19 +00001838 root.info(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001839
1840def debug(msg, *args, **kwargs):
1841 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001842 Log a message with severity 'DEBUG' on the root logger. If the logger has
1843 no handlers, call basicConfig() to add a console handler with a pre-defined
1844 format.
Guido van Rossum57102f82002-11-13 16:15:58 +00001845 """
1846 if len(root.handlers) == 0:
1847 basicConfig()
Neal Norwitzd9108552006-03-17 08:00:19 +00001848 root.debug(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001849
Vinay Sajipb2635b22004-09-24 11:45:52 +00001850def log(level, msg, *args, **kwargs):
1851 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001852 Log 'msg % args' with the integer severity 'level' on the root logger. If
1853 the logger has no handlers, call basicConfig() to add a console handler
1854 with a pre-defined format.
Vinay Sajipb2635b22004-09-24 11:45:52 +00001855 """
1856 if len(root.handlers) == 0:
1857 basicConfig()
Neal Norwitzd9108552006-03-17 08:00:19 +00001858 root.log(level, msg, *args, **kwargs)
Vinay Sajipb2635b22004-09-24 11:45:52 +00001859
Guido van Rossum57102f82002-11-13 16:15:58 +00001860def disable(level):
1861 """
Benjamin Peterson886af962010-03-21 23:13:07 +00001862 Disable all logging calls of severity 'level' and below.
Guido van Rossum57102f82002-11-13 16:15:58 +00001863 """
1864 root.manager.disable = level
1865
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001866def shutdown(handlerList=_handlerList):
Guido van Rossum57102f82002-11-13 16:15:58 +00001867 """
1868 Perform any cleanup actions in the logging system (e.g. flushing
1869 buffers).
1870
1871 Should be called at application exit.
1872 """
Benjamin Peterson55549932009-11-25 17:19:56 +00001873 for wr in reversed(handlerList[:]):
Vinay Sajipe12f7152004-07-29 09:19:30 +00001874 #errors might occur, for example, if files are locked
Vinay Sajip260ce432006-02-09 08:34:14 +00001875 #we just ignore them if raiseExceptions is not set
Vinay Sajipe12f7152004-07-29 09:19:30 +00001876 try:
Benjamin Peterson55549932009-11-25 17:19:56 +00001877 h = wr()
Vinay Sajipde6e9d62010-08-23 17:50:30 +00001878 if h:
1879 try:
Vinay Sajipd9512e92011-03-08 22:53:21 +00001880 h.acquire()
Vinay Sajipde6e9d62010-08-23 17:50:30 +00001881 h.flush()
1882 h.close()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001883 except (OSError, ValueError):
Vinay Sajipde6e9d62010-08-23 17:50:30 +00001884 # Ignore errors which might be caused
1885 # because handlers have been closed but
1886 # references to them are still around at
1887 # application exit.
1888 pass
Vinay Sajipd9512e92011-03-08 22:53:21 +00001889 finally:
1890 h.release()
Vinay Sajip8cf4eb12012-10-09 08:06:13 +01001891 except: # ignore everything, as we're shutting down
Vinay Sajip260ce432006-02-09 08:34:14 +00001892 if raiseExceptions:
1893 raise
1894 #else, swallow
Vinay Sajiped6bb142004-02-20 13:18:36 +00001895
1896#Let's try and shutdown automatically on application exit...
Georg Brandl01e4d572010-02-06 22:27:51 +00001897import atexit
1898atexit.register(shutdown)
Georg Brandlf9734072008-12-07 15:30:06 +00001899
1900# Null handler
1901
1902class NullHandler(Handler):
1903 """
1904 This handler does nothing. It's intended to be used to avoid the
1905 "No handlers could be found for logger XXX" one-off warning. This is
1906 important for library code, which may contain code to log events. If a user
1907 of the library does not configure logging, the one-off warning might be
1908 produced; to avoid this, the library developer simply needs to instantiate
1909 a NullHandler and add it to the top-level logger of the library module or
1910 package.
1911 """
Vinay Sajip4fbe4b32010-09-26 11:04:10 +00001912 def handle(self, record):
Vinay Sajipe6c1eb92011-03-29 17:20:34 +01001913 """Stub."""
Vinay Sajip4fbe4b32010-09-26 11:04:10 +00001914
Georg Brandlf9734072008-12-07 15:30:06 +00001915 def emit(self, record):
Vinay Sajipe6c1eb92011-03-29 17:20:34 +01001916 """Stub."""
Georg Brandlf9734072008-12-07 15:30:06 +00001917
Vinay Sajip4fbe4b32010-09-26 11:04:10 +00001918 def createLock(self):
1919 self.lock = None
1920
Georg Brandlf9734072008-12-07 15:30:06 +00001921# Warnings integration
1922
1923_warnings_showwarning = None
1924
1925def _showwarning(message, category, filename, lineno, file=None, line=None):
1926 """
1927 Implementation of showwarnings which redirects to logging, which will first
1928 check to see if the file parameter is None. If a file is specified, it will
1929 delegate to the original warnings implementation of showwarning. Otherwise,
1930 it will call warnings.formatwarning and will log the resulting string to a
1931 warnings logger named "py.warnings" with level logging.WARNING.
1932 """
1933 if file is not None:
1934 if _warnings_showwarning is not None:
1935 _warnings_showwarning(message, category, filename, lineno, file, line)
1936 else:
1937 s = warnings.formatwarning(message, category, filename, lineno, line)
1938 logger = getLogger("py.warnings")
1939 if not logger.handlers:
1940 logger.addHandler(NullHandler())
1941 logger.warning("%s", s)
1942
1943def captureWarnings(capture):
1944 """
1945 If capture is true, redirect all warnings to the logging package.
1946 If capture is False, ensure that warnings are not redirected to logging
1947 but to their original destinations.
1948 """
1949 global _warnings_showwarning
1950 if capture:
1951 if _warnings_showwarning is None:
1952 _warnings_showwarning = warnings.showwarning
1953 warnings.showwarning = _showwarning
1954 else:
1955 if _warnings_showwarning is not None:
1956 warnings.showwarning = _warnings_showwarning
1957 _warnings_showwarning = None