blob: e1c4a37b535bc9a91ba71e0cc7865d9568f9b094 [file] [log] [blame]
Vinay Sajipdb81c4c2010-02-25 23:13:06 +00001# Copyright 2001-2010 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
19comp.lang.python, and influenced by Apache's log4j system.
20
Benjamin Peterson46a99002010-01-09 18:45:30 +000021Copyright (C) 2001-2010 Vinay Sajip. All Rights Reserved.
Guido van Rossum57102f82002-11-13 16:15:58 +000022
23To use, simply 'import logging' and log away!
24"""
25
Benjamin Peterson55549932009-11-25 17:19:56 +000026import sys, os, time, io, traceback, warnings, weakref
Vinay Sajip6a65c5d2010-10-26 13:16:11 +000027from string import Template
Georg Brandlf9734072008-12-07 15:30:06 +000028
Christian Heimes18c66892008-02-17 13:31:39 +000029__all__ = ['BASIC_FORMAT', 'BufferingFormatter', 'CRITICAL', 'DEBUG', 'ERROR',
Vinay Sajipad5fa2f2009-04-27 13:55:05 +000030 'FATAL', 'FileHandler', 'Filter', 'Formatter', 'Handler', 'INFO',
31 'LogRecord', 'Logger', 'LoggerAdapter', 'NOTSET', 'NullHandler',
32 'StreamHandler', 'WARN', 'WARNING', 'addLevelName', 'basicConfig',
33 'captureWarnings', 'critical', 'debug', 'disable', 'error',
34 'exception', 'fatal', 'getLevelName', 'getLogger', 'getLoggerClass',
Vinay Sajip062d56b2010-10-19 15:26:24 +000035 'info', 'log', 'makeLogRecord', 'setLoggerClass', 'warn', 'warning',
Vinay Sajip5a27d402010-12-10 11:42:57 +000036 'getLogRecordFactory', 'setLogRecordFactory', 'lastResort']
Vinay Sajipb89e7c92005-03-13 09:54:31 +000037
38try:
39 import codecs
40except ImportError:
41 codecs = None
Guido van Rossum57102f82002-11-13 16:15:58 +000042
43try:
Georg Brandl2067bfd2008-05-25 13:05:15 +000044 import _thread as thread
Guido van Rossum57102f82002-11-13 16:15:58 +000045 import threading
46except ImportError:
47 thread = None
Guido van Rossum57102f82002-11-13 16:15:58 +000048
49__author__ = "Vinay Sajip <vinay_sajip@red-dove.com>"
Thomas Wouters477c8d52006-05-27 19:21:47 +000050__status__ = "production"
Vinay Sajipdb81c4c2010-02-25 23:13:06 +000051__version__ = "0.5.1.2"
52__date__ = "07 February 2010"
Guido van Rossum57102f82002-11-13 16:15:58 +000053
54#---------------------------------------------------------------------------
55# Miscellaneous module data
56#---------------------------------------------------------------------------
57
58#
Vinay Sajip829dc512005-02-18 11:53:32 +000059# _srcfile is used when walking the stack to check when we've got the first
Guido van Rossum57102f82002-11-13 16:15:58 +000060# caller stack frame.
Neal Norwitz6fa635d2003-02-18 14:20:07 +000061#
Vinay Sajipc384fc22005-09-02 11:20:33 +000062if hasattr(sys, 'frozen'): #support for py2exe
63 _srcfile = "logging%s__init__%s" % (os.sep, __file__[-4:])
Neal Norwitz9d72bb42007-04-17 08:48:32 +000064elif __file__[-4:].lower() in ['.pyc', '.pyo']:
Guido van Rossum455ab772002-11-13 16:18:29 +000065 _srcfile = __file__[:-4] + '.py'
Guido van Rossum57102f82002-11-13 16:15:58 +000066else:
Guido van Rossum455ab772002-11-13 16:18:29 +000067 _srcfile = __file__
68_srcfile = os.path.normcase(_srcfile)
Guido van Rossum57102f82002-11-13 16:15:58 +000069
Vinay Sajip829dc512005-02-18 11:53:32 +000070# next bit filched from 1.5.2's inspect.py
71def currentframe():
72 """Return the frame object for the caller's stack frame."""
73 try:
Neal Norwitz1e8659b2005-10-21 06:00:24 +000074 raise Exception
Vinay Sajip829dc512005-02-18 11:53:32 +000075 except:
Guido van Rossume7ba4952007-06-06 23:52:48 +000076 return sys.exc_info()[2].tb_frame.f_back
Vinay Sajip829dc512005-02-18 11:53:32 +000077
Thomas Wouterscf297e42007-02-23 15:07:44 +000078if hasattr(sys, '_getframe'): currentframe = lambda: sys._getframe(3)
Vinay Sajip829dc512005-02-18 11:53:32 +000079# done filching
80
Jeremy Hylton250684d2003-01-23 18:29:29 +000081# _srcfile is only used in conjunction with sys._getframe().
82# To provide compatibility with older versions of Python, set _srcfile
83# to None if _getframe() is not available; this value will prevent
84# findCaller() from being called.
Vinay Sajip829dc512005-02-18 11:53:32 +000085#if not hasattr(sys, "_getframe"):
86# _srcfile = None
Jeremy Hylton250684d2003-01-23 18:29:29 +000087
Guido van Rossum57102f82002-11-13 16:15:58 +000088#
89#_startTime is used as the base when calculating the relative time of events
90#
91_startTime = time.time()
92
93#
94#raiseExceptions is used to see if exceptions during handling should be
95#propagated
96#
97raiseExceptions = 1
98
Vinay Sajipd364a072006-03-13 22:05:28 +000099#
100# If you don't want threading information in the log, set this to zero
101#
102logThreads = 1
103
104#
Jesse Noller9a0fc972009-01-18 21:12:58 +0000105# If you don't want multiprocessing information in the log, set this to zero
106#
107logMultiprocessing = 1
108
109#
Vinay Sajipd364a072006-03-13 22:05:28 +0000110# If you don't want process information in the log, set this to zero
111#
112logProcesses = 1
113
Guido van Rossum57102f82002-11-13 16:15:58 +0000114#---------------------------------------------------------------------------
115# Level related stuff
116#---------------------------------------------------------------------------
117#
118# Default levels and level names, these can be replaced with any positive set
119# of values having corresponding names. There is a pseudo-level, NOTSET, which
120# is only really there as a lower limit for user-defined levels. Handlers and
121# loggers are initialized with NOTSET so that they will log all messages, even
122# at user-defined levels.
123#
Vinay Sajipb89e7c92005-03-13 09:54:31 +0000124
Guido van Rossum57102f82002-11-13 16:15:58 +0000125CRITICAL = 50
126FATAL = CRITICAL
127ERROR = 40
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000128WARNING = 30
129WARN = WARNING
Guido van Rossum57102f82002-11-13 16:15:58 +0000130INFO = 20
131DEBUG = 10
132NOTSET = 0
133
134_levelNames = {
135 CRITICAL : 'CRITICAL',
136 ERROR : 'ERROR',
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000137 WARNING : 'WARNING',
Guido van Rossum57102f82002-11-13 16:15:58 +0000138 INFO : 'INFO',
139 DEBUG : 'DEBUG',
140 NOTSET : 'NOTSET',
141 'CRITICAL' : CRITICAL,
142 'ERROR' : ERROR,
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000143 'WARN' : WARNING,
144 'WARNING' : WARNING,
Guido van Rossum57102f82002-11-13 16:15:58 +0000145 'INFO' : INFO,
146 'DEBUG' : DEBUG,
147 'NOTSET' : NOTSET,
148}
149
150def getLevelName(level):
151 """
152 Return the textual representation of logging level 'level'.
153
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000154 If the level is one of the predefined levels (CRITICAL, ERROR, WARNING,
Guido van Rossum57102f82002-11-13 16:15:58 +0000155 INFO, DEBUG) then you get the corresponding string. If you have
156 associated levels with names using addLevelName then the name you have
Vinay Sajip779e0c92004-07-03 11:47:26 +0000157 associated with 'level' is returned.
158
159 If a numeric value corresponding to one of the defined levels is passed
160 in, the corresponding string representation is returned.
161
162 Otherwise, the string "Level %s" % level is returned.
Guido van Rossum57102f82002-11-13 16:15:58 +0000163 """
164 return _levelNames.get(level, ("Level %s" % level))
165
166def addLevelName(level, levelName):
167 """
168 Associate 'levelName' with 'level'.
169
170 This is used when converting levels to text during message formatting.
171 """
172 _acquireLock()
173 try: #unlikely to cause an exception, but you never know...
174 _levelNames[level] = levelName
175 _levelNames[levelName] = level
176 finally:
177 _releaseLock()
178
Vinay Sajipd4fabf42009-07-13 11:28:25 +0000179def _checkLevel(level):
180 if isinstance(level, int):
181 rv = level
182 elif str(level) == level:
183 if level not in _levelNames:
184 raise ValueError("Unknown level: %r" % level)
185 rv = _levelNames[level]
186 else:
187 raise TypeError("Level not an integer or a valid string: %r" % level)
188 return rv
189
Guido van Rossum57102f82002-11-13 16:15:58 +0000190#---------------------------------------------------------------------------
191# Thread-related stuff
192#---------------------------------------------------------------------------
193
194#
195#_lock is used to serialize access to shared data structures in this module.
Benjamin Peterson55549932009-11-25 17:19:56 +0000196#This needs to be an RLock because fileConfig() creates and configures
197#Handlers, and so might arbitrary user threads. Since Handler code updates the
198#shared dictionary _handlers, it needs to acquire the lock. But if configuring,
Guido van Rossum57102f82002-11-13 16:15:58 +0000199#the lock would already have been acquired - so we need an RLock.
200#The same argument applies to Loggers and Manager.loggerDict.
201#
Vinay Sajip03f6c112009-11-27 14:03:36 +0000202if thread:
203 _lock = threading.RLock()
204else:
205 _lock = None
206
Guido van Rossum57102f82002-11-13 16:15:58 +0000207
208def _acquireLock():
209 """
210 Acquire the module-level lock for serializing access to shared data.
211
212 This should be released with _releaseLock().
213 """
Guido van Rossum57102f82002-11-13 16:15:58 +0000214 if _lock:
215 _lock.acquire()
216
217def _releaseLock():
218 """
219 Release the module-level lock acquired by calling _acquireLock().
220 """
221 if _lock:
222 _lock.release()
223
224#---------------------------------------------------------------------------
225# The logging record
226#---------------------------------------------------------------------------
227
Benjamin Peterson55549932009-11-25 17:19:56 +0000228class LogRecord(object):
Guido van Rossum57102f82002-11-13 16:15:58 +0000229 """
230 A LogRecord instance represents an event being logged.
231
232 LogRecord instances are created every time something is logged. They
233 contain all the information pertinent to the event being logged. The
234 main information passed in is in msg and args, which are combined
235 using str(msg) % args to create the message field of the record. The
236 record also includes information such as when the record was created,
237 the source line where the logging call was made, and any exception
238 information to be logged.
239 """
Vinay Sajiped1992f2006-02-09 08:48:36 +0000240 def __init__(self, name, level, pathname, lineno,
Vinay Sajip61561522010-12-03 11:50:38 +0000241 msg, args, exc_info, func=None, sinfo=None, **kwargs):
Guido van Rossum57102f82002-11-13 16:15:58 +0000242 """
243 Initialize a logging record with interesting information.
244 """
245 ct = time.time()
246 self.name = name
247 self.msg = msg
Vinay Sajip4ed315a2004-10-20 08:39:40 +0000248 #
249 # The following statement allows passing of a dictionary as a sole
250 # argument, so that you can do something like
251 # logging.debug("a %(a)d b %(b)s", {'a':1, 'b':2})
252 # Suggested by Stefan Behnel.
253 # Note that without the test for args[0], we get a problem because
254 # during formatting, we test to see if the arg is present using
255 # 'if self.args:'. If the event being logged is e.g. 'Value is %d'
256 # and if the passed arg fails 'if self.args:' then no formatting
257 # is done. For example, logger.warn('Value is %d', 0) would log
258 # 'Value is %d' instead of 'Value is 0'.
259 # For the use case of passing a dictionary, this should not be a
260 # problem.
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000261 if args and len(args) == 1 and isinstance(args[0], dict) and args[0]:
Vinay Sajip4ed315a2004-10-20 08:39:40 +0000262 args = args[0]
Guido van Rossum57102f82002-11-13 16:15:58 +0000263 self.args = args
264 self.levelname = getLevelName(level)
265 self.levelno = level
266 self.pathname = pathname
267 try:
268 self.filename = os.path.basename(pathname)
269 self.module = os.path.splitext(self.filename)[0]
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000270 except (TypeError, ValueError, AttributeError):
Guido van Rossum57102f82002-11-13 16:15:58 +0000271 self.filename = pathname
272 self.module = "Unknown module"
273 self.exc_info = exc_info
Vinay Sajiped6bb142004-02-20 13:18:36 +0000274 self.exc_text = None # used to cache the traceback text
Vinay Sajip8593ae62010-11-14 21:33:04 +0000275 self.stack_info = sinfo
Guido van Rossum57102f82002-11-13 16:15:58 +0000276 self.lineno = lineno
Vinay Sajiped1992f2006-02-09 08:48:36 +0000277 self.funcName = func
Guido van Rossum57102f82002-11-13 16:15:58 +0000278 self.created = ct
Guido van Rossume2a383d2007-01-15 16:59:06 +0000279 self.msecs = (ct - int(ct)) * 1000
Guido van Rossum57102f82002-11-13 16:15:58 +0000280 self.relativeCreated = (self.created - _startTime) * 1000
Vinay Sajipd364a072006-03-13 22:05:28 +0000281 if logThreads and thread:
Guido van Rossum57102f82002-11-13 16:15:58 +0000282 self.thread = thread.get_ident()
Benjamin Peterson72753702008-08-18 18:09:21 +0000283 self.threadName = threading.current_thread().name
Guido van Rossum57102f82002-11-13 16:15:58 +0000284 else:
285 self.thread = None
Vinay Sajip4a704862005-03-31 20:16:55 +0000286 self.threadName = None
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000287 if not logMultiprocessing:
Jesse Noller9a0fc972009-01-18 21:12:58 +0000288 self.processName = None
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000289 else:
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000290 self.processName = 'MainProcess'
291 mp = sys.modules.get('multiprocessing')
292 if mp is not None:
293 # Errors may occur if multiprocessing has not finished loading
294 # yet - e.g. if a custom import hook causes third-party code
295 # to run when multiprocessing calls import. See issue 8200
296 # for an example
297 try:
298 self.processName = mp.current_process().name
299 except StandardError:
300 pass
Vinay Sajipd364a072006-03-13 22:05:28 +0000301 if logProcesses and hasattr(os, 'getpid'):
Jack Jansen4c641d02003-02-21 22:29:45 +0000302 self.process = os.getpid()
303 else:
304 self.process = None
Guido van Rossum57102f82002-11-13 16:15:58 +0000305
306 def __str__(self):
307 return '<LogRecord: %s, %s, %s, %s, "%s">'%(self.name, self.levelno,
308 self.pathname, self.lineno, self.msg)
309
310 def getMessage(self):
311 """
312 Return the message for this LogRecord.
313
314 Return the message for this LogRecord after merging any user-supplied
315 arguments with the message.
316 """
Vinay Sajipdc5097f2010-08-31 07:52:17 +0000317 msg = str(self.msg)
Guido van Rossum57102f82002-11-13 16:15:58 +0000318 if self.args:
319 msg = msg % self.args
320 return msg
321
Vinay Sajip062d56b2010-10-19 15:26:24 +0000322#
323# Determine which class to use when instantiating log records.
324#
Vinay Sajip61561522010-12-03 11:50:38 +0000325_logRecordFactory = LogRecord
Vinay Sajip062d56b2010-10-19 15:26:24 +0000326
Vinay Sajip61561522010-12-03 11:50:38 +0000327def setLogRecordFactory(factory):
Vinay Sajip062d56b2010-10-19 15:26:24 +0000328 """
Vinay Sajipfad058f2010-12-03 13:01:11 +0000329 Set the factory to be used when instantiating a log record.
Vinay Sajip062d56b2010-10-19 15:26:24 +0000330
Vinay Sajip61561522010-12-03 11:50:38 +0000331 :param factory: A callable which will be called to instantiate
332 a log record.
333 """
334 global _logRecordFactory
335 _logRecordFactory = factory
336
337def getLogRecordFactory():
Vinay Sajip062d56b2010-10-19 15:26:24 +0000338 """
Vinay Sajipfad058f2010-12-03 13:01:11 +0000339 Return the factory to be used when instantiating a log record.
Vinay Sajip062d56b2010-10-19 15:26:24 +0000340 """
341
Vinay Sajip61561522010-12-03 11:50:38 +0000342 return _logRecordFactory
Vinay Sajip062d56b2010-10-19 15:26:24 +0000343
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000344def makeLogRecord(dict):
345 """
346 Make a LogRecord whose attributes are defined by the specified dictionary,
347 This function is useful for converting a logging event received over
348 a socket connection (which is sent as a dictionary) into a LogRecord
349 instance.
350 """
Vinay Sajip61561522010-12-03 11:50:38 +0000351 rv = _logRecordFactory(None, None, "", 0, "", (), None, None)
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000352 rv.__dict__.update(dict)
353 return rv
354
Guido van Rossum57102f82002-11-13 16:15:58 +0000355#---------------------------------------------------------------------------
356# Formatter classes and functions
357#---------------------------------------------------------------------------
358
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000359class PercentStyle(object):
360
361 default_format = '%(message)s'
362 asctime_format = '%(asctime)s'
363
364 def __init__(self, fmt):
365 self._fmt = fmt or self.default_format
366
367 def usesTime(self):
368 return self._fmt.find(self.asctime_format) >= 0
369
370 def format(self, record):
371 return self._fmt % record.__dict__
372
373class StrFormatStyle(PercentStyle):
374 default_format = '{message}'
375 asctime_format = '{asctime}'
376
377 def format(self, record):
378 return self._fmt.format(**record.__dict__)
379
380
381class StringTemplateStyle(PercentStyle):
382 default_format = '${message}'
383 asctime_format = '${asctime}'
384
385 def __init__(self, fmt):
386 self._fmt = fmt or self.default_format
387 self._tpl = Template(self._fmt)
388
389 def usesTime(self):
390 fmt = self._fmt
391 return fmt.find('$asctime') >= 0 or fmt.find(self.asctime_format) >= 0
392
393 def format(self, record):
394 return self._tpl.substitute(**record.__dict__)
395
396_STYLES = {
397 '%': PercentStyle,
398 '{': StrFormatStyle,
399 '$': StringTemplateStyle
400}
401
Benjamin Peterson55549932009-11-25 17:19:56 +0000402class Formatter(object):
Guido van Rossum57102f82002-11-13 16:15:58 +0000403 """
404 Formatter instances are used to convert a LogRecord to text.
405
406 Formatters need to know how a LogRecord is constructed. They are
407 responsible for converting a LogRecord to (usually) a string which can
408 be interpreted by either a human or an external system. The base Formatter
409 allows a formatting string to be specified. If none is supplied, the
Vinay Sajip2a20dfc2010-10-20 20:05:38 +0000410 default value of "%s(message)" is used.
Guido van Rossum57102f82002-11-13 16:15:58 +0000411
412 The Formatter can be initialized with a format string which makes use of
413 knowledge of the LogRecord attributes - e.g. the default value mentioned
414 above makes use of the fact that the user's message and arguments are pre-
415 formatted into a LogRecord's message attribute. Currently, the useful
416 attributes in a LogRecord are described by:
417
418 %(name)s Name of the logger (logging channel)
419 %(levelno)s Numeric logging level for the message (DEBUG, INFO,
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000420 WARNING, ERROR, CRITICAL)
Guido van Rossum57102f82002-11-13 16:15:58 +0000421 %(levelname)s Text logging level for the message ("DEBUG", "INFO",
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000422 "WARNING", "ERROR", "CRITICAL")
Guido van Rossum57102f82002-11-13 16:15:58 +0000423 %(pathname)s Full pathname of the source file where the logging
424 call was issued (if available)
425 %(filename)s Filename portion of pathname
426 %(module)s Module (name portion of filename)
427 %(lineno)d Source line number where the logging call was issued
428 (if available)
Vinay Sajiped1992f2006-02-09 08:48:36 +0000429 %(funcName)s Function name
Guido van Rossum57102f82002-11-13 16:15:58 +0000430 %(created)f Time when the LogRecord was created (time.time()
431 return value)
432 %(asctime)s Textual time when the LogRecord was created
433 %(msecs)d Millisecond portion of the creation time
434 %(relativeCreated)d Time in milliseconds when the LogRecord was created,
435 relative to the time the logging module was loaded
436 (typically at application startup time)
437 %(thread)d Thread ID (if available)
Vinay Sajip4a704862005-03-31 20:16:55 +0000438 %(threadName)s Thread name (if available)
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000439 %(process)d Process ID (if available)
Guido van Rossum57102f82002-11-13 16:15:58 +0000440 %(message)s The result of record.getMessage(), computed just as
441 the record is emitted
442 """
443
444 converter = time.localtime
445
Vinay Sajipa39c5712010-10-25 13:57:39 +0000446 def __init__(self, fmt=None, datefmt=None, style='%'):
Guido van Rossum57102f82002-11-13 16:15:58 +0000447 """
448 Initialize the formatter with specified format strings.
449
450 Initialize the formatter either with the specified format string, or a
451 default as described above. Allow for specialized date formatting with
452 the optional datefmt argument (if omitted, you get the ISO8601 format).
Vinay Sajipa39c5712010-10-25 13:57:39 +0000453
454 Use a style parameter of '%', '{' or '$' to specify that you want to
455 use one of %-formatting, :meth:`str.format` (``{}``) formatting or
456 :class:`string.Template` formatting in your format string.
457
458 .. versionchanged: 3.2
459 Added the ``style`` parameter.
Guido van Rossum57102f82002-11-13 16:15:58 +0000460 """
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000461 if style not in _STYLES:
462 raise ValueError('Style must be one of: %s' % ','.join(
463 _STYLES.keys()))
464 self._style = _STYLES[style](fmt)
465 self._fmt = self._style._fmt
Guido van Rossum57102f82002-11-13 16:15:58 +0000466 self.datefmt = datefmt
467
468 def formatTime(self, record, datefmt=None):
469 """
470 Return the creation time of the specified LogRecord as formatted text.
471
472 This method should be called from format() by a formatter which
473 wants to make use of a formatted time. This method can be overridden
474 in formatters to provide for any specific requirement, but the
475 basic behaviour is as follows: if datefmt (a string) is specified,
476 it is used with time.strftime() to format the creation time of the
477 record. Otherwise, the ISO8601 format is used. The resulting
478 string is returned. This function uses a user-configurable function
479 to convert the creation time to a tuple. By default, time.localtime()
480 is used; to change this for a particular formatter instance, set the
481 'converter' attribute to a function with the same signature as
482 time.localtime() or time.gmtime(). To change it for all formatters,
483 for example if you want all logging times to be shown in GMT,
484 set the 'converter' attribute in the Formatter class.
485 """
486 ct = self.converter(record.created)
487 if datefmt:
488 s = time.strftime(datefmt, ct)
489 else:
490 t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
Vinay Sajipa39c5712010-10-25 13:57:39 +0000491 s = "%s,%03d" % (t, record.msecs) # the use of % here is internal
Guido van Rossum57102f82002-11-13 16:15:58 +0000492 return s
493
494 def formatException(self, ei):
495 """
496 Format and return the specified exception information as a string.
497
498 This default implementation just uses
499 traceback.print_exception()
500 """
Guido van Rossum34d19282007-08-09 01:03:29 +0000501 sio = io.StringIO()
Vinay Sajip40d9a4e2010-08-30 18:10:03 +0000502 tb = ei[2]
503 # See issues #9427, #1553375. Commented out for now.
504 #if getattr(self, 'fullstack', False):
505 # traceback.print_stack(tb.tb_frame.f_back, file=sio)
506 traceback.print_exception(ei[0], ei[1], tb, None, sio)
Guido van Rossum57102f82002-11-13 16:15:58 +0000507 s = sio.getvalue()
508 sio.close()
Guido van Rossum486364b2007-06-30 05:01:58 +0000509 if s[-1:] == "\n":
Guido van Rossum57102f82002-11-13 16:15:58 +0000510 s = s[:-1]
511 return s
512
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000513 def usesTime(self):
514 """
515 Check if the format uses the creation time of the record.
516 """
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000517 return self._style.usesTime()
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000518
Vinay Sajipd0557bf2010-10-25 15:25:24 +0000519 def formatMessage(self, record):
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000520 return self._style.format(record)
Vinay Sajipd0557bf2010-10-25 15:25:24 +0000521
Vinay Sajip8593ae62010-11-14 21:33:04 +0000522 def formatStack(self, stack_info):
523 """
524 This method is provided as an extension point for specialized
525 formatting of stack information.
526
527 The input data is a string as returned from a call to
528 :func:`traceback.print_stack`, but with the last trailing newline
529 removed.
530
531 The base implementation just returns the value passed in.
532 """
533 return stack_info
534
Guido van Rossum57102f82002-11-13 16:15:58 +0000535 def format(self, record):
536 """
537 Format the specified record as text.
538
539 The record's attribute dictionary is used as the operand to a
540 string formatting operation which yields the returned string.
541 Before formatting the dictionary, a couple of preparatory steps
542 are carried out. The message attribute of the record is computed
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000543 using LogRecord.getMessage(). If the formatting string uses the
544 time (as determined by a call to usesTime(), formatTime() is
545 called to format the event time. If there is exception information,
546 it is formatted using formatException() and appended to the message.
Guido van Rossum57102f82002-11-13 16:15:58 +0000547 """
548 record.message = record.getMessage()
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000549 if self.usesTime():
Guido van Rossum57102f82002-11-13 16:15:58 +0000550 record.asctime = self.formatTime(record, self.datefmt)
Vinay Sajipd0557bf2010-10-25 15:25:24 +0000551 s = self.formatMessage(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000552 if record.exc_info:
Vinay Sajiped6bb142004-02-20 13:18:36 +0000553 # Cache the traceback text to avoid converting it multiple times
554 # (it's constant anyway)
555 if not record.exc_text:
556 record.exc_text = self.formatException(record.exc_info)
557 if record.exc_text:
Guido van Rossum486364b2007-06-30 05:01:58 +0000558 if s[-1:] != "\n":
Guido van Rossum57102f82002-11-13 16:15:58 +0000559 s = s + "\n"
Vinay Sajiped6bb142004-02-20 13:18:36 +0000560 s = s + record.exc_text
Vinay Sajip8593ae62010-11-14 21:33:04 +0000561 if record.stack_info:
562 if s[-1:] != "\n":
563 s = s + "\n"
564 s = s + self.formatStack(record.stack_info)
Guido van Rossum57102f82002-11-13 16:15:58 +0000565 return s
566
567#
568# The default formatter to use when no other is specified
569#
570_defaultFormatter = Formatter()
571
Benjamin Peterson55549932009-11-25 17:19:56 +0000572class BufferingFormatter(object):
Guido van Rossum57102f82002-11-13 16:15:58 +0000573 """
574 A formatter suitable for formatting a number of records.
575 """
576 def __init__(self, linefmt=None):
577 """
578 Optionally specify a formatter which will be used to format each
579 individual record.
580 """
581 if linefmt:
582 self.linefmt = linefmt
583 else:
584 self.linefmt = _defaultFormatter
585
586 def formatHeader(self, records):
587 """
588 Return the header string for the specified records.
589 """
590 return ""
591
592 def formatFooter(self, records):
593 """
594 Return the footer string for the specified records.
595 """
596 return ""
597
598 def format(self, records):
599 """
600 Format the specified records and return the result as a string.
601 """
602 rv = ""
603 if len(records) > 0:
604 rv = rv + self.formatHeader(records)
605 for record in records:
606 rv = rv + self.linefmt.format(record)
607 rv = rv + self.formatFooter(records)
608 return rv
609
610#---------------------------------------------------------------------------
611# Filter classes and functions
612#---------------------------------------------------------------------------
613
Benjamin Peterson55549932009-11-25 17:19:56 +0000614class Filter(object):
Guido van Rossum57102f82002-11-13 16:15:58 +0000615 """
616 Filter instances are used to perform arbitrary filtering of LogRecords.
617
618 Loggers and Handlers can optionally use Filter instances to filter
619 records as desired. The base filter class only allows events which are
620 below a certain point in the logger hierarchy. For example, a filter
621 initialized with "A.B" will allow events logged by loggers "A.B",
622 "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
623 initialized with the empty string, all events are passed.
624 """
625 def __init__(self, name=''):
626 """
627 Initialize a filter.
628
629 Initialize with the name of the logger which, together with its
630 children, will have its events allowed through the filter. If no
631 name is specified, allow every event.
632 """
633 self.name = name
634 self.nlen = len(name)
635
636 def filter(self, record):
637 """
638 Determine if the specified record is to be logged.
639
640 Is the specified record to be logged? Returns 0 for no, nonzero for
641 yes. If deemed appropriate, the record may be modified in-place.
642 """
643 if self.nlen == 0:
644 return 1
645 elif self.name == record.name:
646 return 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000647 elif record.name.find(self.name, 0, self.nlen) != 0:
Guido van Rossum57102f82002-11-13 16:15:58 +0000648 return 0
649 return (record.name[self.nlen] == ".")
650
Benjamin Peterson55549932009-11-25 17:19:56 +0000651class Filterer(object):
Guido van Rossum57102f82002-11-13 16:15:58 +0000652 """
653 A base class for loggers and handlers which allows them to share
654 common code.
655 """
656 def __init__(self):
657 """
658 Initialize the list of filters to be an empty list.
659 """
660 self.filters = []
661
662 def addFilter(self, filter):
663 """
664 Add the specified filter to this handler.
665 """
666 if not (filter in self.filters):
667 self.filters.append(filter)
668
669 def removeFilter(self, filter):
670 """
671 Remove the specified filter from this handler.
672 """
673 if filter in self.filters:
674 self.filters.remove(filter)
675
676 def filter(self, record):
677 """
678 Determine if a record is loggable by consulting all the filters.
679
680 The default is to allow the record to be logged; any filter can veto
681 this and the record is then dropped. Returns a zero value if a record
682 is to be dropped, else non-zero.
Vinay Sajip6dbed2e2010-10-19 20:53:01 +0000683
684 .. versionchanged: 3.2
685
686 Allow filters to be just callables.
Guido van Rossum57102f82002-11-13 16:15:58 +0000687 """
688 rv = 1
689 for f in self.filters:
Vinay Sajip6dbed2e2010-10-19 20:53:01 +0000690 if hasattr(f, 'filter'):
691 result = f.filter(record)
Vinay Sajip6dbed2e2010-10-19 20:53:01 +0000692 else:
Vinay Sajipfc082ca2010-10-19 21:13:49 +0000693 result = f(record) # assume callable - will raise if not
Vinay Sajip6dbed2e2010-10-19 20:53:01 +0000694 if not result:
Guido van Rossum57102f82002-11-13 16:15:58 +0000695 rv = 0
696 break
697 return rv
698
699#---------------------------------------------------------------------------
700# Handler classes and functions
701#---------------------------------------------------------------------------
702
Benjamin Peterson55549932009-11-25 17:19:56 +0000703_handlers = weakref.WeakValueDictionary() #map of handler names to handlers
Vinay Sajip0ee9ba22005-09-08 18:14:16 +0000704_handlerList = [] # added to allow handlers to be removed in reverse of order initialized
Guido van Rossum57102f82002-11-13 16:15:58 +0000705
Benjamin Peterson55549932009-11-25 17:19:56 +0000706def _removeHandlerRef(wr):
707 """
708 Remove a handler reference from the internal cleanup list.
709 """
Vinay Sajipde6e9d62010-08-23 17:50:30 +0000710 # This function can be called during module teardown, when globals are
711 # set to None. If _acquireLock is None, assume this is the case and do
712 # nothing.
713 if _acquireLock is not None:
714 _acquireLock()
715 try:
716 if wr in _handlerList:
717 _handlerList.remove(wr)
718 finally:
719 _releaseLock()
Benjamin Peterson55549932009-11-25 17:19:56 +0000720
721def _addHandlerRef(handler):
722 """
723 Add a handler to the internal cleanup list using a weak reference.
724 """
725 _acquireLock()
726 try:
727 _handlerList.append(weakref.ref(handler, _removeHandlerRef))
728 finally:
729 _releaseLock()
730
Guido van Rossum57102f82002-11-13 16:15:58 +0000731class Handler(Filterer):
732 """
733 Handler instances dispatch logging events to specific destinations.
734
735 The base handler class. Acts as a placeholder which defines the Handler
736 interface. Handlers can optionally use Formatter instances to format
737 records as desired. By default, no formatter is specified; in this case,
738 the 'raw' message as determined by record.message is logged.
739 """
740 def __init__(self, level=NOTSET):
741 """
742 Initializes the instance - basically setting the formatter to None
743 and the filter list to empty.
744 """
745 Filterer.__init__(self)
Benjamin Peterson55549932009-11-25 17:19:56 +0000746 self._name = None
Vinay Sajipd4fabf42009-07-13 11:28:25 +0000747 self.level = _checkLevel(level)
Guido van Rossum57102f82002-11-13 16:15:58 +0000748 self.formatter = None
Benjamin Peterson55549932009-11-25 17:19:56 +0000749 # Add the handler to the global _handlerList (for cleanup on shutdown)
750 _addHandlerRef(self)
751 self.createLock()
752
753 def get_name(self):
754 return self._name
755
756 def set_name(self, name):
Guido van Rossum57102f82002-11-13 16:15:58 +0000757 _acquireLock()
Benjamin Peterson55549932009-11-25 17:19:56 +0000758 try:
759 if self._name in _handlers:
760 del _handlers[self._name]
761 self._name = name
762 if name:
763 _handlers[name] = self
Guido van Rossum57102f82002-11-13 16:15:58 +0000764 finally:
765 _releaseLock()
Benjamin Peterson55549932009-11-25 17:19:56 +0000766
767 name = property(get_name, set_name)
Guido van Rossum57102f82002-11-13 16:15:58 +0000768
769 def createLock(self):
770 """
771 Acquire a thread lock for serializing access to the underlying I/O.
772 """
773 if thread:
Vinay Sajip4a704862005-03-31 20:16:55 +0000774 self.lock = threading.RLock()
Guido van Rossum57102f82002-11-13 16:15:58 +0000775 else:
776 self.lock = None
777
778 def acquire(self):
779 """
780 Acquire the I/O thread lock.
781 """
782 if self.lock:
783 self.lock.acquire()
784
785 def release(self):
786 """
787 Release the I/O thread lock.
788 """
789 if self.lock:
790 self.lock.release()
791
792 def setLevel(self, level):
793 """
794 Set the logging level of this handler.
795 """
Vinay Sajipd4fabf42009-07-13 11:28:25 +0000796 self.level = _checkLevel(level)
Guido van Rossum57102f82002-11-13 16:15:58 +0000797
798 def format(self, record):
799 """
800 Format the specified record.
801
802 If a formatter is set, use it. Otherwise, use the default formatter
803 for the module.
804 """
805 if self.formatter:
806 fmt = self.formatter
807 else:
808 fmt = _defaultFormatter
809 return fmt.format(record)
810
811 def emit(self, record):
812 """
813 Do whatever it takes to actually log the specified logging record.
814
815 This version is intended to be implemented by subclasses and so
816 raises a NotImplementedError.
817 """
Collin Winterce36ad82007-08-30 01:19:48 +0000818 raise NotImplementedError('emit must be implemented '
819 'by Handler subclasses')
Guido van Rossum57102f82002-11-13 16:15:58 +0000820
821 def handle(self, record):
822 """
823 Conditionally emit the specified logging record.
824
825 Emission depends on filters which may have been added to the handler.
826 Wrap the actual emission of the record with acquisition/release of
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000827 the I/O thread lock. Returns whether the filter passed the record for
828 emission.
Guido van Rossum57102f82002-11-13 16:15:58 +0000829 """
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000830 rv = self.filter(record)
831 if rv:
Guido van Rossum57102f82002-11-13 16:15:58 +0000832 self.acquire()
833 try:
834 self.emit(record)
835 finally:
836 self.release()
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000837 return rv
Guido van Rossum57102f82002-11-13 16:15:58 +0000838
839 def setFormatter(self, fmt):
840 """
841 Set the formatter for this handler.
842 """
843 self.formatter = fmt
844
845 def flush(self):
846 """
847 Ensure all logging output has been flushed.
848
849 This version does nothing and is intended to be implemented by
850 subclasses.
851 """
852 pass
853
854 def close(self):
855 """
856 Tidy up any resources used by the handler.
857
Benjamin Peterson55549932009-11-25 17:19:56 +0000858 This version removes the handler from an internal map of handlers,
859 _handlers, which is used for handler lookup by name. Subclasses
Vinay Sajiped6bb142004-02-20 13:18:36 +0000860 should ensure that this gets called from overridden close()
861 methods.
Guido van Rossum57102f82002-11-13 16:15:58 +0000862 """
Vinay Sajiped6bb142004-02-20 13:18:36 +0000863 #get the module data lock, as we're updating a shared structure.
864 _acquireLock()
865 try: #unlikely to raise an exception, but you never know...
Benjamin Peterson55549932009-11-25 17:19:56 +0000866 if self._name and self._name in _handlers:
867 del _handlers[self._name]
Vinay Sajiped6bb142004-02-20 13:18:36 +0000868 finally:
869 _releaseLock()
Guido van Rossum57102f82002-11-13 16:15:58 +0000870
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000871 def handleError(self, record):
Guido van Rossum57102f82002-11-13 16:15:58 +0000872 """
873 Handle errors which occur during an emit() call.
874
875 This method should be called from handlers when an exception is
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000876 encountered during an emit() call. If raiseExceptions is false,
Guido van Rossum57102f82002-11-13 16:15:58 +0000877 exceptions get silently ignored. This is what is mostly wanted
878 for a logging system - most users will not care about errors in
879 the logging system, they are more interested in application errors.
880 You could, however, replace this with a custom handler if you wish.
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000881 The record which was being processed is passed in to this method.
Guido van Rossum57102f82002-11-13 16:15:58 +0000882 """
883 if raiseExceptions:
Guido van Rossum57102f82002-11-13 16:15:58 +0000884 ei = sys.exc_info()
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000885 try:
Vinay Sajipdb81c4c2010-02-25 23:13:06 +0000886 traceback.print_exception(ei[0], ei[1], ei[2],
887 None, sys.stderr)
888 sys.stderr.write('Logged from file %s, line %s\n' % (
889 record.filename, record.lineno))
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000890 except IOError:
891 pass # see issue 5971
892 finally:
893 del ei
Guido van Rossum57102f82002-11-13 16:15:58 +0000894
895class StreamHandler(Handler):
896 """
897 A handler class which writes logging records, appropriately formatted,
898 to a stream. Note that this class does not close the stream, as
899 sys.stdout or sys.stderr may be used.
900 """
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000901
Vinay Sajip2a20dfc2010-10-20 20:05:38 +0000902 terminator = '\n'
903
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000904 def __init__(self, stream=None):
Guido van Rossum57102f82002-11-13 16:15:58 +0000905 """
906 Initialize the handler.
907
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000908 If stream is not specified, sys.stderr is used.
Guido van Rossum57102f82002-11-13 16:15:58 +0000909 """
910 Handler.__init__(self)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000911 if stream is None:
912 stream = sys.stderr
913 self.stream = stream
Guido van Rossum57102f82002-11-13 16:15:58 +0000914
915 def flush(self):
916 """
917 Flushes the stream.
918 """
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000919 if self.stream and hasattr(self.stream, "flush"):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000920 self.stream.flush()
Guido van Rossum57102f82002-11-13 16:15:58 +0000921
922 def emit(self, record):
923 """
924 Emit a record.
925
926 If a formatter is specified, it is used to format the record.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000927 The record is then written to the stream with a trailing newline. If
928 exception information is present, it is formatted using
929 traceback.print_exception and appended to the stream. If the stream
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000930 has an 'encoding' attribute, it is used to determine how to do the
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000931 output to the stream.
Guido van Rossum57102f82002-11-13 16:15:58 +0000932 """
933 try:
934 msg = self.format(record)
Benjamin Petersonf91df042009-02-13 02:50:59 +0000935 stream = self.stream
Vinay Sajip2a20dfc2010-10-20 20:05:38 +0000936 stream.write(msg)
937 stream.write(self.terminator)
Guido van Rossum57102f82002-11-13 16:15:58 +0000938 self.flush()
Vinay Sajip85c19092005-10-31 13:14:19 +0000939 except (KeyboardInterrupt, SystemExit):
940 raise
Guido van Rossum57102f82002-11-13 16:15:58 +0000941 except:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000942 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000943
944class FileHandler(StreamHandler):
945 """
946 A handler class which writes formatted logging records to disk files.
947 """
Christian Heimese7a15bb2008-01-24 16:21:45 +0000948 def __init__(self, filename, mode='a', encoding=None, delay=0):
Guido van Rossum57102f82002-11-13 16:15:58 +0000949 """
950 Open the specified file and use it as the stream for logging.
951 """
Vinay Sajip4bbab2b2004-07-08 10:22:35 +0000952 #keep the absolute path, otherwise derived classes which use this
953 #may come a cropper when the current directory changes
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000954 if codecs is None:
955 encoding = None
Vinay Sajip4bbab2b2004-07-08 10:22:35 +0000956 self.baseFilename = os.path.abspath(filename)
Guido van Rossum57102f82002-11-13 16:15:58 +0000957 self.mode = mode
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000958 self.encoding = encoding
Christian Heimese7a15bb2008-01-24 16:21:45 +0000959 if delay:
Vinay Sajip6268cbc2009-01-21 00:19:28 +0000960 #We don't open the stream, but we still need to call the
961 #Handler constructor to set level, formatter, lock etc.
962 Handler.__init__(self)
Christian Heimese7a15bb2008-01-24 16:21:45 +0000963 self.stream = None
964 else:
Vinay Sajip6268cbc2009-01-21 00:19:28 +0000965 StreamHandler.__init__(self, self._open())
Guido van Rossum57102f82002-11-13 16:15:58 +0000966
967 def close(self):
968 """
969 Closes the stream.
970 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000971 if self.stream:
972 self.flush()
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000973 if hasattr(self.stream, "close"):
974 self.stream.close()
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000975 StreamHandler.close(self)
976 self.stream = None
Guido van Rossum57102f82002-11-13 16:15:58 +0000977
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000978 def _open(self):
979 """
980 Open the current base file with the (original) mode and encoding.
981 Return the resulting stream.
982 """
983 if self.encoding is None:
984 stream = open(self.baseFilename, self.mode)
985 else:
986 stream = codecs.open(self.baseFilename, self.mode, self.encoding)
987 return stream
988
Christian Heimese7a15bb2008-01-24 16:21:45 +0000989 def emit(self, record):
990 """
991 Emit a record.
992
993 If the stream was not opened because 'delay' was specified in the
994 constructor, open it before calling the superclass's emit.
995 """
996 if self.stream is None:
Vinay Sajip6268cbc2009-01-21 00:19:28 +0000997 self.stream = self._open()
Christian Heimese7a15bb2008-01-24 16:21:45 +0000998 StreamHandler.emit(self, record)
999
Vinay Sajip5a27d402010-12-10 11:42:57 +00001000class _StderrHandler(StreamHandler):
1001 """
1002 This class is like a StreamHandler using sys.stderr, but always uses
1003 whatever sys.stderr is currently set to rather than the value of
1004 sys.stderr at handler construction time.
1005 """
1006 def __init__(self, level=NOTSET):
1007 """
1008 Initialize the handler.
1009 """
1010 Handler.__init__(self, level)
1011
1012 @property
1013 def stream(self):
1014 return sys.stderr
1015
1016
1017_defaultLastResort = _StderrHandler(WARNING)
1018lastResort = _defaultLastResort
1019
Guido van Rossum57102f82002-11-13 16:15:58 +00001020#---------------------------------------------------------------------------
1021# Manager classes and functions
1022#---------------------------------------------------------------------------
1023
Benjamin Peterson55549932009-11-25 17:19:56 +00001024class PlaceHolder(object):
Guido van Rossum57102f82002-11-13 16:15:58 +00001025 """
1026 PlaceHolder instances are used in the Manager logger hierarchy to take
Vinay Sajip3f742842004-02-28 16:07:46 +00001027 the place of nodes for which no loggers have been defined. This class is
1028 intended for internal use only and not as part of the public API.
Guido van Rossum57102f82002-11-13 16:15:58 +00001029 """
1030 def __init__(self, alogger):
1031 """
1032 Initialize with the specified logger being a child of this placeholder.
1033 """
Vinay Sajip239322b2005-10-14 09:36:35 +00001034 self.loggerMap = { alogger : None }
Guido van Rossum57102f82002-11-13 16:15:58 +00001035
1036 def append(self, alogger):
1037 """
1038 Add the specified logger as a child of this placeholder.
1039 """
Guido van Rossum93662412006-08-19 16:09:41 +00001040 if alogger not in self.loggerMap:
Vinay Sajip239322b2005-10-14 09:36:35 +00001041 self.loggerMap[alogger] = None
Guido van Rossum57102f82002-11-13 16:15:58 +00001042
1043#
1044# Determine which class to use when instantiating loggers.
1045#
1046_loggerClass = None
1047
1048def setLoggerClass(klass):
1049 """
1050 Set the class to be used when instantiating a logger. The class should
1051 define __init__() such that only a name argument is required, and the
1052 __init__() should call Logger.__init__()
1053 """
1054 if klass != Logger:
Guido van Rossum57102f82002-11-13 16:15:58 +00001055 if not issubclass(klass, Logger):
Collin Winterce36ad82007-08-30 01:19:48 +00001056 raise TypeError("logger not derived from logging.Logger: "
1057 + klass.__name__)
Guido van Rossum57102f82002-11-13 16:15:58 +00001058 global _loggerClass
1059 _loggerClass = klass
1060
Vinay Sajipb9591172004-09-22 12:39:26 +00001061def getLoggerClass():
1062 """
1063 Return the class to be used when instantiating a logger.
1064 """
1065
1066 return _loggerClass
1067
Benjamin Peterson55549932009-11-25 17:19:56 +00001068class Manager(object):
Guido van Rossum57102f82002-11-13 16:15:58 +00001069 """
1070 There is [under normal circumstances] just one Manager instance, which
1071 holds the hierarchy of loggers.
1072 """
Neal Norwitzd1cade02002-11-15 23:31:28 +00001073 def __init__(self, rootnode):
Guido van Rossum57102f82002-11-13 16:15:58 +00001074 """
1075 Initialize the manager with the root node of the logger hierarchy.
1076 """
Neal Norwitzd1cade02002-11-15 23:31:28 +00001077 self.root = rootnode
Guido van Rossum57102f82002-11-13 16:15:58 +00001078 self.disable = 0
Vinay Sajip5a27d402010-12-10 11:42:57 +00001079 self.emittedNoHandlerWarning = False
Guido van Rossum57102f82002-11-13 16:15:58 +00001080 self.loggerDict = {}
Vinay Sajipdb81c4c2010-02-25 23:13:06 +00001081 self.loggerClass = None
Vinay Sajip61561522010-12-03 11:50:38 +00001082 self.logRecordFactory = None
Guido van Rossum57102f82002-11-13 16:15:58 +00001083
1084 def getLogger(self, name):
1085 """
1086 Get a logger with the specified name (channel name), creating it
Vinay Sajipb9591172004-09-22 12:39:26 +00001087 if it doesn't yet exist. This name is a dot-separated hierarchical
1088 name, such as "a", "a.b", "a.b.c" or similar.
Guido van Rossum57102f82002-11-13 16:15:58 +00001089
1090 If a PlaceHolder existed for the specified name [i.e. the logger
1091 didn't exist but a child of it did], replace it with the created
1092 logger and fix up the parent/child references which pointed to the
1093 placeholder to now point to the logger.
1094 """
1095 rv = None
1096 _acquireLock()
1097 try:
Guido van Rossum93662412006-08-19 16:09:41 +00001098 if name in self.loggerDict:
Guido van Rossum57102f82002-11-13 16:15:58 +00001099 rv = self.loggerDict[name]
1100 if isinstance(rv, PlaceHolder):
1101 ph = rv
Vinay Sajipdb81c4c2010-02-25 23:13:06 +00001102 rv = (self.loggerClass or _loggerClass)(name)
Guido van Rossum57102f82002-11-13 16:15:58 +00001103 rv.manager = self
1104 self.loggerDict[name] = rv
1105 self._fixupChildren(ph, rv)
1106 self._fixupParents(rv)
1107 else:
Vinay Sajipdb81c4c2010-02-25 23:13:06 +00001108 rv = (self.loggerClass or _loggerClass)(name)
Guido van Rossum57102f82002-11-13 16:15:58 +00001109 rv.manager = self
1110 self.loggerDict[name] = rv
1111 self._fixupParents(rv)
1112 finally:
1113 _releaseLock()
1114 return rv
1115
Vinay Sajipdb81c4c2010-02-25 23:13:06 +00001116 def setLoggerClass(self, klass):
1117 """
1118 Set the class to be used when instantiating a logger with this Manager.
1119 """
1120 if klass != Logger:
1121 if not issubclass(klass, Logger):
1122 raise TypeError("logger not derived from logging.Logger: "
1123 + klass.__name__)
1124 self.loggerClass = klass
1125
Vinay Sajip61561522010-12-03 11:50:38 +00001126 def setLogRecordFactory(self, factory):
Vinay Sajip6fac8172010-10-19 20:44:14 +00001127 """
Vinay Sajipfad058f2010-12-03 13:01:11 +00001128 Set the factory to be used when instantiating a log record with this
Vinay Sajip6fac8172010-10-19 20:44:14 +00001129 Manager.
1130 """
Vinay Sajip61561522010-12-03 11:50:38 +00001131 self.logRecordFactory = factory
Vinay Sajip6fac8172010-10-19 20:44:14 +00001132
Guido van Rossum57102f82002-11-13 16:15:58 +00001133 def _fixupParents(self, alogger):
1134 """
1135 Ensure that there are either loggers or placeholders all the way
1136 from the specified logger to the root of the logger hierarchy.
1137 """
1138 name = alogger.name
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001139 i = name.rfind(".")
Guido van Rossum57102f82002-11-13 16:15:58 +00001140 rv = None
1141 while (i > 0) and not rv:
1142 substr = name[:i]
Guido van Rossum93662412006-08-19 16:09:41 +00001143 if substr not in self.loggerDict:
Guido van Rossum57102f82002-11-13 16:15:58 +00001144 self.loggerDict[substr] = PlaceHolder(alogger)
1145 else:
1146 obj = self.loggerDict[substr]
1147 if isinstance(obj, Logger):
1148 rv = obj
1149 else:
1150 assert isinstance(obj, PlaceHolder)
1151 obj.append(alogger)
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001152 i = name.rfind(".", 0, i - 1)
Guido van Rossum57102f82002-11-13 16:15:58 +00001153 if not rv:
1154 rv = self.root
1155 alogger.parent = rv
1156
1157 def _fixupChildren(self, ph, alogger):
1158 """
1159 Ensure that children of the placeholder ph are connected to the
1160 specified logger.
1161 """
Thomas Wouters89f507f2006-12-13 04:49:30 +00001162 name = alogger.name
1163 namelen = len(name)
Vinay Sajip239322b2005-10-14 09:36:35 +00001164 for c in ph.loggerMap.keys():
Thomas Wouters89f507f2006-12-13 04:49:30 +00001165 #The if means ... if not c.parent.name.startswith(nm)
1166 if c.parent.name[:namelen] != name:
Guido van Rossum57102f82002-11-13 16:15:58 +00001167 alogger.parent = c.parent
1168 c.parent = alogger
1169
1170#---------------------------------------------------------------------------
1171# Logger classes and functions
1172#---------------------------------------------------------------------------
1173
1174class Logger(Filterer):
1175 """
1176 Instances of the Logger class represent a single logging channel. A
1177 "logging channel" indicates an area of an application. Exactly how an
1178 "area" is defined is up to the application developer. Since an
1179 application can have any number of areas, logging channels are identified
1180 by a unique string. Application areas can be nested (e.g. an area
1181 of "input processing" might include sub-areas "read CSV files", "read
1182 XLS files" and "read Gnumeric files"). To cater for this natural nesting,
1183 channel names are organized into a namespace hierarchy where levels are
1184 separated by periods, much like the Java or Python package namespace. So
1185 in the instance given above, channel names might be "input" for the upper
1186 level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels.
1187 There is no arbitrary limit to the depth of nesting.
1188 """
1189 def __init__(self, name, level=NOTSET):
1190 """
1191 Initialize the logger with a name and an optional level.
1192 """
1193 Filterer.__init__(self)
1194 self.name = name
Vinay Sajipd4fabf42009-07-13 11:28:25 +00001195 self.level = _checkLevel(level)
Guido van Rossum57102f82002-11-13 16:15:58 +00001196 self.parent = None
1197 self.propagate = 1
1198 self.handlers = []
1199 self.disabled = 0
1200
1201 def setLevel(self, level):
1202 """
1203 Set the logging level of this logger.
1204 """
Vinay Sajipd4fabf42009-07-13 11:28:25 +00001205 self.level = _checkLevel(level)
Guido van Rossum57102f82002-11-13 16:15:58 +00001206
Guido van Rossum57102f82002-11-13 16:15:58 +00001207 def debug(self, msg, *args, **kwargs):
1208 """
1209 Log 'msg % args' with severity 'DEBUG'.
1210
1211 To pass exception information, use the keyword argument exc_info with
1212 a true value, e.g.
1213
1214 logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
1215 """
Guido van Rossum04110fb2007-08-24 16:32:05 +00001216 if self.isEnabledFor(DEBUG):
Neal Norwitzd9108552006-03-17 08:00:19 +00001217 self._log(DEBUG, msg, args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001218
1219 def info(self, msg, *args, **kwargs):
1220 """
1221 Log 'msg % args' with severity 'INFO'.
1222
1223 To pass exception information, use the keyword argument exc_info with
1224 a true value, e.g.
1225
1226 logger.info("Houston, we have a %s", "interesting problem", exc_info=1)
1227 """
Guido van Rossum04110fb2007-08-24 16:32:05 +00001228 if self.isEnabledFor(INFO):
Neal Norwitzd9108552006-03-17 08:00:19 +00001229 self._log(INFO, msg, args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001230
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001231 def warning(self, msg, *args, **kwargs):
Guido van Rossum57102f82002-11-13 16:15:58 +00001232 """
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001233 Log 'msg % args' with severity 'WARNING'.
Guido van Rossum57102f82002-11-13 16:15:58 +00001234
1235 To pass exception information, use the keyword argument exc_info with
1236 a true value, e.g.
1237
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001238 logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)
Guido van Rossum57102f82002-11-13 16:15:58 +00001239 """
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001240 if self.isEnabledFor(WARNING):
Neal Norwitzd9108552006-03-17 08:00:19 +00001241 self._log(WARNING, msg, args, **kwargs)
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001242
1243 warn = warning
Guido van Rossum57102f82002-11-13 16:15:58 +00001244
1245 def error(self, msg, *args, **kwargs):
1246 """
1247 Log 'msg % args' with severity 'ERROR'.
1248
1249 To pass exception information, use the keyword argument exc_info with
1250 a true value, e.g.
1251
1252 logger.error("Houston, we have a %s", "major problem", exc_info=1)
1253 """
Guido van Rossum57102f82002-11-13 16:15:58 +00001254 if self.isEnabledFor(ERROR):
Neal Norwitzd9108552006-03-17 08:00:19 +00001255 self._log(ERROR, msg, args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001256
Vinay Sajip8593ae62010-11-14 21:33:04 +00001257 def exception(self, msg, *args, **kwargs):
Guido van Rossum57102f82002-11-13 16:15:58 +00001258 """
1259 Convenience method for logging an ERROR with exception information.
1260 """
Vinay Sajip8593ae62010-11-14 21:33:04 +00001261 kwargs['exc_info'] = True
1262 self.error(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001263
1264 def critical(self, msg, *args, **kwargs):
1265 """
1266 Log 'msg % args' with severity 'CRITICAL'.
1267
1268 To pass exception information, use the keyword argument exc_info with
1269 a true value, e.g.
1270
1271 logger.critical("Houston, we have a %s", "major disaster", exc_info=1)
1272 """
Guido van Rossum04110fb2007-08-24 16:32:05 +00001273 if self.isEnabledFor(CRITICAL):
Neal Norwitzd9108552006-03-17 08:00:19 +00001274 self._log(CRITICAL, msg, args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001275
1276 fatal = critical
1277
1278 def log(self, level, msg, *args, **kwargs):
1279 """
Vinay Sajipeb477d02004-08-04 08:38:08 +00001280 Log 'msg % args' with the integer severity 'level'.
Guido van Rossum57102f82002-11-13 16:15:58 +00001281
1282 To pass exception information, use the keyword argument exc_info with
1283 a true value, e.g.
1284
1285 logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
1286 """
Guido van Rossum13257902007-06-07 23:15:56 +00001287 if not isinstance(level, int):
Vinay Sajip779e0c92004-07-03 11:47:26 +00001288 if raiseExceptions:
Collin Winterce36ad82007-08-30 01:19:48 +00001289 raise TypeError("level must be an integer")
Vinay Sajip779e0c92004-07-03 11:47:26 +00001290 else:
1291 return
Guido van Rossum57102f82002-11-13 16:15:58 +00001292 if self.isEnabledFor(level):
Neal Norwitzd9108552006-03-17 08:00:19 +00001293 self._log(level, msg, args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001294
Vinay Sajip8593ae62010-11-14 21:33:04 +00001295 def findCaller(self, stack_info=False):
Guido van Rossum57102f82002-11-13 16:15:58 +00001296 """
1297 Find the stack frame of the caller so that we can note the source
Vinay Sajip829dc512005-02-18 11:53:32 +00001298 file name, line number and function name.
Guido van Rossum57102f82002-11-13 16:15:58 +00001299 """
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001300 f = currentframe()
1301 #On some versions of IronPython, currentframe() returns None if
1302 #IronPython isn't run with -X:Frames.
1303 if f is not None:
1304 f = f.f_back
Vinay Sajip8593ae62010-11-14 21:33:04 +00001305 rv = "(unknown file)", 0, "(unknown function)", None
Thomas Woutersa9773292006-04-21 09:43:23 +00001306 while hasattr(f, "f_code"):
Jeremy Hylton250684d2003-01-23 18:29:29 +00001307 co = f.f_code
1308 filename = os.path.normcase(co.co_filename)
1309 if filename == _srcfile:
1310 f = f.f_back
1311 continue
Vinay Sajip8593ae62010-11-14 21:33:04 +00001312 sinfo = None
1313 if stack_info:
1314 sio = io.StringIO()
1315 sio.write('Stack (most recent call last):\n')
1316 traceback.print_stack(f, file=sio)
1317 sinfo = sio.getvalue()
1318 if sinfo[-1] == '\n':
1319 sinfo = sinfo[:-1]
1320 sio.close()
1321 rv = (co.co_filename, f.f_lineno, co.co_name, sinfo)
Thomas Woutersa9773292006-04-21 09:43:23 +00001322 break
1323 return rv
Guido van Rossum57102f82002-11-13 16:15:58 +00001324
Vinay Sajip8593ae62010-11-14 21:33:04 +00001325 def makeRecord(self, name, level, fn, lno, msg, args, exc_info,
1326 func=None, extra=None, sinfo=None):
Guido van Rossum57102f82002-11-13 16:15:58 +00001327 """
1328 A factory method which can be overridden in subclasses to create
1329 specialized LogRecords.
1330 """
Vinay Sajip61561522010-12-03 11:50:38 +00001331 rv = _logRecordFactory(name, level, fn, lno, msg, args, exc_info, func,
Vinay Sajip8593ae62010-11-14 21:33:04 +00001332 sinfo)
Christian Heimes04c420f2008-01-18 18:40:46 +00001333 if extra is not None:
Vinay Sajip260ce432006-02-09 08:34:14 +00001334 for key in extra:
1335 if (key in ["message", "asctime"]) or (key in rv.__dict__):
1336 raise KeyError("Attempt to overwrite %r in LogRecord" % key)
1337 rv.__dict__[key] = extra[key]
1338 return rv
Guido van Rossum57102f82002-11-13 16:15:58 +00001339
Vinay Sajip8593ae62010-11-14 21:33:04 +00001340 def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False):
Guido van Rossum57102f82002-11-13 16:15:58 +00001341 """
1342 Low-level logging routine which creates a LogRecord and then calls
1343 all the handlers of this logger to handle the record.
1344 """
Vinay Sajip8593ae62010-11-14 21:33:04 +00001345 sinfo = None
Jeremy Hylton250684d2003-01-23 18:29:29 +00001346 if _srcfile:
Vinay Sajipb672b6d2009-02-19 12:36:11 +00001347 #IronPython doesn't track Python frames, so findCaller throws an
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001348 #exception on some versions of IronPython. We trap it here so that
1349 #IronPython can use logging.
Vinay Sajipb672b6d2009-02-19 12:36:11 +00001350 try:
Vinay Sajip8593ae62010-11-14 21:33:04 +00001351 fn, lno, func, sinfo = self.findCaller(stack_info)
Vinay Sajipb672b6d2009-02-19 12:36:11 +00001352 except ValueError:
1353 fn, lno, func = "(unknown file)", 0, "(unknown function)"
Guido van Rossum57102f82002-11-13 16:15:58 +00001354 else:
Vinay Sajip829dc512005-02-18 11:53:32 +00001355 fn, lno, func = "(unknown file)", 0, "(unknown function)"
Guido van Rossum57102f82002-11-13 16:15:58 +00001356 if exc_info:
Guido van Rossum13257902007-06-07 23:15:56 +00001357 if not isinstance(exc_info, tuple):
Vinay Sajiped6bb142004-02-20 13:18:36 +00001358 exc_info = sys.exc_info()
Vinay Sajip8593ae62010-11-14 21:33:04 +00001359 record = self.makeRecord(self.name, level, fn, lno, msg, args,
1360 exc_info, func, extra, sinfo)
Guido van Rossum57102f82002-11-13 16:15:58 +00001361 self.handle(record)
1362
1363 def handle(self, record):
1364 """
1365 Call the handlers for the specified record.
1366
1367 This method is used for unpickled records received from a socket, as
1368 well as those created locally. Logger-level filtering is applied.
1369 """
1370 if (not self.disabled) and self.filter(record):
1371 self.callHandlers(record)
1372
1373 def addHandler(self, hdlr):
1374 """
1375 Add the specified handler to this logger.
1376 """
Vinay Sajip32fb6a82010-09-25 17:42:36 +00001377 _acquireLock()
1378 try:
1379 if not (hdlr in self.handlers):
1380 self.handlers.append(hdlr)
1381 finally:
1382 _releaseLock()
Guido van Rossum57102f82002-11-13 16:15:58 +00001383
1384 def removeHandler(self, hdlr):
1385 """
1386 Remove the specified handler from this logger.
1387 """
Vinay Sajip32fb6a82010-09-25 17:42:36 +00001388 _acquireLock()
1389 try:
1390 if hdlr in self.handlers:
Vinay Sajip116f16e2005-09-16 10:33:40 +00001391 self.handlers.remove(hdlr)
Vinay Sajip32fb6a82010-09-25 17:42:36 +00001392 finally:
1393 _releaseLock()
Guido van Rossum57102f82002-11-13 16:15:58 +00001394
Vinay Sajipb4a08092010-09-20 09:55:00 +00001395 def hasHandlers(self):
1396 """
1397 See if this logger has any handlers configured.
1398
1399 Loop through all handlers for this logger and its parents in the
1400 logger hierarchy. Return True if a handler was found, else False.
1401 Stop searching up the hierarchy whenever a logger with the "propagate"
1402 attribute set to zero is found - that will be the last logger which
1403 is checked for the existence of handlers.
1404 """
1405 c = self
1406 rv = False
1407 while c:
1408 if c.handlers:
1409 rv = True
1410 break
1411 if not c.propagate:
1412 break
1413 else:
1414 c = c.parent
1415 return rv
1416
Guido van Rossum57102f82002-11-13 16:15:58 +00001417 def callHandlers(self, record):
1418 """
1419 Pass a record to all relevant handlers.
1420
1421 Loop through all handlers for this logger and its parents in the
1422 logger hierarchy. If no handler was found, output a one-off error
1423 message to sys.stderr. Stop searching up the hierarchy whenever a
1424 logger with the "propagate" attribute set to zero is found - that
1425 will be the last logger whose handlers are called.
1426 """
1427 c = self
1428 found = 0
1429 while c:
1430 for hdlr in c.handlers:
1431 found = found + 1
1432 if record.levelno >= hdlr.level:
1433 hdlr.handle(record)
1434 if not c.propagate:
1435 c = None #break out
1436 else:
1437 c = c.parent
Vinay Sajip5a27d402010-12-10 11:42:57 +00001438 if (found == 0):
1439 if lastResort:
1440 lastResort.handle(record)
1441 elif raiseExceptions and not self.manager.emittedNoHandlerWarning:
1442 sys.stderr.write("No handlers could be found for logger"
1443 " \"%s\"\n" % self.name)
1444 self.manager.emittedNoHandlerWarning = True
Guido van Rossum57102f82002-11-13 16:15:58 +00001445
1446 def getEffectiveLevel(self):
1447 """
1448 Get the effective level for this logger.
1449
1450 Loop through this logger and its parents in the logger hierarchy,
1451 looking for a non-zero logging level. Return the first one found.
1452 """
1453 logger = self
1454 while logger:
1455 if logger.level:
1456 return logger.level
1457 logger = logger.parent
1458 return NOTSET
1459
1460 def isEnabledFor(self, level):
1461 """
1462 Is this logger enabled for level 'level'?
1463 """
1464 if self.manager.disable >= level:
1465 return 0
1466 return level >= self.getEffectiveLevel()
1467
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001468 def getChild(self, suffix):
1469 """
1470 Get a logger which is a descendant to this one.
1471
1472 This is a convenience method, such that
1473
1474 logging.getLogger('abc').getChild('def.ghi')
1475
1476 is the same as
1477
1478 logging.getLogger('abc.def.ghi')
1479
1480 It's useful, for example, when the parent logger is named using
1481 __name__ rather than a literal string.
1482 """
1483 if self.root is not self:
1484 suffix = '.'.join((self.name, suffix))
1485 return self.manager.getLogger(suffix)
1486
Guido van Rossum57102f82002-11-13 16:15:58 +00001487class RootLogger(Logger):
1488 """
1489 A root logger is not that different to any other logger, except that
1490 it must have a logging level and there is only one instance of it in
1491 the hierarchy.
1492 """
1493 def __init__(self, level):
1494 """
1495 Initialize the logger with the name "root".
1496 """
1497 Logger.__init__(self, "root", level)
1498
1499_loggerClass = Logger
1500
Benjamin Peterson55549932009-11-25 17:19:56 +00001501class LoggerAdapter(object):
Christian Heimes04c420f2008-01-18 18:40:46 +00001502 """
1503 An adapter for loggers which makes it easier to specify contextual
1504 information in logging output.
1505 """
1506
1507 def __init__(self, logger, extra):
1508 """
1509 Initialize the adapter with a logger and a dict-like object which
1510 provides contextual information. This constructor signature allows
1511 easy stacking of LoggerAdapters, if so desired.
1512
1513 You can effectively pass keyword arguments as shown in the
1514 following example:
1515
1516 adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2"))
1517 """
1518 self.logger = logger
1519 self.extra = extra
1520
1521 def process(self, msg, kwargs):
1522 """
1523 Process the logging message and keyword arguments passed in to
1524 a logging call to insert contextual information. You can either
1525 manipulate the message itself, the keyword args or both. Return
1526 the message and kwargs modified (or not) to suit your needs.
1527
1528 Normally, you'll only need to override this one method in a
1529 LoggerAdapter subclass for your specific needs.
1530 """
1531 kwargs["extra"] = self.extra
1532 return msg, kwargs
1533
Vinay Sajip212b5902010-09-21 11:31:32 +00001534 #
1535 # Boilerplate convenience methods
1536 #
Christian Heimes04c420f2008-01-18 18:40:46 +00001537 def debug(self, msg, *args, **kwargs):
1538 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001539 Delegate a debug call to the underlying logger.
Christian Heimes04c420f2008-01-18 18:40:46 +00001540 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001541 self.log(DEBUG, msg, *args, **kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00001542
1543 def info(self, msg, *args, **kwargs):
1544 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001545 Delegate an info call to the underlying logger.
Christian Heimes04c420f2008-01-18 18:40:46 +00001546 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001547 self.log(INFO, msg, *args, **kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00001548
1549 def warning(self, msg, *args, **kwargs):
1550 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001551 Delegate a warning call to the underlying logger.
Christian Heimes04c420f2008-01-18 18:40:46 +00001552 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001553 self.log(WARNING, msg, *args, **kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00001554
Vinay Sajipc84f0162010-09-21 11:25:39 +00001555 warn = warning
1556
Christian Heimes04c420f2008-01-18 18:40:46 +00001557 def error(self, msg, *args, **kwargs):
1558 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001559 Delegate an error call to the underlying logger.
Christian Heimes04c420f2008-01-18 18:40:46 +00001560 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001561 self.log(ERROR, msg, *args, **kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00001562
1563 def exception(self, msg, *args, **kwargs):
1564 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001565 Delegate an exception call to the underlying logger.
Christian Heimes04c420f2008-01-18 18:40:46 +00001566 """
Christian Heimes04c420f2008-01-18 18:40:46 +00001567 kwargs["exc_info"] = 1
Vinay Sajip212b5902010-09-21 11:31:32 +00001568 self.log(ERROR, msg, *args, **kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00001569
1570 def critical(self, msg, *args, **kwargs):
1571 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001572 Delegate a critical call to the underlying logger.
Christian Heimes04c420f2008-01-18 18:40:46 +00001573 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001574 self.log(CRITICAL, msg, *args, **kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00001575
1576 def log(self, level, msg, *args, **kwargs):
1577 """
1578 Delegate a log call to the underlying logger, after adding
1579 contextual information from this adapter instance.
1580 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001581 if self.isEnabledFor(level):
1582 msg, kwargs = self.process(msg, kwargs)
1583 self.logger._log(level, msg, args, **kwargs)
1584
1585 def isEnabledFor(self, level):
1586 """
1587 Is this logger enabled for level 'level'?
1588 """
1589 if self.logger.manager.disable >= level:
1590 return False
1591 return level >= self.getEffectiveLevel()
Christian Heimes04c420f2008-01-18 18:40:46 +00001592
Vinay Sajipc84f0162010-09-21 11:25:39 +00001593 def setLevel(self, level):
1594 """
1595 Set the specified level on the underlying logger.
1596 """
1597 self.logger.setLevel(level)
1598
Vinay Sajipc84f0162010-09-21 11:25:39 +00001599 def getEffectiveLevel(self):
1600 """
1601 Get the effective level for the underlying logger.
1602 """
1603 return self.logger.getEffectiveLevel()
1604
Vinay Sajip61c3f0d2010-09-20 10:13:13 +00001605 def hasHandlers(self):
1606 """
1607 See if the underlying logger has any handlers.
1608 """
1609 return self.logger.hasHandlers()
1610
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001611root = RootLogger(WARNING)
Guido van Rossum57102f82002-11-13 16:15:58 +00001612Logger.root = root
1613Logger.manager = Manager(Logger.root)
1614
1615#---------------------------------------------------------------------------
1616# Configuration classes and functions
1617#---------------------------------------------------------------------------
1618
1619BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s"
1620
Vinay Sajip779e0c92004-07-03 11:47:26 +00001621def basicConfig(**kwargs):
Guido van Rossum57102f82002-11-13 16:15:58 +00001622 """
Vinay Sajip779e0c92004-07-03 11:47:26 +00001623 Do basic configuration for the logging system.
1624
1625 This function does nothing if the root logger already has handlers
1626 configured. It is a convenience method intended for use by simple scripts
1627 to do one-shot configuration of the logging package.
1628
1629 The default behaviour is to create a StreamHandler which writes to
1630 sys.stderr, set a formatter using the BASIC_FORMAT format string, and
1631 add the handler to the root logger.
1632
1633 A number of optional keyword arguments may be specified, which can alter
1634 the default behaviour.
1635
1636 filename Specifies that a FileHandler be created, using the specified
1637 filename, rather than a StreamHandler.
1638 filemode Specifies the mode to open the file, if filename is specified
Vinay Sajipb89e7c92005-03-13 09:54:31 +00001639 (if filemode is unspecified, it defaults to 'a').
Vinay Sajip779e0c92004-07-03 11:47:26 +00001640 format Use the specified format string for the handler.
1641 datefmt Use the specified date/time format.
Vinay Sajipc5b27302010-10-31 14:59:16 +00001642 style If a format string is specified, use this to specify the
1643 type of format string (possible values '%', '{', '$', for
1644 %-formatting, :meth:`str.format` and :class:`string.Template`
1645 - defaults to '%').
Vinay Sajip779e0c92004-07-03 11:47:26 +00001646 level Set the root logger level to the specified level.
1647 stream Use the specified stream to initialize the StreamHandler. Note
1648 that this argument is incompatible with 'filename' - if both
1649 are present, 'stream' is ignored.
1650
1651 Note that you could specify a stream created using open(filename, mode)
1652 rather than passing the filename and mode in. However, it should be
1653 remembered that StreamHandler does not close its stream (since it may be
1654 using sys.stdout or sys.stderr), whereas FileHandler closes its stream
1655 when the handler is closed.
Vinay Sajipc5b27302010-10-31 14:59:16 +00001656
1657 .. versionchanged: 3.2
1658 Added the ``style`` parameter.
Guido van Rossum57102f82002-11-13 16:15:58 +00001659 """
Vinay Sajip2314fc72010-09-10 08:25:13 +00001660 # Add thread safety in case someone mistakenly calls
1661 # basicConfig() from multiple threads
1662 _acquireLock()
1663 try:
1664 if len(root.handlers) == 0:
1665 filename = kwargs.get("filename")
1666 if filename:
1667 mode = kwargs.get("filemode", 'a')
1668 hdlr = FileHandler(filename, mode)
1669 else:
1670 stream = kwargs.get("stream")
1671 hdlr = StreamHandler(stream)
1672 fs = kwargs.get("format", BASIC_FORMAT)
1673 dfs = kwargs.get("datefmt", None)
Vinay Sajipc5b27302010-10-31 14:59:16 +00001674 style = kwargs.get("style", '%')
1675 fmt = Formatter(fs, dfs, style)
Vinay Sajip2314fc72010-09-10 08:25:13 +00001676 hdlr.setFormatter(fmt)
1677 root.addHandler(hdlr)
1678 level = kwargs.get("level")
1679 if level is not None:
1680 root.setLevel(level)
1681 finally:
1682 _releaseLock()
Guido van Rossum57102f82002-11-13 16:15:58 +00001683
1684#---------------------------------------------------------------------------
1685# Utility functions at module level.
1686# Basically delegate everything to the root logger.
1687#---------------------------------------------------------------------------
1688
1689def getLogger(name=None):
1690 """
1691 Return a logger with the specified name, creating it if necessary.
1692
1693 If no name is specified, return the root logger.
1694 """
1695 if name:
1696 return Logger.manager.getLogger(name)
1697 else:
1698 return root
1699
Guido van Rossum57102f82002-11-13 16:15:58 +00001700def critical(msg, *args, **kwargs):
1701 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001702 Log a message with severity 'CRITICAL' on the root logger. If the logger
1703 has no handlers, call basicConfig() to add a console handler with a
1704 pre-defined format.
Guido van Rossum57102f82002-11-13 16:15:58 +00001705 """
1706 if len(root.handlers) == 0:
1707 basicConfig()
Neal Norwitzd9108552006-03-17 08:00:19 +00001708 root.critical(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001709
1710fatal = critical
1711
1712def error(msg, *args, **kwargs):
1713 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001714 Log a message with severity 'ERROR' on the root logger. If the logger has
1715 no handlers, call basicConfig() to add a console handler with a pre-defined
1716 format.
Guido van Rossum57102f82002-11-13 16:15:58 +00001717 """
1718 if len(root.handlers) == 0:
1719 basicConfig()
Neal Norwitzd9108552006-03-17 08:00:19 +00001720 root.error(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001721
Vinay Sajip8593ae62010-11-14 21:33:04 +00001722def exception(msg, *args, **kwargs):
Guido van Rossum57102f82002-11-13 16:15:58 +00001723 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001724 Log a message with severity 'ERROR' on the root logger, with exception
1725 information. If the logger has no handlers, basicConfig() is called to add
1726 a console handler with a pre-defined format.
Guido van Rossum57102f82002-11-13 16:15:58 +00001727 """
Vinay Sajip8593ae62010-11-14 21:33:04 +00001728 kwargs['exc_info'] = True
1729 error(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001730
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001731def warning(msg, *args, **kwargs):
Guido van Rossum57102f82002-11-13 16:15:58 +00001732 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001733 Log a message with severity 'WARNING' on the root logger. If the logger has
1734 no handlers, call basicConfig() to add a console handler with a pre-defined
1735 format.
Guido van Rossum57102f82002-11-13 16:15:58 +00001736 """
1737 if len(root.handlers) == 0:
1738 basicConfig()
Neal Norwitzd9108552006-03-17 08:00:19 +00001739 root.warning(msg, *args, **kwargs)
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001740
1741warn = warning
Guido van Rossum57102f82002-11-13 16:15:58 +00001742
1743def info(msg, *args, **kwargs):
1744 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001745 Log a message with severity 'INFO' on the root logger. If the logger has
1746 no handlers, call basicConfig() to add a console handler with a pre-defined
1747 format.
Guido van Rossum57102f82002-11-13 16:15:58 +00001748 """
1749 if len(root.handlers) == 0:
1750 basicConfig()
Neal Norwitzd9108552006-03-17 08:00:19 +00001751 root.info(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001752
1753def debug(msg, *args, **kwargs):
1754 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001755 Log a message with severity 'DEBUG' on the root logger. If the logger has
1756 no handlers, call basicConfig() to add a console handler with a pre-defined
1757 format.
Guido van Rossum57102f82002-11-13 16:15:58 +00001758 """
1759 if len(root.handlers) == 0:
1760 basicConfig()
Neal Norwitzd9108552006-03-17 08:00:19 +00001761 root.debug(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001762
Vinay Sajipb2635b22004-09-24 11:45:52 +00001763def log(level, msg, *args, **kwargs):
1764 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001765 Log 'msg % args' with the integer severity 'level' on the root logger. If
1766 the logger has no handlers, call basicConfig() to add a console handler
1767 with a pre-defined format.
Vinay Sajipb2635b22004-09-24 11:45:52 +00001768 """
1769 if len(root.handlers) == 0:
1770 basicConfig()
Neal Norwitzd9108552006-03-17 08:00:19 +00001771 root.log(level, msg, *args, **kwargs)
Vinay Sajipb2635b22004-09-24 11:45:52 +00001772
Guido van Rossum57102f82002-11-13 16:15:58 +00001773def disable(level):
1774 """
Benjamin Peterson886af962010-03-21 23:13:07 +00001775 Disable all logging calls of severity 'level' and below.
Guido van Rossum57102f82002-11-13 16:15:58 +00001776 """
1777 root.manager.disable = level
1778
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001779def shutdown(handlerList=_handlerList):
Guido van Rossum57102f82002-11-13 16:15:58 +00001780 """
1781 Perform any cleanup actions in the logging system (e.g. flushing
1782 buffers).
1783
1784 Should be called at application exit.
1785 """
Benjamin Peterson55549932009-11-25 17:19:56 +00001786 for wr in reversed(handlerList[:]):
Vinay Sajipe12f7152004-07-29 09:19:30 +00001787 #errors might occur, for example, if files are locked
Vinay Sajip260ce432006-02-09 08:34:14 +00001788 #we just ignore them if raiseExceptions is not set
Vinay Sajipe12f7152004-07-29 09:19:30 +00001789 try:
Benjamin Peterson55549932009-11-25 17:19:56 +00001790 h = wr()
Vinay Sajipde6e9d62010-08-23 17:50:30 +00001791 if h:
1792 try:
1793 h.flush()
1794 h.close()
1795 except (IOError, ValueError):
1796 # Ignore errors which might be caused
1797 # because handlers have been closed but
1798 # references to them are still around at
1799 # application exit.
1800 pass
Vinay Sajipe12f7152004-07-29 09:19:30 +00001801 except:
Vinay Sajip260ce432006-02-09 08:34:14 +00001802 if raiseExceptions:
1803 raise
1804 #else, swallow
Vinay Sajiped6bb142004-02-20 13:18:36 +00001805
1806#Let's try and shutdown automatically on application exit...
Georg Brandl01e4d572010-02-06 22:27:51 +00001807import atexit
1808atexit.register(shutdown)
Georg Brandlf9734072008-12-07 15:30:06 +00001809
1810# Null handler
1811
1812class NullHandler(Handler):
1813 """
1814 This handler does nothing. It's intended to be used to avoid the
1815 "No handlers could be found for logger XXX" one-off warning. This is
1816 important for library code, which may contain code to log events. If a user
1817 of the library does not configure logging, the one-off warning might be
1818 produced; to avoid this, the library developer simply needs to instantiate
1819 a NullHandler and add it to the top-level logger of the library module or
1820 package.
1821 """
Vinay Sajip4fbe4b32010-09-26 11:04:10 +00001822 def handle(self, record):
1823 pass
1824
Georg Brandlf9734072008-12-07 15:30:06 +00001825 def emit(self, record):
1826 pass
1827
Vinay Sajip4fbe4b32010-09-26 11:04:10 +00001828 def createLock(self):
1829 self.lock = None
1830
Georg Brandlf9734072008-12-07 15:30:06 +00001831# Warnings integration
1832
1833_warnings_showwarning = None
1834
1835def _showwarning(message, category, filename, lineno, file=None, line=None):
1836 """
1837 Implementation of showwarnings which redirects to logging, which will first
1838 check to see if the file parameter is None. If a file is specified, it will
1839 delegate to the original warnings implementation of showwarning. Otherwise,
1840 it will call warnings.formatwarning and will log the resulting string to a
1841 warnings logger named "py.warnings" with level logging.WARNING.
1842 """
1843 if file is not None:
1844 if _warnings_showwarning is not None:
1845 _warnings_showwarning(message, category, filename, lineno, file, line)
1846 else:
1847 s = warnings.formatwarning(message, category, filename, lineno, line)
1848 logger = getLogger("py.warnings")
1849 if not logger.handlers:
1850 logger.addHandler(NullHandler())
1851 logger.warning("%s", s)
1852
1853def captureWarnings(capture):
1854 """
1855 If capture is true, redirect all warnings to the logging package.
1856 If capture is False, ensure that warnings are not redirected to logging
1857 but to their original destinations.
1858 """
1859 global _warnings_showwarning
1860 if capture:
1861 if _warnings_showwarning is None:
1862 _warnings_showwarning = warnings.showwarning
1863 warnings.showwarning = _showwarning
1864 else:
1865 if _warnings_showwarning is not None:
1866 warnings.showwarning = _warnings_showwarning
1867 _warnings_showwarning = None