blob: 244c91536e40fe7bc540c068cc5a330c5756388f [file] [log] [blame]
Vinay Sajip9b727ec2012-01-25 17:49:45 +00001# Copyright 2001-2012 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 Sajip0abf61d2012-02-23 19:45:52 +000021Copyright (C) 2001-2012 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:
Guido van Rossum57102f82002-11-13 16:15:58 +000039 import threading
Vinay Sajip26fe4b72011-04-26 18:43:05 +010040except ImportError: #pragma: no cover
Victor Stinner2a129742011-05-30 23:02:52 +020041 threading = None
Guido van Rossum57102f82002-11-13 16:15:58 +000042
43__author__ = "Vinay Sajip <vinay_sajip@red-dove.com>"
Thomas Wouters477c8d52006-05-27 19:21:47 +000044__status__ = "production"
Vinay Sajipdb81c4c2010-02-25 23:13:06 +000045__version__ = "0.5.1.2"
46__date__ = "07 February 2010"
Guido van Rossum57102f82002-11-13 16:15:58 +000047
48#---------------------------------------------------------------------------
49# Miscellaneous module data
50#---------------------------------------------------------------------------
51
52#
Vinay Sajip829dc512005-02-18 11:53:32 +000053# _srcfile is used when walking the stack to check when we've got the first
Guido van Rossum57102f82002-11-13 16:15:58 +000054# caller stack frame.
Neal Norwitz6fa635d2003-02-18 14:20:07 +000055#
Vinay Sajipc384fc22005-09-02 11:20:33 +000056if hasattr(sys, 'frozen'): #support for py2exe
57 _srcfile = "logging%s__init__%s" % (os.sep, __file__[-4:])
Guido van Rossum57102f82002-11-13 16:15:58 +000058else:
Guido van Rossum455ab772002-11-13 16:18:29 +000059 _srcfile = __file__
60_srcfile = os.path.normcase(_srcfile)
Guido van Rossum57102f82002-11-13 16:15:58 +000061
Vinay Sajip829dc512005-02-18 11:53:32 +000062
Vinay Sajip26fe4b72011-04-26 18:43:05 +010063if hasattr(sys, '_getframe'):
64 currentframe = lambda: sys._getframe(3)
65else: #pragma: no cover
66 def currentframe():
67 """Return the frame object for the caller's stack frame."""
68 try:
69 raise Exception
Vinay Sajip8cf4eb12012-10-09 08:06:13 +010070 except Exception:
Vinay Sajip26fe4b72011-04-26 18:43:05 +010071 return sys.exc_info()[2].tb_frame.f_back
Vinay Sajip829dc512005-02-18 11:53:32 +000072
Jeremy Hylton250684d2003-01-23 18:29:29 +000073# _srcfile is only used in conjunction with sys._getframe().
74# To provide compatibility with older versions of Python, set _srcfile
75# to None if _getframe() is not available; this value will prevent
76# findCaller() from being called.
Vinay Sajip829dc512005-02-18 11:53:32 +000077#if not hasattr(sys, "_getframe"):
78# _srcfile = None
Jeremy Hylton250684d2003-01-23 18:29:29 +000079
Guido van Rossum57102f82002-11-13 16:15:58 +000080#
81#_startTime is used as the base when calculating the relative time of events
82#
83_startTime = time.time()
84
85#
86#raiseExceptions is used to see if exceptions during handling should be
87#propagated
88#
Vinay Sajip26fe4b72011-04-26 18:43:05 +010089raiseExceptions = True
Guido van Rossum57102f82002-11-13 16:15:58 +000090
Vinay Sajipd364a072006-03-13 22:05:28 +000091#
92# If you don't want threading information in the log, set this to zero
93#
Vinay Sajip26fe4b72011-04-26 18:43:05 +010094logThreads = True
Vinay Sajipd364a072006-03-13 22:05:28 +000095
96#
Jesse Noller9a0fc972009-01-18 21:12:58 +000097# If you don't want multiprocessing information in the log, set this to zero
98#
Vinay Sajip26fe4b72011-04-26 18:43:05 +010099logMultiprocessing = True
Jesse Noller9a0fc972009-01-18 21:12:58 +0000100
101#
Vinay Sajipd364a072006-03-13 22:05:28 +0000102# If you don't want process information in the log, set this to zero
103#
Vinay Sajip26fe4b72011-04-26 18:43:05 +0100104logProcesses = True
Vinay Sajipd364a072006-03-13 22:05:28 +0000105
Guido van Rossum57102f82002-11-13 16:15:58 +0000106#---------------------------------------------------------------------------
107# Level related stuff
108#---------------------------------------------------------------------------
109#
110# Default levels and level names, these can be replaced with any positive set
111# of values having corresponding names. There is a pseudo-level, NOTSET, which
112# is only really there as a lower limit for user-defined levels. Handlers and
113# loggers are initialized with NOTSET so that they will log all messages, even
114# at user-defined levels.
115#
Vinay Sajipb89e7c92005-03-13 09:54:31 +0000116
Guido van Rossum57102f82002-11-13 16:15:58 +0000117CRITICAL = 50
118FATAL = CRITICAL
119ERROR = 40
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000120WARNING = 30
121WARN = WARNING
Guido van Rossum57102f82002-11-13 16:15:58 +0000122INFO = 20
123DEBUG = 10
124NOTSET = 0
125
126_levelNames = {
127 CRITICAL : 'CRITICAL',
128 ERROR : 'ERROR',
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000129 WARNING : 'WARNING',
Guido van Rossum57102f82002-11-13 16:15:58 +0000130 INFO : 'INFO',
131 DEBUG : 'DEBUG',
132 NOTSET : 'NOTSET',
133 'CRITICAL' : CRITICAL,
134 'ERROR' : ERROR,
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000135 'WARN' : WARNING,
136 'WARNING' : WARNING,
Guido van Rossum57102f82002-11-13 16:15:58 +0000137 'INFO' : INFO,
138 'DEBUG' : DEBUG,
139 'NOTSET' : NOTSET,
140}
141
142def getLevelName(level):
143 """
144 Return the textual representation of logging level 'level'.
145
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000146 If the level is one of the predefined levels (CRITICAL, ERROR, WARNING,
Guido van Rossum57102f82002-11-13 16:15:58 +0000147 INFO, DEBUG) then you get the corresponding string. If you have
148 associated levels with names using addLevelName then the name you have
Vinay Sajip779e0c92004-07-03 11:47:26 +0000149 associated with 'level' is returned.
150
151 If a numeric value corresponding to one of the defined levels is passed
152 in, the corresponding string representation is returned.
153
154 Otherwise, the string "Level %s" % level is returned.
Guido van Rossum57102f82002-11-13 16:15:58 +0000155 """
156 return _levelNames.get(level, ("Level %s" % level))
157
158def addLevelName(level, levelName):
159 """
160 Associate 'levelName' with 'level'.
161
162 This is used when converting levels to text during message formatting.
163 """
164 _acquireLock()
165 try: #unlikely to cause an exception, but you never know...
166 _levelNames[level] = levelName
167 _levelNames[levelName] = level
168 finally:
169 _releaseLock()
170
Vinay Sajipd4fabf42009-07-13 11:28:25 +0000171def _checkLevel(level):
172 if isinstance(level, int):
173 rv = level
174 elif str(level) == level:
175 if level not in _levelNames:
176 raise ValueError("Unknown level: %r" % level)
177 rv = _levelNames[level]
178 else:
179 raise TypeError("Level not an integer or a valid string: %r" % level)
180 return rv
181
Guido van Rossum57102f82002-11-13 16:15:58 +0000182#---------------------------------------------------------------------------
183# Thread-related stuff
184#---------------------------------------------------------------------------
185
186#
187#_lock is used to serialize access to shared data structures in this module.
Benjamin Peterson55549932009-11-25 17:19:56 +0000188#This needs to be an RLock because fileConfig() creates and configures
189#Handlers, and so might arbitrary user threads. Since Handler code updates the
190#shared dictionary _handlers, it needs to acquire the lock. But if configuring,
Guido van Rossum57102f82002-11-13 16:15:58 +0000191#the lock would already have been acquired - so we need an RLock.
192#The same argument applies to Loggers and Manager.loggerDict.
193#
Victor Stinner2a129742011-05-30 23:02:52 +0200194if threading:
Vinay Sajip03f6c112009-11-27 14:03:36 +0000195 _lock = threading.RLock()
Vinay Sajip26fe4b72011-04-26 18:43:05 +0100196else: #pragma: no cover
Vinay Sajip03f6c112009-11-27 14:03:36 +0000197 _lock = None
198
Guido van Rossum57102f82002-11-13 16:15:58 +0000199
200def _acquireLock():
201 """
202 Acquire the module-level lock for serializing access to shared data.
203
204 This should be released with _releaseLock().
205 """
Guido van Rossum57102f82002-11-13 16:15:58 +0000206 if _lock:
207 _lock.acquire()
208
209def _releaseLock():
210 """
211 Release the module-level lock acquired by calling _acquireLock().
212 """
213 if _lock:
214 _lock.release()
215
216#---------------------------------------------------------------------------
217# The logging record
218#---------------------------------------------------------------------------
219
Benjamin Peterson55549932009-11-25 17:19:56 +0000220class LogRecord(object):
Guido van Rossum57102f82002-11-13 16:15:58 +0000221 """
222 A LogRecord instance represents an event being logged.
223
224 LogRecord instances are created every time something is logged. They
225 contain all the information pertinent to the event being logged. The
226 main information passed in is in msg and args, which are combined
227 using str(msg) % args to create the message field of the record. The
228 record also includes information such as when the record was created,
229 the source line where the logging call was made, and any exception
230 information to be logged.
231 """
Vinay Sajiped1992f2006-02-09 08:48:36 +0000232 def __init__(self, name, level, pathname, lineno,
Vinay Sajip61561522010-12-03 11:50:38 +0000233 msg, args, exc_info, func=None, sinfo=None, **kwargs):
Guido van Rossum57102f82002-11-13 16:15:58 +0000234 """
235 Initialize a logging record with interesting information.
236 """
237 ct = time.time()
238 self.name = name
239 self.msg = msg
Vinay Sajip4ed315a2004-10-20 08:39:40 +0000240 #
241 # The following statement allows passing of a dictionary as a sole
242 # argument, so that you can do something like
243 # logging.debug("a %(a)d b %(b)s", {'a':1, 'b':2})
244 # Suggested by Stefan Behnel.
245 # Note that without the test for args[0], we get a problem because
246 # during formatting, we test to see if the arg is present using
247 # 'if self.args:'. If the event being logged is e.g. 'Value is %d'
248 # and if the passed arg fails 'if self.args:' then no formatting
Vinay Sajip0a889532011-10-22 13:34:48 +0100249 # is done. For example, logger.warning('Value is %d', 0) would log
Vinay Sajip4ed315a2004-10-20 08:39:40 +0000250 # 'Value is %d' instead of 'Value is 0'.
251 # For the use case of passing a dictionary, this should not be a
252 # problem.
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000253 if args and len(args) == 1 and isinstance(args[0], dict) and args[0]:
Vinay Sajip4ed315a2004-10-20 08:39:40 +0000254 args = args[0]
Guido van Rossum57102f82002-11-13 16:15:58 +0000255 self.args = args
256 self.levelname = getLevelName(level)
257 self.levelno = level
258 self.pathname = pathname
259 try:
260 self.filename = os.path.basename(pathname)
261 self.module = os.path.splitext(self.filename)[0]
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000262 except (TypeError, ValueError, AttributeError):
Guido van Rossum57102f82002-11-13 16:15:58 +0000263 self.filename = pathname
264 self.module = "Unknown module"
265 self.exc_info = exc_info
Vinay Sajiped6bb142004-02-20 13:18:36 +0000266 self.exc_text = None # used to cache the traceback text
Vinay Sajip8593ae62010-11-14 21:33:04 +0000267 self.stack_info = sinfo
Guido van Rossum57102f82002-11-13 16:15:58 +0000268 self.lineno = lineno
Vinay Sajiped1992f2006-02-09 08:48:36 +0000269 self.funcName = func
Guido van Rossum57102f82002-11-13 16:15:58 +0000270 self.created = ct
Guido van Rossume2a383d2007-01-15 16:59:06 +0000271 self.msecs = (ct - int(ct)) * 1000
Guido van Rossum57102f82002-11-13 16:15:58 +0000272 self.relativeCreated = (self.created - _startTime) * 1000
Victor Stinner2a129742011-05-30 23:02:52 +0200273 if logThreads and threading:
274 self.thread = threading.get_ident()
Benjamin Peterson72753702008-08-18 18:09:21 +0000275 self.threadName = threading.current_thread().name
Vinay Sajip26fe4b72011-04-26 18:43:05 +0100276 else: # pragma: no cover
Guido van Rossum57102f82002-11-13 16:15:58 +0000277 self.thread = None
Vinay Sajip4a704862005-03-31 20:16:55 +0000278 self.threadName = None
Vinay Sajip26fe4b72011-04-26 18:43:05 +0100279 if not logMultiprocessing: # pragma: no cover
Jesse Noller9a0fc972009-01-18 21:12:58 +0000280 self.processName = None
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000281 else:
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000282 self.processName = 'MainProcess'
283 mp = sys.modules.get('multiprocessing')
284 if mp is not None:
285 # Errors may occur if multiprocessing has not finished loading
286 # yet - e.g. if a custom import hook causes third-party code
287 # to run when multiprocessing calls import. See issue 8200
288 # for an example
289 try:
290 self.processName = mp.current_process().name
Vinay Sajip9b727ec2012-01-25 17:49:45 +0000291 except Exception: #pragma: no cover
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000292 pass
Vinay Sajipd364a072006-03-13 22:05:28 +0000293 if logProcesses and hasattr(os, 'getpid'):
Jack Jansen4c641d02003-02-21 22:29:45 +0000294 self.process = os.getpid()
295 else:
296 self.process = None
Guido van Rossum57102f82002-11-13 16:15:58 +0000297
298 def __str__(self):
299 return '<LogRecord: %s, %s, %s, %s, "%s">'%(self.name, self.levelno,
300 self.pathname, self.lineno, self.msg)
301
302 def getMessage(self):
303 """
304 Return the message for this LogRecord.
305
306 Return the message for this LogRecord after merging any user-supplied
307 arguments with the message.
308 """
Vinay Sajipdc5097f2010-08-31 07:52:17 +0000309 msg = str(self.msg)
Guido van Rossum57102f82002-11-13 16:15:58 +0000310 if self.args:
311 msg = msg % self.args
312 return msg
313
Vinay Sajip062d56b2010-10-19 15:26:24 +0000314#
315# Determine which class to use when instantiating log records.
316#
Vinay Sajip61561522010-12-03 11:50:38 +0000317_logRecordFactory = LogRecord
Vinay Sajip062d56b2010-10-19 15:26:24 +0000318
Vinay Sajip61561522010-12-03 11:50:38 +0000319def setLogRecordFactory(factory):
Vinay Sajip062d56b2010-10-19 15:26:24 +0000320 """
Vinay Sajipfad058f2010-12-03 13:01:11 +0000321 Set the factory to be used when instantiating a log record.
Vinay Sajip062d56b2010-10-19 15:26:24 +0000322
Vinay Sajip61561522010-12-03 11:50:38 +0000323 :param factory: A callable which will be called to instantiate
324 a log record.
325 """
326 global _logRecordFactory
327 _logRecordFactory = factory
328
329def getLogRecordFactory():
Vinay Sajip062d56b2010-10-19 15:26:24 +0000330 """
Vinay Sajipfad058f2010-12-03 13:01:11 +0000331 Return the factory to be used when instantiating a log record.
Vinay Sajip062d56b2010-10-19 15:26:24 +0000332 """
333
Vinay Sajip61561522010-12-03 11:50:38 +0000334 return _logRecordFactory
Vinay Sajip062d56b2010-10-19 15:26:24 +0000335
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000336def makeLogRecord(dict):
337 """
338 Make a LogRecord whose attributes are defined by the specified dictionary,
339 This function is useful for converting a logging event received over
340 a socket connection (which is sent as a dictionary) into a LogRecord
341 instance.
342 """
Vinay Sajip61561522010-12-03 11:50:38 +0000343 rv = _logRecordFactory(None, None, "", 0, "", (), None, None)
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000344 rv.__dict__.update(dict)
345 return rv
346
Guido van Rossum57102f82002-11-13 16:15:58 +0000347#---------------------------------------------------------------------------
348# Formatter classes and functions
349#---------------------------------------------------------------------------
350
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000351class PercentStyle(object):
352
353 default_format = '%(message)s'
354 asctime_format = '%(asctime)s'
Vinay Sajip10914b72011-02-26 14:15:48 +0000355 asctime_search = '%(asctime)'
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000356
357 def __init__(self, fmt):
358 self._fmt = fmt or self.default_format
359
360 def usesTime(self):
Vinay Sajip10914b72011-02-26 14:15:48 +0000361 return self._fmt.find(self.asctime_search) >= 0
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000362
363 def format(self, record):
364 return self._fmt % record.__dict__
365
366class StrFormatStyle(PercentStyle):
367 default_format = '{message}'
368 asctime_format = '{asctime}'
Vinay Sajip10914b72011-02-26 14:15:48 +0000369 asctime_search = '{asctime'
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000370
371 def format(self, record):
372 return self._fmt.format(**record.__dict__)
373
374
375class StringTemplateStyle(PercentStyle):
376 default_format = '${message}'
377 asctime_format = '${asctime}'
Vinay Sajip89807a52011-02-26 16:06:02 +0000378 asctime_search = '${asctime}'
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000379
380 def __init__(self, fmt):
381 self._fmt = fmt or self.default_format
382 self._tpl = Template(self._fmt)
383
384 def usesTime(self):
385 fmt = self._fmt
386 return fmt.find('$asctime') >= 0 or fmt.find(self.asctime_format) >= 0
387
388 def format(self, record):
389 return self._tpl.substitute(**record.__dict__)
390
391_STYLES = {
392 '%': PercentStyle,
393 '{': StrFormatStyle,
394 '$': StringTemplateStyle
395}
396
Benjamin Peterson55549932009-11-25 17:19:56 +0000397class Formatter(object):
Guido van Rossum57102f82002-11-13 16:15:58 +0000398 """
399 Formatter instances are used to convert a LogRecord to text.
400
401 Formatters need to know how a LogRecord is constructed. They are
402 responsible for converting a LogRecord to (usually) a string which can
403 be interpreted by either a human or an external system. The base Formatter
404 allows a formatting string to be specified. If none is supplied, the
Vinay Sajip2a20dfc2010-10-20 20:05:38 +0000405 default value of "%s(message)" is used.
Guido van Rossum57102f82002-11-13 16:15:58 +0000406
407 The Formatter can be initialized with a format string which makes use of
408 knowledge of the LogRecord attributes - e.g. the default value mentioned
409 above makes use of the fact that the user's message and arguments are pre-
410 formatted into a LogRecord's message attribute. Currently, the useful
411 attributes in a LogRecord are described by:
412
413 %(name)s Name of the logger (logging channel)
414 %(levelno)s Numeric logging level for the message (DEBUG, INFO,
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000415 WARNING, ERROR, CRITICAL)
Guido van Rossum57102f82002-11-13 16:15:58 +0000416 %(levelname)s Text logging level for the message ("DEBUG", "INFO",
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000417 "WARNING", "ERROR", "CRITICAL")
Guido van Rossum57102f82002-11-13 16:15:58 +0000418 %(pathname)s Full pathname of the source file where the logging
419 call was issued (if available)
420 %(filename)s Filename portion of pathname
421 %(module)s Module (name portion of filename)
422 %(lineno)d Source line number where the logging call was issued
423 (if available)
Vinay Sajiped1992f2006-02-09 08:48:36 +0000424 %(funcName)s Function name
Guido van Rossum57102f82002-11-13 16:15:58 +0000425 %(created)f Time when the LogRecord was created (time.time()
426 return value)
427 %(asctime)s Textual time when the LogRecord was created
428 %(msecs)d Millisecond portion of the creation time
429 %(relativeCreated)d Time in milliseconds when the LogRecord was created,
430 relative to the time the logging module was loaded
431 (typically at application startup time)
432 %(thread)d Thread ID (if available)
Vinay Sajip4a704862005-03-31 20:16:55 +0000433 %(threadName)s Thread name (if available)
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000434 %(process)d Process ID (if available)
Guido van Rossum57102f82002-11-13 16:15:58 +0000435 %(message)s The result of record.getMessage(), computed just as
436 the record is emitted
437 """
438
439 converter = time.localtime
440
Vinay Sajipa39c5712010-10-25 13:57:39 +0000441 def __init__(self, fmt=None, datefmt=None, style='%'):
Guido van Rossum57102f82002-11-13 16:15:58 +0000442 """
443 Initialize the formatter with specified format strings.
444
445 Initialize the formatter either with the specified format string, or a
446 default as described above. Allow for specialized date formatting with
447 the optional datefmt argument (if omitted, you get the ISO8601 format).
Vinay Sajipa39c5712010-10-25 13:57:39 +0000448
449 Use a style parameter of '%', '{' or '$' to specify that you want to
450 use one of %-formatting, :meth:`str.format` (``{}``) formatting or
451 :class:`string.Template` formatting in your format string.
452
453 .. versionchanged: 3.2
454 Added the ``style`` parameter.
Guido van Rossum57102f82002-11-13 16:15:58 +0000455 """
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000456 if style not in _STYLES:
457 raise ValueError('Style must be one of: %s' % ','.join(
458 _STYLES.keys()))
459 self._style = _STYLES[style](fmt)
460 self._fmt = self._style._fmt
Guido van Rossum57102f82002-11-13 16:15:58 +0000461 self.datefmt = datefmt
462
Vinay Sajipae5740f2011-06-09 18:42:19 +0100463 default_time_format = '%Y-%m-%d %H:%M:%S'
464 default_msec_format = '%s,%03d'
465
Guido van Rossum57102f82002-11-13 16:15:58 +0000466 def formatTime(self, record, datefmt=None):
467 """
468 Return the creation time of the specified LogRecord as formatted text.
469
470 This method should be called from format() by a formatter which
471 wants to make use of a formatted time. This method can be overridden
472 in formatters to provide for any specific requirement, but the
473 basic behaviour is as follows: if datefmt (a string) is specified,
474 it is used with time.strftime() to format the creation time of the
475 record. Otherwise, the ISO8601 format is used. The resulting
476 string is returned. This function uses a user-configurable function
477 to convert the creation time to a tuple. By default, time.localtime()
478 is used; to change this for a particular formatter instance, set the
479 'converter' attribute to a function with the same signature as
480 time.localtime() or time.gmtime(). To change it for all formatters,
481 for example if you want all logging times to be shown in GMT,
482 set the 'converter' attribute in the Formatter class.
483 """
484 ct = self.converter(record.created)
485 if datefmt:
486 s = time.strftime(datefmt, ct)
487 else:
Vinay Sajipae5740f2011-06-09 18:42:19 +0100488 t = time.strftime(self.default_time_format, ct)
489 s = self.default_msec_format % (t, record.msecs)
Guido van Rossum57102f82002-11-13 16:15:58 +0000490 return s
491
492 def formatException(self, ei):
493 """
494 Format and return the specified exception information as a string.
495
496 This default implementation just uses
497 traceback.print_exception()
498 """
Guido van Rossum34d19282007-08-09 01:03:29 +0000499 sio = io.StringIO()
Vinay Sajip40d9a4e2010-08-30 18:10:03 +0000500 tb = ei[2]
501 # See issues #9427, #1553375. Commented out for now.
502 #if getattr(self, 'fullstack', False):
503 # traceback.print_stack(tb.tb_frame.f_back, file=sio)
504 traceback.print_exception(ei[0], ei[1], tb, None, sio)
Guido van Rossum57102f82002-11-13 16:15:58 +0000505 s = sio.getvalue()
506 sio.close()
Guido van Rossum486364b2007-06-30 05:01:58 +0000507 if s[-1:] == "\n":
Guido van Rossum57102f82002-11-13 16:15:58 +0000508 s = s[:-1]
509 return s
510
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000511 def usesTime(self):
512 """
513 Check if the format uses the creation time of the record.
514 """
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000515 return self._style.usesTime()
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000516
Vinay Sajipd0557bf2010-10-25 15:25:24 +0000517 def formatMessage(self, record):
Vinay Sajip6a65c5d2010-10-26 13:16:11 +0000518 return self._style.format(record)
Vinay Sajipd0557bf2010-10-25 15:25:24 +0000519
Vinay Sajip8593ae62010-11-14 21:33:04 +0000520 def formatStack(self, stack_info):
521 """
522 This method is provided as an extension point for specialized
523 formatting of stack information.
524
525 The input data is a string as returned from a call to
526 :func:`traceback.print_stack`, but with the last trailing newline
527 removed.
528
529 The base implementation just returns the value passed in.
530 """
531 return stack_info
532
Guido van Rossum57102f82002-11-13 16:15:58 +0000533 def format(self, record):
534 """
535 Format the specified record as text.
536
537 The record's attribute dictionary is used as the operand to a
538 string formatting operation which yields the returned string.
539 Before formatting the dictionary, a couple of preparatory steps
540 are carried out. The message attribute of the record is computed
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000541 using LogRecord.getMessage(). If the formatting string uses the
542 time (as determined by a call to usesTime(), formatTime() is
543 called to format the event time. If there is exception information,
544 it is formatted using formatException() and appended to the message.
Guido van Rossum57102f82002-11-13 16:15:58 +0000545 """
546 record.message = record.getMessage()
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000547 if self.usesTime():
Guido van Rossum57102f82002-11-13 16:15:58 +0000548 record.asctime = self.formatTime(record, self.datefmt)
Vinay Sajipd0557bf2010-10-25 15:25:24 +0000549 s = self.formatMessage(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000550 if record.exc_info:
Vinay Sajiped6bb142004-02-20 13:18:36 +0000551 # Cache the traceback text to avoid converting it multiple times
552 # (it's constant anyway)
553 if not record.exc_text:
554 record.exc_text = self.formatException(record.exc_info)
555 if record.exc_text:
Guido van Rossum486364b2007-06-30 05:01:58 +0000556 if s[-1:] != "\n":
Guido van Rossum57102f82002-11-13 16:15:58 +0000557 s = s + "\n"
Vinay Sajiped6bb142004-02-20 13:18:36 +0000558 s = s + record.exc_text
Vinay Sajip8593ae62010-11-14 21:33:04 +0000559 if record.stack_info:
560 if s[-1:] != "\n":
561 s = s + "\n"
562 s = s + self.formatStack(record.stack_info)
Guido van Rossum57102f82002-11-13 16:15:58 +0000563 return s
564
565#
566# The default formatter to use when no other is specified
567#
568_defaultFormatter = Formatter()
569
Benjamin Peterson55549932009-11-25 17:19:56 +0000570class BufferingFormatter(object):
Guido van Rossum57102f82002-11-13 16:15:58 +0000571 """
572 A formatter suitable for formatting a number of records.
573 """
574 def __init__(self, linefmt=None):
575 """
576 Optionally specify a formatter which will be used to format each
577 individual record.
578 """
579 if linefmt:
580 self.linefmt = linefmt
581 else:
582 self.linefmt = _defaultFormatter
583
584 def formatHeader(self, records):
585 """
586 Return the header string for the specified records.
587 """
588 return ""
589
590 def formatFooter(self, records):
591 """
592 Return the footer string for the specified records.
593 """
594 return ""
595
596 def format(self, records):
597 """
598 Format the specified records and return the result as a string.
599 """
600 rv = ""
601 if len(records) > 0:
602 rv = rv + self.formatHeader(records)
603 for record in records:
604 rv = rv + self.linefmt.format(record)
605 rv = rv + self.formatFooter(records)
606 return rv
607
608#---------------------------------------------------------------------------
609# Filter classes and functions
610#---------------------------------------------------------------------------
611
Benjamin Peterson55549932009-11-25 17:19:56 +0000612class Filter(object):
Guido van Rossum57102f82002-11-13 16:15:58 +0000613 """
614 Filter instances are used to perform arbitrary filtering of LogRecords.
615
616 Loggers and Handlers can optionally use Filter instances to filter
617 records as desired. The base filter class only allows events which are
618 below a certain point in the logger hierarchy. For example, a filter
619 initialized with "A.B" will allow events logged by loggers "A.B",
620 "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
621 initialized with the empty string, all events are passed.
622 """
623 def __init__(self, name=''):
624 """
625 Initialize a filter.
626
627 Initialize with the name of the logger which, together with its
628 children, will have its events allowed through the filter. If no
629 name is specified, allow every event.
630 """
631 self.name = name
632 self.nlen = len(name)
633
634 def filter(self, record):
635 """
636 Determine if the specified record is to be logged.
637
638 Is the specified record to be logged? Returns 0 for no, nonzero for
639 yes. If deemed appropriate, the record may be modified in-place.
640 """
641 if self.nlen == 0:
Vinay Sajip26fe4b72011-04-26 18:43:05 +0100642 return True
Guido van Rossum57102f82002-11-13 16:15:58 +0000643 elif self.name == record.name:
Vinay Sajip26fe4b72011-04-26 18:43:05 +0100644 return True
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000645 elif record.name.find(self.name, 0, self.nlen) != 0:
Vinay Sajip26fe4b72011-04-26 18:43:05 +0100646 return False
Guido van Rossum57102f82002-11-13 16:15:58 +0000647 return (record.name[self.nlen] == ".")
648
Benjamin Peterson55549932009-11-25 17:19:56 +0000649class Filterer(object):
Guido van Rossum57102f82002-11-13 16:15:58 +0000650 """
651 A base class for loggers and handlers which allows them to share
652 common code.
653 """
654 def __init__(self):
655 """
656 Initialize the list of filters to be an empty list.
657 """
658 self.filters = []
659
660 def addFilter(self, filter):
661 """
662 Add the specified filter to this handler.
663 """
664 if not (filter in self.filters):
665 self.filters.append(filter)
666
667 def removeFilter(self, filter):
668 """
669 Remove the specified filter from this handler.
670 """
671 if filter in self.filters:
672 self.filters.remove(filter)
673
674 def filter(self, record):
675 """
676 Determine if a record is loggable by consulting all the filters.
677
678 The default is to allow the record to be logged; any filter can veto
679 this and the record is then dropped. Returns a zero value if a record
680 is to be dropped, else non-zero.
Vinay Sajip6dbed2e2010-10-19 20:53:01 +0000681
682 .. versionchanged: 3.2
683
684 Allow filters to be just callables.
Guido van Rossum57102f82002-11-13 16:15:58 +0000685 """
Vinay Sajip312cc0d2011-04-30 21:51:51 +0100686 rv = True
Guido van Rossum57102f82002-11-13 16:15:58 +0000687 for f in self.filters:
Vinay Sajip6dbed2e2010-10-19 20:53:01 +0000688 if hasattr(f, 'filter'):
689 result = f.filter(record)
Vinay Sajip6dbed2e2010-10-19 20:53:01 +0000690 else:
Vinay Sajipfc082ca2010-10-19 21:13:49 +0000691 result = f(record) # assume callable - will raise if not
Vinay Sajip6dbed2e2010-10-19 20:53:01 +0000692 if not result:
Vinay Sajip312cc0d2011-04-30 21:51:51 +0100693 rv = False
Guido van Rossum57102f82002-11-13 16:15:58 +0000694 break
695 return rv
696
697#---------------------------------------------------------------------------
698# Handler classes and functions
699#---------------------------------------------------------------------------
700
Benjamin Peterson55549932009-11-25 17:19:56 +0000701_handlers = weakref.WeakValueDictionary() #map of handler names to handlers
Vinay Sajip0ee9ba22005-09-08 18:14:16 +0000702_handlerList = [] # added to allow handlers to be removed in reverse of order initialized
Guido van Rossum57102f82002-11-13 16:15:58 +0000703
Benjamin Peterson55549932009-11-25 17:19:56 +0000704def _removeHandlerRef(wr):
705 """
706 Remove a handler reference from the internal cleanup list.
707 """
Vinay Sajipde6e9d62010-08-23 17:50:30 +0000708 # This function can be called during module teardown, when globals are
709 # set to None. If _acquireLock is None, assume this is the case and do
710 # nothing.
Vinay Sajip5e1c3ce2013-01-15 17:55:57 +0000711 if (_acquireLock is not None and _handlerList is not None and
712 _releaseLock is not None):
Vinay Sajipde6e9d62010-08-23 17:50:30 +0000713 _acquireLock()
714 try:
715 if wr in _handlerList:
716 _handlerList.remove(wr)
717 finally:
718 _releaseLock()
Benjamin Peterson55549932009-11-25 17:19:56 +0000719
720def _addHandlerRef(handler):
721 """
722 Add a handler to the internal cleanup list using a weak reference.
723 """
724 _acquireLock()
725 try:
726 _handlerList.append(weakref.ref(handler, _removeHandlerRef))
727 finally:
728 _releaseLock()
729
Guido van Rossum57102f82002-11-13 16:15:58 +0000730class Handler(Filterer):
731 """
732 Handler instances dispatch logging events to specific destinations.
733
734 The base handler class. Acts as a placeholder which defines the Handler
735 interface. Handlers can optionally use Formatter instances to format
736 records as desired. By default, no formatter is specified; in this case,
737 the 'raw' message as determined by record.message is logged.
738 """
739 def __init__(self, level=NOTSET):
740 """
741 Initializes the instance - basically setting the formatter to None
742 and the filter list to empty.
743 """
744 Filterer.__init__(self)
Benjamin Peterson55549932009-11-25 17:19:56 +0000745 self._name = None
Vinay Sajipd4fabf42009-07-13 11:28:25 +0000746 self.level = _checkLevel(level)
Guido van Rossum57102f82002-11-13 16:15:58 +0000747 self.formatter = None
Benjamin Peterson55549932009-11-25 17:19:56 +0000748 # Add the handler to the global _handlerList (for cleanup on shutdown)
749 _addHandlerRef(self)
750 self.createLock()
751
752 def get_name(self):
753 return self._name
754
755 def set_name(self, name):
Guido van Rossum57102f82002-11-13 16:15:58 +0000756 _acquireLock()
Benjamin Peterson55549932009-11-25 17:19:56 +0000757 try:
758 if self._name in _handlers:
759 del _handlers[self._name]
760 self._name = name
761 if name:
762 _handlers[name] = self
Guido van Rossum57102f82002-11-13 16:15:58 +0000763 finally:
764 _releaseLock()
Benjamin Peterson55549932009-11-25 17:19:56 +0000765
766 name = property(get_name, set_name)
Guido van Rossum57102f82002-11-13 16:15:58 +0000767
768 def createLock(self):
769 """
770 Acquire a thread lock for serializing access to the underlying I/O.
771 """
Victor Stinner2a129742011-05-30 23:02:52 +0200772 if threading:
Vinay Sajip4a704862005-03-31 20:16:55 +0000773 self.lock = threading.RLock()
Vinay Sajip26fe4b72011-04-26 18:43:05 +0100774 else: #pragma: no cover
Guido van Rossum57102f82002-11-13 16:15:58 +0000775 self.lock = None
776
777 def acquire(self):
778 """
779 Acquire the I/O thread lock.
780 """
781 if self.lock:
782 self.lock.acquire()
783
784 def release(self):
785 """
786 Release the I/O thread lock.
787 """
788 if self.lock:
789 self.lock.release()
790
791 def setLevel(self, level):
792 """
Gregory P. Smithe85488c2011-12-17 12:36:34 -0800793 Set the logging level of this handler. level must be an int or a str.
Guido van Rossum57102f82002-11-13 16:15:58 +0000794 """
Vinay Sajipd4fabf42009-07-13 11:28:25 +0000795 self.level = _checkLevel(level)
Guido van Rossum57102f82002-11-13 16:15:58 +0000796
797 def format(self, record):
798 """
799 Format the specified record.
800
801 If a formatter is set, use it. Otherwise, use the default formatter
802 for the module.
803 """
804 if self.formatter:
805 fmt = self.formatter
806 else:
807 fmt = _defaultFormatter
808 return fmt.format(record)
809
810 def emit(self, record):
811 """
812 Do whatever it takes to actually log the specified logging record.
813
814 This version is intended to be implemented by subclasses and so
815 raises a NotImplementedError.
816 """
Collin Winterce36ad82007-08-30 01:19:48 +0000817 raise NotImplementedError('emit must be implemented '
818 'by Handler subclasses')
Guido van Rossum57102f82002-11-13 16:15:58 +0000819
820 def handle(self, record):
821 """
822 Conditionally emit the specified logging record.
823
824 Emission depends on filters which may have been added to the handler.
825 Wrap the actual emission of the record with acquisition/release of
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000826 the I/O thread lock. Returns whether the filter passed the record for
827 emission.
Guido van Rossum57102f82002-11-13 16:15:58 +0000828 """
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000829 rv = self.filter(record)
830 if rv:
Guido van Rossum57102f82002-11-13 16:15:58 +0000831 self.acquire()
832 try:
833 self.emit(record)
834 finally:
835 self.release()
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000836 return rv
Guido van Rossum57102f82002-11-13 16:15:58 +0000837
838 def setFormatter(self, fmt):
839 """
840 Set the formatter for this handler.
841 """
842 self.formatter = fmt
843
844 def flush(self):
845 """
846 Ensure all logging output has been flushed.
847
848 This version does nothing and is intended to be implemented by
849 subclasses.
850 """
851 pass
852
853 def close(self):
854 """
855 Tidy up any resources used by the handler.
856
Benjamin Peterson55549932009-11-25 17:19:56 +0000857 This version removes the handler from an internal map of handlers,
858 _handlers, which is used for handler lookup by name. Subclasses
Vinay Sajiped6bb142004-02-20 13:18:36 +0000859 should ensure that this gets called from overridden close()
860 methods.
Guido van Rossum57102f82002-11-13 16:15:58 +0000861 """
Vinay Sajiped6bb142004-02-20 13:18:36 +0000862 #get the module data lock, as we're updating a shared structure.
863 _acquireLock()
864 try: #unlikely to raise an exception, but you never know...
Benjamin Peterson55549932009-11-25 17:19:56 +0000865 if self._name and self._name in _handlers:
866 del _handlers[self._name]
Vinay Sajiped6bb142004-02-20 13:18:36 +0000867 finally:
868 _releaseLock()
Guido van Rossum57102f82002-11-13 16:15:58 +0000869
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000870 def handleError(self, record):
Guido van Rossum57102f82002-11-13 16:15:58 +0000871 """
872 Handle errors which occur during an emit() call.
873
874 This method should be called from handlers when an exception is
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000875 encountered during an emit() call. If raiseExceptions is false,
Guido van Rossum57102f82002-11-13 16:15:58 +0000876 exceptions get silently ignored. This is what is mostly wanted
877 for a logging system - most users will not care about errors in
878 the logging system, they are more interested in application errors.
879 You could, however, replace this with a custom handler if you wish.
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000880 The record which was being processed is passed in to this method.
Guido van Rossum57102f82002-11-13 16:15:58 +0000881 """
Vinay Sajip889bb292012-01-20 11:23:02 +0000882 if raiseExceptions and sys.stderr: # see issue 13807
Vinay Sajipd06d5402012-10-31 23:49:19 +0000883 t, v, tb = sys.exc_info()
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000884 try:
Vinay Sajipd06d5402012-10-31 23:49:19 +0000885 sys.stderr.write('--- Logging error ---\n')
886 traceback.print_exception(t, v, tb, None, sys.stderr)
887 sys.stderr.write('Call stack:\n')
888 # Walk the stack frame up until we're out of logging,
889 # so as to print the calling context.
890 frame = tb.tb_frame
891 while (frame and os.path.dirname(frame.f_code.co_filename) ==
892 __path__[0]):
893 frame = frame.f_back
894 if frame:
895 traceback.print_stack(frame, file=sys.stderr)
896 else:
897 # couldn't find the right stack frame, for some reason
898 sys.stderr.write('Logged from file %s, line %s\n' % (
899 record.filename, record.lineno))
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200900 except OSError: #pragma: no cover
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000901 pass # see issue 5971
902 finally:
Vinay Sajipd06d5402012-10-31 23:49:19 +0000903 del t, v, tb
Guido van Rossum57102f82002-11-13 16:15:58 +0000904
905class StreamHandler(Handler):
906 """
907 A handler class which writes logging records, appropriately formatted,
908 to a stream. Note that this class does not close the stream, as
909 sys.stdout or sys.stderr may be used.
910 """
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000911
Vinay Sajip2a20dfc2010-10-20 20:05:38 +0000912 terminator = '\n'
913
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000914 def __init__(self, stream=None):
Guido van Rossum57102f82002-11-13 16:15:58 +0000915 """
916 Initialize the handler.
917
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000918 If stream is not specified, sys.stderr is used.
Guido van Rossum57102f82002-11-13 16:15:58 +0000919 """
920 Handler.__init__(self)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000921 if stream is None:
922 stream = sys.stderr
923 self.stream = stream
Guido van Rossum57102f82002-11-13 16:15:58 +0000924
925 def flush(self):
926 """
927 Flushes the stream.
928 """
Vinay Sajipf0509032012-02-23 20:49:08 +0000929 self.acquire()
930 try:
Vinay Sajip0abf61d2012-02-23 19:45:52 +0000931 if self.stream and hasattr(self.stream, "flush"):
932 self.stream.flush()
Vinay Sajipf0509032012-02-23 20:49:08 +0000933 finally:
934 self.release()
Guido van Rossum57102f82002-11-13 16:15:58 +0000935
936 def emit(self, record):
937 """
938 Emit a record.
939
940 If a formatter is specified, it is used to format the record.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000941 The record is then written to the stream with a trailing newline. If
942 exception information is present, it is formatted using
943 traceback.print_exception and appended to the stream. If the stream
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000944 has an 'encoding' attribute, it is used to determine how to do the
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000945 output to the stream.
Guido van Rossum57102f82002-11-13 16:15:58 +0000946 """
947 try:
948 msg = self.format(record)
Benjamin Petersonf91df042009-02-13 02:50:59 +0000949 stream = self.stream
Vinay Sajip2a20dfc2010-10-20 20:05:38 +0000950 stream.write(msg)
951 stream.write(self.terminator)
Guido van Rossum57102f82002-11-13 16:15:58 +0000952 self.flush()
Vinay Sajip8cf4eb12012-10-09 08:06:13 +0100953 except Exception:
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000954 self.handleError(record)
Guido van Rossum57102f82002-11-13 16:15:58 +0000955
956class FileHandler(StreamHandler):
957 """
958 A handler class which writes formatted logging records to disk files.
959 """
Vinay Sajip26fe4b72011-04-26 18:43:05 +0100960 def __init__(self, filename, mode='a', encoding=None, delay=False):
Guido van Rossum57102f82002-11-13 16:15:58 +0000961 """
962 Open the specified file and use it as the stream for logging.
963 """
Vinay Sajip4bbab2b2004-07-08 10:22:35 +0000964 #keep the absolute path, otherwise derived classes which use this
965 #may come a cropper when the current directory changes
966 self.baseFilename = os.path.abspath(filename)
Guido van Rossum57102f82002-11-13 16:15:58 +0000967 self.mode = mode
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000968 self.encoding = encoding
Christian Heimese7a15bb2008-01-24 16:21:45 +0000969 if delay:
Vinay Sajip6268cbc2009-01-21 00:19:28 +0000970 #We don't open the stream, but we still need to call the
971 #Handler constructor to set level, formatter, lock etc.
972 Handler.__init__(self)
Christian Heimese7a15bb2008-01-24 16:21:45 +0000973 self.stream = None
974 else:
Vinay Sajip6268cbc2009-01-21 00:19:28 +0000975 StreamHandler.__init__(self, self._open())
Guido van Rossum57102f82002-11-13 16:15:58 +0000976
977 def close(self):
978 """
979 Closes the stream.
980 """
Vinay Sajipf0509032012-02-23 20:49:08 +0000981 self.acquire()
982 try:
Vinay Sajip0abf61d2012-02-23 19:45:52 +0000983 if self.stream:
984 self.flush()
985 if hasattr(self.stream, "close"):
986 self.stream.close()
987 StreamHandler.close(self)
988 self.stream = None
Vinay Sajipf0509032012-02-23 20:49:08 +0000989 finally:
990 self.release()
Guido van Rossum57102f82002-11-13 16:15:58 +0000991
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000992 def _open(self):
993 """
994 Open the current base file with the (original) mode and encoding.
995 Return the resulting stream.
996 """
Florent Xicluna5252f9f2011-11-07 19:43:05 +0100997 return open(self.baseFilename, self.mode, encoding=self.encoding)
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000998
Christian Heimese7a15bb2008-01-24 16:21:45 +0000999 def emit(self, record):
1000 """
1001 Emit a record.
1002
1003 If the stream was not opened because 'delay' was specified in the
1004 constructor, open it before calling the superclass's emit.
1005 """
1006 if self.stream is None:
Vinay Sajip6268cbc2009-01-21 00:19:28 +00001007 self.stream = self._open()
Christian Heimese7a15bb2008-01-24 16:21:45 +00001008 StreamHandler.emit(self, record)
1009
Vinay Sajip5a27d402010-12-10 11:42:57 +00001010class _StderrHandler(StreamHandler):
1011 """
1012 This class is like a StreamHandler using sys.stderr, but always uses
1013 whatever sys.stderr is currently set to rather than the value of
1014 sys.stderr at handler construction time.
1015 """
1016 def __init__(self, level=NOTSET):
1017 """
1018 Initialize the handler.
1019 """
1020 Handler.__init__(self, level)
1021
1022 @property
1023 def stream(self):
1024 return sys.stderr
1025
1026
1027_defaultLastResort = _StderrHandler(WARNING)
1028lastResort = _defaultLastResort
1029
Guido van Rossum57102f82002-11-13 16:15:58 +00001030#---------------------------------------------------------------------------
1031# Manager classes and functions
1032#---------------------------------------------------------------------------
1033
Benjamin Peterson55549932009-11-25 17:19:56 +00001034class PlaceHolder(object):
Guido van Rossum57102f82002-11-13 16:15:58 +00001035 """
1036 PlaceHolder instances are used in the Manager logger hierarchy to take
Vinay Sajip3f742842004-02-28 16:07:46 +00001037 the place of nodes for which no loggers have been defined. This class is
1038 intended for internal use only and not as part of the public API.
Guido van Rossum57102f82002-11-13 16:15:58 +00001039 """
1040 def __init__(self, alogger):
1041 """
1042 Initialize with the specified logger being a child of this placeholder.
1043 """
Vinay Sajip239322b2005-10-14 09:36:35 +00001044 self.loggerMap = { alogger : None }
Guido van Rossum57102f82002-11-13 16:15:58 +00001045
1046 def append(self, alogger):
1047 """
1048 Add the specified logger as a child of this placeholder.
1049 """
Guido van Rossum93662412006-08-19 16:09:41 +00001050 if alogger not in self.loggerMap:
Vinay Sajip239322b2005-10-14 09:36:35 +00001051 self.loggerMap[alogger] = None
Guido van Rossum57102f82002-11-13 16:15:58 +00001052
1053#
1054# Determine which class to use when instantiating loggers.
1055#
1056_loggerClass = None
1057
1058def setLoggerClass(klass):
1059 """
1060 Set the class to be used when instantiating a logger. The class should
1061 define __init__() such that only a name argument is required, and the
1062 __init__() should call Logger.__init__()
1063 """
1064 if klass != Logger:
Guido van Rossum57102f82002-11-13 16:15:58 +00001065 if not issubclass(klass, Logger):
Collin Winterce36ad82007-08-30 01:19:48 +00001066 raise TypeError("logger not derived from logging.Logger: "
1067 + klass.__name__)
Guido van Rossum57102f82002-11-13 16:15:58 +00001068 global _loggerClass
1069 _loggerClass = klass
1070
Vinay Sajipb9591172004-09-22 12:39:26 +00001071def getLoggerClass():
1072 """
1073 Return the class to be used when instantiating a logger.
1074 """
1075
1076 return _loggerClass
1077
Benjamin Peterson55549932009-11-25 17:19:56 +00001078class Manager(object):
Guido van Rossum57102f82002-11-13 16:15:58 +00001079 """
1080 There is [under normal circumstances] just one Manager instance, which
1081 holds the hierarchy of loggers.
1082 """
Neal Norwitzd1cade02002-11-15 23:31:28 +00001083 def __init__(self, rootnode):
Guido van Rossum57102f82002-11-13 16:15:58 +00001084 """
1085 Initialize the manager with the root node of the logger hierarchy.
1086 """
Neal Norwitzd1cade02002-11-15 23:31:28 +00001087 self.root = rootnode
Guido van Rossum57102f82002-11-13 16:15:58 +00001088 self.disable = 0
Vinay Sajip5a27d402010-12-10 11:42:57 +00001089 self.emittedNoHandlerWarning = False
Guido van Rossum57102f82002-11-13 16:15:58 +00001090 self.loggerDict = {}
Vinay Sajipdb81c4c2010-02-25 23:13:06 +00001091 self.loggerClass = None
Vinay Sajip61561522010-12-03 11:50:38 +00001092 self.logRecordFactory = None
Guido van Rossum57102f82002-11-13 16:15:58 +00001093
1094 def getLogger(self, name):
1095 """
1096 Get a logger with the specified name (channel name), creating it
Vinay Sajipb9591172004-09-22 12:39:26 +00001097 if it doesn't yet exist. This name is a dot-separated hierarchical
1098 name, such as "a", "a.b", "a.b.c" or similar.
Guido van Rossum57102f82002-11-13 16:15:58 +00001099
1100 If a PlaceHolder existed for the specified name [i.e. the logger
1101 didn't exist but a child of it did], replace it with the created
1102 logger and fix up the parent/child references which pointed to the
1103 placeholder to now point to the logger.
1104 """
1105 rv = None
Vinay Sajip61b787e2011-11-07 08:53:03 +00001106 if not isinstance(name, str):
Vinay Sajip3bd56382011-11-07 10:15:08 +00001107 raise TypeError('A logger name must be a string')
Guido van Rossum57102f82002-11-13 16:15:58 +00001108 _acquireLock()
1109 try:
Guido van Rossum93662412006-08-19 16:09:41 +00001110 if name in self.loggerDict:
Guido van Rossum57102f82002-11-13 16:15:58 +00001111 rv = self.loggerDict[name]
1112 if isinstance(rv, PlaceHolder):
1113 ph = rv
Vinay Sajipdb81c4c2010-02-25 23:13:06 +00001114 rv = (self.loggerClass or _loggerClass)(name)
Guido van Rossum57102f82002-11-13 16:15:58 +00001115 rv.manager = self
1116 self.loggerDict[name] = rv
1117 self._fixupChildren(ph, rv)
1118 self._fixupParents(rv)
1119 else:
Vinay Sajipdb81c4c2010-02-25 23:13:06 +00001120 rv = (self.loggerClass or _loggerClass)(name)
Guido van Rossum57102f82002-11-13 16:15:58 +00001121 rv.manager = self
1122 self.loggerDict[name] = rv
1123 self._fixupParents(rv)
1124 finally:
1125 _releaseLock()
1126 return rv
1127
Vinay Sajipdb81c4c2010-02-25 23:13:06 +00001128 def setLoggerClass(self, klass):
1129 """
1130 Set the class to be used when instantiating a logger with this Manager.
1131 """
1132 if klass != Logger:
1133 if not issubclass(klass, Logger):
1134 raise TypeError("logger not derived from logging.Logger: "
1135 + klass.__name__)
1136 self.loggerClass = klass
1137
Vinay Sajip61561522010-12-03 11:50:38 +00001138 def setLogRecordFactory(self, factory):
Vinay Sajip6fac8172010-10-19 20:44:14 +00001139 """
Vinay Sajipfad058f2010-12-03 13:01:11 +00001140 Set the factory to be used when instantiating a log record with this
Vinay Sajip6fac8172010-10-19 20:44:14 +00001141 Manager.
1142 """
Vinay Sajip61561522010-12-03 11:50:38 +00001143 self.logRecordFactory = factory
Vinay Sajip6fac8172010-10-19 20:44:14 +00001144
Guido van Rossum57102f82002-11-13 16:15:58 +00001145 def _fixupParents(self, alogger):
1146 """
1147 Ensure that there are either loggers or placeholders all the way
1148 from the specified logger to the root of the logger hierarchy.
1149 """
1150 name = alogger.name
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001151 i = name.rfind(".")
Guido van Rossum57102f82002-11-13 16:15:58 +00001152 rv = None
1153 while (i > 0) and not rv:
1154 substr = name[:i]
Guido van Rossum93662412006-08-19 16:09:41 +00001155 if substr not in self.loggerDict:
Guido van Rossum57102f82002-11-13 16:15:58 +00001156 self.loggerDict[substr] = PlaceHolder(alogger)
1157 else:
1158 obj = self.loggerDict[substr]
1159 if isinstance(obj, Logger):
1160 rv = obj
1161 else:
1162 assert isinstance(obj, PlaceHolder)
1163 obj.append(alogger)
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001164 i = name.rfind(".", 0, i - 1)
Guido van Rossum57102f82002-11-13 16:15:58 +00001165 if not rv:
1166 rv = self.root
1167 alogger.parent = rv
1168
1169 def _fixupChildren(self, ph, alogger):
1170 """
1171 Ensure that children of the placeholder ph are connected to the
1172 specified logger.
1173 """
Thomas Wouters89f507f2006-12-13 04:49:30 +00001174 name = alogger.name
1175 namelen = len(name)
Vinay Sajip239322b2005-10-14 09:36:35 +00001176 for c in ph.loggerMap.keys():
Thomas Wouters89f507f2006-12-13 04:49:30 +00001177 #The if means ... if not c.parent.name.startswith(nm)
1178 if c.parent.name[:namelen] != name:
Guido van Rossum57102f82002-11-13 16:15:58 +00001179 alogger.parent = c.parent
1180 c.parent = alogger
1181
1182#---------------------------------------------------------------------------
1183# Logger classes and functions
1184#---------------------------------------------------------------------------
1185
1186class Logger(Filterer):
1187 """
1188 Instances of the Logger class represent a single logging channel. A
1189 "logging channel" indicates an area of an application. Exactly how an
1190 "area" is defined is up to the application developer. Since an
1191 application can have any number of areas, logging channels are identified
1192 by a unique string. Application areas can be nested (e.g. an area
1193 of "input processing" might include sub-areas "read CSV files", "read
1194 XLS files" and "read Gnumeric files"). To cater for this natural nesting,
1195 channel names are organized into a namespace hierarchy where levels are
1196 separated by periods, much like the Java or Python package namespace. So
1197 in the instance given above, channel names might be "input" for the upper
1198 level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels.
1199 There is no arbitrary limit to the depth of nesting.
1200 """
1201 def __init__(self, name, level=NOTSET):
1202 """
1203 Initialize the logger with a name and an optional level.
1204 """
1205 Filterer.__init__(self)
1206 self.name = name
Vinay Sajipd4fabf42009-07-13 11:28:25 +00001207 self.level = _checkLevel(level)
Guido van Rossum57102f82002-11-13 16:15:58 +00001208 self.parent = None
Vinay Sajip312cc0d2011-04-30 21:51:51 +01001209 self.propagate = True
Guido van Rossum57102f82002-11-13 16:15:58 +00001210 self.handlers = []
Vinay Sajip312cc0d2011-04-30 21:51:51 +01001211 self.disabled = False
Guido van Rossum57102f82002-11-13 16:15:58 +00001212
1213 def setLevel(self, level):
1214 """
Gregory P. Smithe85488c2011-12-17 12:36:34 -08001215 Set the logging level of this logger. level must be an int or a str.
Guido van Rossum57102f82002-11-13 16:15:58 +00001216 """
Vinay Sajipd4fabf42009-07-13 11:28:25 +00001217 self.level = _checkLevel(level)
Guido van Rossum57102f82002-11-13 16:15:58 +00001218
Guido van Rossum57102f82002-11-13 16:15:58 +00001219 def debug(self, msg, *args, **kwargs):
1220 """
1221 Log 'msg % args' with severity 'DEBUG'.
1222
1223 To pass exception information, use the keyword argument exc_info with
1224 a true value, e.g.
1225
1226 logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
1227 """
Guido van Rossum04110fb2007-08-24 16:32:05 +00001228 if self.isEnabledFor(DEBUG):
Neal Norwitzd9108552006-03-17 08:00:19 +00001229 self._log(DEBUG, msg, args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001230
1231 def info(self, msg, *args, **kwargs):
1232 """
1233 Log 'msg % args' with severity 'INFO'.
1234
1235 To pass exception information, use the keyword argument exc_info with
1236 a true value, e.g.
1237
1238 logger.info("Houston, we have a %s", "interesting problem", exc_info=1)
1239 """
Guido van Rossum04110fb2007-08-24 16:32:05 +00001240 if self.isEnabledFor(INFO):
Neal Norwitzd9108552006-03-17 08:00:19 +00001241 self._log(INFO, msg, args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001242
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001243 def warning(self, msg, *args, **kwargs):
Guido van Rossum57102f82002-11-13 16:15:58 +00001244 """
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001245 Log 'msg % args' with severity 'WARNING'.
Guido van Rossum57102f82002-11-13 16:15:58 +00001246
1247 To pass exception information, use the keyword argument exc_info with
1248 a true value, e.g.
1249
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001250 logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)
Guido van Rossum57102f82002-11-13 16:15:58 +00001251 """
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001252 if self.isEnabledFor(WARNING):
Neal Norwitzd9108552006-03-17 08:00:19 +00001253 self._log(WARNING, msg, args, **kwargs)
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001254
Vinay Sajip04d5bc02011-10-21 07:33:42 +01001255 def warn(self, msg, *args, **kwargs):
1256 warnings.warn("The 'warn' method is deprecated, "
Vinay Sajip0a889532011-10-22 13:34:48 +01001257 "use 'warning' instead", DeprecationWarning, 2)
Vinay Sajip04d5bc02011-10-21 07:33:42 +01001258 self.warning(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001259
1260 def error(self, msg, *args, **kwargs):
1261 """
1262 Log 'msg % args' with severity 'ERROR'.
1263
1264 To pass exception information, use the keyword argument exc_info with
1265 a true value, e.g.
1266
1267 logger.error("Houston, we have a %s", "major problem", exc_info=1)
1268 """
Guido van Rossum57102f82002-11-13 16:15:58 +00001269 if self.isEnabledFor(ERROR):
Neal Norwitzd9108552006-03-17 08:00:19 +00001270 self._log(ERROR, msg, args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001271
Vinay Sajip8593ae62010-11-14 21:33:04 +00001272 def exception(self, msg, *args, **kwargs):
Guido van Rossum57102f82002-11-13 16:15:58 +00001273 """
1274 Convenience method for logging an ERROR with exception information.
1275 """
Vinay Sajip8593ae62010-11-14 21:33:04 +00001276 kwargs['exc_info'] = True
1277 self.error(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001278
1279 def critical(self, msg, *args, **kwargs):
1280 """
1281 Log 'msg % args' with severity 'CRITICAL'.
1282
1283 To pass exception information, use the keyword argument exc_info with
1284 a true value, e.g.
1285
1286 logger.critical("Houston, we have a %s", "major disaster", exc_info=1)
1287 """
Guido van Rossum04110fb2007-08-24 16:32:05 +00001288 if self.isEnabledFor(CRITICAL):
Neal Norwitzd9108552006-03-17 08:00:19 +00001289 self._log(CRITICAL, msg, args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001290
1291 fatal = critical
1292
1293 def log(self, level, msg, *args, **kwargs):
1294 """
Vinay Sajipeb477d02004-08-04 08:38:08 +00001295 Log 'msg % args' with the integer severity 'level'.
Guido van Rossum57102f82002-11-13 16:15:58 +00001296
1297 To pass exception information, use the keyword argument exc_info with
1298 a true value, e.g.
1299
1300 logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
1301 """
Guido van Rossum13257902007-06-07 23:15:56 +00001302 if not isinstance(level, int):
Vinay Sajip779e0c92004-07-03 11:47:26 +00001303 if raiseExceptions:
Collin Winterce36ad82007-08-30 01:19:48 +00001304 raise TypeError("level must be an integer")
Vinay Sajip779e0c92004-07-03 11:47:26 +00001305 else:
1306 return
Guido van Rossum57102f82002-11-13 16:15:58 +00001307 if self.isEnabledFor(level):
Neal Norwitzd9108552006-03-17 08:00:19 +00001308 self._log(level, msg, args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001309
Vinay Sajip8593ae62010-11-14 21:33:04 +00001310 def findCaller(self, stack_info=False):
Guido van Rossum57102f82002-11-13 16:15:58 +00001311 """
1312 Find the stack frame of the caller so that we can note the source
Vinay Sajip829dc512005-02-18 11:53:32 +00001313 file name, line number and function name.
Guido van Rossum57102f82002-11-13 16:15:58 +00001314 """
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001315 f = currentframe()
1316 #On some versions of IronPython, currentframe() returns None if
1317 #IronPython isn't run with -X:Frames.
1318 if f is not None:
1319 f = f.f_back
Vinay Sajip8593ae62010-11-14 21:33:04 +00001320 rv = "(unknown file)", 0, "(unknown function)", None
Thomas Woutersa9773292006-04-21 09:43:23 +00001321 while hasattr(f, "f_code"):
Jeremy Hylton250684d2003-01-23 18:29:29 +00001322 co = f.f_code
1323 filename = os.path.normcase(co.co_filename)
1324 if filename == _srcfile:
1325 f = f.f_back
1326 continue
Vinay Sajip8593ae62010-11-14 21:33:04 +00001327 sinfo = None
1328 if stack_info:
1329 sio = io.StringIO()
1330 sio.write('Stack (most recent call last):\n')
1331 traceback.print_stack(f, file=sio)
1332 sinfo = sio.getvalue()
1333 if sinfo[-1] == '\n':
1334 sinfo = sinfo[:-1]
1335 sio.close()
1336 rv = (co.co_filename, f.f_lineno, co.co_name, sinfo)
Thomas Woutersa9773292006-04-21 09:43:23 +00001337 break
1338 return rv
Guido van Rossum57102f82002-11-13 16:15:58 +00001339
Vinay Sajip8593ae62010-11-14 21:33:04 +00001340 def makeRecord(self, name, level, fn, lno, msg, args, exc_info,
1341 func=None, extra=None, sinfo=None):
Guido van Rossum57102f82002-11-13 16:15:58 +00001342 """
1343 A factory method which can be overridden in subclasses to create
1344 specialized LogRecords.
1345 """
Vinay Sajip61561522010-12-03 11:50:38 +00001346 rv = _logRecordFactory(name, level, fn, lno, msg, args, exc_info, func,
Vinay Sajip8593ae62010-11-14 21:33:04 +00001347 sinfo)
Christian Heimes04c420f2008-01-18 18:40:46 +00001348 if extra is not None:
Vinay Sajip260ce432006-02-09 08:34:14 +00001349 for key in extra:
1350 if (key in ["message", "asctime"]) or (key in rv.__dict__):
1351 raise KeyError("Attempt to overwrite %r in LogRecord" % key)
1352 rv.__dict__[key] = extra[key]
1353 return rv
Guido van Rossum57102f82002-11-13 16:15:58 +00001354
Vinay Sajip8593ae62010-11-14 21:33:04 +00001355 def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False):
Guido van Rossum57102f82002-11-13 16:15:58 +00001356 """
1357 Low-level logging routine which creates a LogRecord and then calls
1358 all the handlers of this logger to handle the record.
1359 """
Vinay Sajip8593ae62010-11-14 21:33:04 +00001360 sinfo = None
Jeremy Hylton250684d2003-01-23 18:29:29 +00001361 if _srcfile:
Andrew Svetlov737fb892012-12-18 21:14:22 +02001362 #IronPython doesn't track Python frames, so findCaller raises an
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001363 #exception on some versions of IronPython. We trap it here so that
1364 #IronPython can use logging.
Vinay Sajipb672b6d2009-02-19 12:36:11 +00001365 try:
Vinay Sajip8593ae62010-11-14 21:33:04 +00001366 fn, lno, func, sinfo = self.findCaller(stack_info)
Vinay Sajip26fe4b72011-04-26 18:43:05 +01001367 except ValueError: # pragma: no cover
Vinay Sajipb672b6d2009-02-19 12:36:11 +00001368 fn, lno, func = "(unknown file)", 0, "(unknown function)"
Vinay Sajip26fe4b72011-04-26 18:43:05 +01001369 else: # pragma: no cover
Vinay Sajip829dc512005-02-18 11:53:32 +00001370 fn, lno, func = "(unknown file)", 0, "(unknown function)"
Guido van Rossum57102f82002-11-13 16:15:58 +00001371 if exc_info:
Guido van Rossum13257902007-06-07 23:15:56 +00001372 if not isinstance(exc_info, tuple):
Vinay Sajiped6bb142004-02-20 13:18:36 +00001373 exc_info = sys.exc_info()
Vinay Sajip8593ae62010-11-14 21:33:04 +00001374 record = self.makeRecord(self.name, level, fn, lno, msg, args,
1375 exc_info, func, extra, sinfo)
Guido van Rossum57102f82002-11-13 16:15:58 +00001376 self.handle(record)
1377
1378 def handle(self, record):
1379 """
1380 Call the handlers for the specified record.
1381
1382 This method is used for unpickled records received from a socket, as
1383 well as those created locally. Logger-level filtering is applied.
1384 """
1385 if (not self.disabled) and self.filter(record):
1386 self.callHandlers(record)
1387
1388 def addHandler(self, hdlr):
1389 """
1390 Add the specified handler to this logger.
1391 """
Vinay Sajip32fb6a82010-09-25 17:42:36 +00001392 _acquireLock()
1393 try:
1394 if not (hdlr in self.handlers):
1395 self.handlers.append(hdlr)
1396 finally:
1397 _releaseLock()
Guido van Rossum57102f82002-11-13 16:15:58 +00001398
1399 def removeHandler(self, hdlr):
1400 """
1401 Remove the specified handler from this logger.
1402 """
Vinay Sajip32fb6a82010-09-25 17:42:36 +00001403 _acquireLock()
1404 try:
1405 if hdlr in self.handlers:
Vinay Sajip116f16e2005-09-16 10:33:40 +00001406 self.handlers.remove(hdlr)
Vinay Sajip32fb6a82010-09-25 17:42:36 +00001407 finally:
1408 _releaseLock()
Guido van Rossum57102f82002-11-13 16:15:58 +00001409
Vinay Sajipb4a08092010-09-20 09:55:00 +00001410 def hasHandlers(self):
1411 """
1412 See if this logger has any handlers configured.
1413
1414 Loop through all handlers for this logger and its parents in the
1415 logger hierarchy. Return True if a handler was found, else False.
1416 Stop searching up the hierarchy whenever a logger with the "propagate"
1417 attribute set to zero is found - that will be the last logger which
1418 is checked for the existence of handlers.
1419 """
1420 c = self
1421 rv = False
1422 while c:
1423 if c.handlers:
1424 rv = True
1425 break
1426 if not c.propagate:
1427 break
1428 else:
1429 c = c.parent
1430 return rv
1431
Guido van Rossum57102f82002-11-13 16:15:58 +00001432 def callHandlers(self, record):
1433 """
1434 Pass a record to all relevant handlers.
1435
1436 Loop through all handlers for this logger and its parents in the
1437 logger hierarchy. If no handler was found, output a one-off error
1438 message to sys.stderr. Stop searching up the hierarchy whenever a
1439 logger with the "propagate" attribute set to zero is found - that
1440 will be the last logger whose handlers are called.
1441 """
1442 c = self
1443 found = 0
1444 while c:
1445 for hdlr in c.handlers:
1446 found = found + 1
1447 if record.levelno >= hdlr.level:
1448 hdlr.handle(record)
1449 if not c.propagate:
1450 c = None #break out
1451 else:
1452 c = c.parent
Vinay Sajip5a27d402010-12-10 11:42:57 +00001453 if (found == 0):
1454 if lastResort:
Vinay Sajip45dedaa2011-07-25 19:53:28 +01001455 if record.levelno >= lastResort.level:
1456 lastResort.handle(record)
Vinay Sajip5a27d402010-12-10 11:42:57 +00001457 elif raiseExceptions and not self.manager.emittedNoHandlerWarning:
1458 sys.stderr.write("No handlers could be found for logger"
1459 " \"%s\"\n" % self.name)
1460 self.manager.emittedNoHandlerWarning = True
Guido van Rossum57102f82002-11-13 16:15:58 +00001461
1462 def getEffectiveLevel(self):
1463 """
1464 Get the effective level for this logger.
1465
1466 Loop through this logger and its parents in the logger hierarchy,
1467 looking for a non-zero logging level. Return the first one found.
1468 """
1469 logger = self
1470 while logger:
1471 if logger.level:
1472 return logger.level
1473 logger = logger.parent
1474 return NOTSET
1475
1476 def isEnabledFor(self, level):
1477 """
1478 Is this logger enabled for level 'level'?
1479 """
1480 if self.manager.disable >= level:
Vinay Sajip26fe4b72011-04-26 18:43:05 +01001481 return False
Guido van Rossum57102f82002-11-13 16:15:58 +00001482 return level >= self.getEffectiveLevel()
1483
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001484 def getChild(self, suffix):
1485 """
1486 Get a logger which is a descendant to this one.
1487
1488 This is a convenience method, such that
1489
1490 logging.getLogger('abc').getChild('def.ghi')
1491
1492 is the same as
1493
1494 logging.getLogger('abc.def.ghi')
1495
1496 It's useful, for example, when the parent logger is named using
1497 __name__ rather than a literal string.
1498 """
1499 if self.root is not self:
1500 suffix = '.'.join((self.name, suffix))
1501 return self.manager.getLogger(suffix)
1502
Guido van Rossum57102f82002-11-13 16:15:58 +00001503class RootLogger(Logger):
1504 """
1505 A root logger is not that different to any other logger, except that
1506 it must have a logging level and there is only one instance of it in
1507 the hierarchy.
1508 """
1509 def __init__(self, level):
1510 """
1511 Initialize the logger with the name "root".
1512 """
1513 Logger.__init__(self, "root", level)
1514
1515_loggerClass = Logger
1516
Benjamin Peterson55549932009-11-25 17:19:56 +00001517class LoggerAdapter(object):
Christian Heimes04c420f2008-01-18 18:40:46 +00001518 """
1519 An adapter for loggers which makes it easier to specify contextual
1520 information in logging output.
1521 """
1522
1523 def __init__(self, logger, extra):
1524 """
1525 Initialize the adapter with a logger and a dict-like object which
1526 provides contextual information. This constructor signature allows
1527 easy stacking of LoggerAdapters, if so desired.
1528
1529 You can effectively pass keyword arguments as shown in the
1530 following example:
1531
1532 adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2"))
1533 """
1534 self.logger = logger
1535 self.extra = extra
1536
1537 def process(self, msg, kwargs):
1538 """
1539 Process the logging message and keyword arguments passed in to
1540 a logging call to insert contextual information. You can either
1541 manipulate the message itself, the keyword args or both. Return
1542 the message and kwargs modified (or not) to suit your needs.
1543
1544 Normally, you'll only need to override this one method in a
1545 LoggerAdapter subclass for your specific needs.
1546 """
1547 kwargs["extra"] = self.extra
1548 return msg, kwargs
1549
Vinay Sajip212b5902010-09-21 11:31:32 +00001550 #
1551 # Boilerplate convenience methods
1552 #
Christian Heimes04c420f2008-01-18 18:40:46 +00001553 def debug(self, msg, *args, **kwargs):
1554 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001555 Delegate a debug call to the underlying logger.
Christian Heimes04c420f2008-01-18 18:40:46 +00001556 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001557 self.log(DEBUG, msg, *args, **kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00001558
1559 def info(self, msg, *args, **kwargs):
1560 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001561 Delegate an info call to the underlying logger.
Christian Heimes04c420f2008-01-18 18:40:46 +00001562 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001563 self.log(INFO, msg, *args, **kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00001564
1565 def warning(self, msg, *args, **kwargs):
1566 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001567 Delegate a warning call to the underlying logger.
Christian Heimes04c420f2008-01-18 18:40:46 +00001568 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001569 self.log(WARNING, msg, *args, **kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00001570
Vinay Sajip04d5bc02011-10-21 07:33:42 +01001571 def warn(self, msg, *args, **kwargs):
1572 warnings.warn("The 'warn' method is deprecated, "
Vinay Sajip0a889532011-10-22 13:34:48 +01001573 "use 'warning' instead", DeprecationWarning, 2)
Vinay Sajip04d5bc02011-10-21 07:33:42 +01001574 self.warning(msg, *args, **kwargs)
Vinay Sajipc84f0162010-09-21 11:25:39 +00001575
Christian Heimes04c420f2008-01-18 18:40:46 +00001576 def error(self, msg, *args, **kwargs):
1577 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001578 Delegate an error call to the underlying logger.
Christian Heimes04c420f2008-01-18 18:40:46 +00001579 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001580 self.log(ERROR, msg, *args, **kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00001581
1582 def exception(self, msg, *args, **kwargs):
1583 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001584 Delegate an exception call to the underlying logger.
Christian Heimes04c420f2008-01-18 18:40:46 +00001585 """
Vinay Sajip312cc0d2011-04-30 21:51:51 +01001586 kwargs["exc_info"] = True
Vinay Sajip212b5902010-09-21 11:31:32 +00001587 self.log(ERROR, msg, *args, **kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00001588
1589 def critical(self, msg, *args, **kwargs):
1590 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001591 Delegate a critical call to the underlying logger.
Christian Heimes04c420f2008-01-18 18:40:46 +00001592 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001593 self.log(CRITICAL, msg, *args, **kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00001594
1595 def log(self, level, msg, *args, **kwargs):
1596 """
1597 Delegate a log call to the underlying logger, after adding
1598 contextual information from this adapter instance.
1599 """
Vinay Sajip212b5902010-09-21 11:31:32 +00001600 if self.isEnabledFor(level):
1601 msg, kwargs = self.process(msg, kwargs)
1602 self.logger._log(level, msg, args, **kwargs)
1603
1604 def isEnabledFor(self, level):
1605 """
1606 Is this logger enabled for level 'level'?
1607 """
1608 if self.logger.manager.disable >= level:
1609 return False
1610 return level >= self.getEffectiveLevel()
Christian Heimes04c420f2008-01-18 18:40:46 +00001611
Vinay Sajipc84f0162010-09-21 11:25:39 +00001612 def setLevel(self, level):
1613 """
1614 Set the specified level on the underlying logger.
1615 """
1616 self.logger.setLevel(level)
1617
Vinay Sajipc84f0162010-09-21 11:25:39 +00001618 def getEffectiveLevel(self):
1619 """
1620 Get the effective level for the underlying logger.
1621 """
1622 return self.logger.getEffectiveLevel()
1623
Vinay Sajip61c3f0d2010-09-20 10:13:13 +00001624 def hasHandlers(self):
1625 """
1626 See if the underlying logger has any handlers.
1627 """
1628 return self.logger.hasHandlers()
1629
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001630root = RootLogger(WARNING)
Guido van Rossum57102f82002-11-13 16:15:58 +00001631Logger.root = root
1632Logger.manager = Manager(Logger.root)
1633
1634#---------------------------------------------------------------------------
1635# Configuration classes and functions
1636#---------------------------------------------------------------------------
1637
1638BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s"
1639
Vinay Sajip779e0c92004-07-03 11:47:26 +00001640def basicConfig(**kwargs):
Guido van Rossum57102f82002-11-13 16:15:58 +00001641 """
Vinay Sajip779e0c92004-07-03 11:47:26 +00001642 Do basic configuration for the logging system.
1643
1644 This function does nothing if the root logger already has handlers
1645 configured. It is a convenience method intended for use by simple scripts
1646 to do one-shot configuration of the logging package.
1647
1648 The default behaviour is to create a StreamHandler which writes to
1649 sys.stderr, set a formatter using the BASIC_FORMAT format string, and
1650 add the handler to the root logger.
1651
1652 A number of optional keyword arguments may be specified, which can alter
1653 the default behaviour.
1654
1655 filename Specifies that a FileHandler be created, using the specified
1656 filename, rather than a StreamHandler.
1657 filemode Specifies the mode to open the file, if filename is specified
Vinay Sajipb89e7c92005-03-13 09:54:31 +00001658 (if filemode is unspecified, it defaults to 'a').
Vinay Sajip779e0c92004-07-03 11:47:26 +00001659 format Use the specified format string for the handler.
1660 datefmt Use the specified date/time format.
Vinay Sajipc5b27302010-10-31 14:59:16 +00001661 style If a format string is specified, use this to specify the
1662 type of format string (possible values '%', '{', '$', for
1663 %-formatting, :meth:`str.format` and :class:`string.Template`
1664 - defaults to '%').
Vinay Sajip779e0c92004-07-03 11:47:26 +00001665 level Set the root logger level to the specified level.
1666 stream Use the specified stream to initialize the StreamHandler. Note
1667 that this argument is incompatible with 'filename' - if both
1668 are present, 'stream' is ignored.
Vinay Sajip4a0a31d2011-04-11 08:42:07 +01001669 handlers If specified, this should be an iterable of already created
1670 handlers, which will be added to the root handler. Any handler
1671 in the list which does not have a formatter assigned will be
1672 assigned the formatter created in this function.
Vinay Sajip779e0c92004-07-03 11:47:26 +00001673
1674 Note that you could specify a stream created using open(filename, mode)
1675 rather than passing the filename and mode in. However, it should be
1676 remembered that StreamHandler does not close its stream (since it may be
1677 using sys.stdout or sys.stderr), whereas FileHandler closes its stream
1678 when the handler is closed.
Vinay Sajipc5b27302010-10-31 14:59:16 +00001679
Vinay Sajip4a0a31d2011-04-11 08:42:07 +01001680 .. versionchanged:: 3.2
Vinay Sajipc5b27302010-10-31 14:59:16 +00001681 Added the ``style`` parameter.
Vinay Sajipa3359ee2011-04-11 08:43:52 +01001682
Vinay Sajip4a0a31d2011-04-11 08:42:07 +01001683 .. versionchanged:: 3.3
1684 Added the ``handlers`` parameter. A ``ValueError`` is now thrown for
1685 incompatible arguments (e.g. ``handlers`` specified together with
1686 ``filename``/``filemode``, or ``filename``/``filemode`` specified
1687 together with ``stream``, or ``handlers`` specified together with
1688 ``stream``.
Guido van Rossum57102f82002-11-13 16:15:58 +00001689 """
Vinay Sajip2314fc72010-09-10 08:25:13 +00001690 # Add thread safety in case someone mistakenly calls
1691 # basicConfig() from multiple threads
1692 _acquireLock()
1693 try:
1694 if len(root.handlers) == 0:
Vinay Sajip4a0a31d2011-04-11 08:42:07 +01001695 handlers = kwargs.get("handlers")
1696 if handlers is None:
1697 if "stream" in kwargs and "filename" in kwargs:
1698 raise ValueError("'stream' and 'filename' should not be "
1699 "specified together")
Vinay Sajip2314fc72010-09-10 08:25:13 +00001700 else:
Vinay Sajip4a0a31d2011-04-11 08:42:07 +01001701 if "stream" in kwargs or "filename" in kwargs:
1702 raise ValueError("'stream' or 'filename' should not be "
1703 "specified together with 'handlers'")
1704 if handlers is None:
1705 filename = kwargs.get("filename")
1706 if filename:
1707 mode = kwargs.get("filemode", 'a')
1708 h = FileHandler(filename, mode)
1709 else:
1710 stream = kwargs.get("stream")
1711 h = StreamHandler(stream)
1712 handlers = [h]
Vinay Sajip2314fc72010-09-10 08:25:13 +00001713 fs = kwargs.get("format", BASIC_FORMAT)
1714 dfs = kwargs.get("datefmt", None)
Vinay Sajipc5b27302010-10-31 14:59:16 +00001715 style = kwargs.get("style", '%')
1716 fmt = Formatter(fs, dfs, style)
Vinay Sajip4a0a31d2011-04-11 08:42:07 +01001717 for h in handlers:
1718 if h.formatter is None:
1719 h.setFormatter(fmt)
1720 root.addHandler(h)
Vinay Sajip2314fc72010-09-10 08:25:13 +00001721 level = kwargs.get("level")
1722 if level is not None:
1723 root.setLevel(level)
1724 finally:
1725 _releaseLock()
Guido van Rossum57102f82002-11-13 16:15:58 +00001726
1727#---------------------------------------------------------------------------
1728# Utility functions at module level.
1729# Basically delegate everything to the root logger.
1730#---------------------------------------------------------------------------
1731
1732def getLogger(name=None):
1733 """
1734 Return a logger with the specified name, creating it if necessary.
1735
1736 If no name is specified, return the root logger.
1737 """
1738 if name:
1739 return Logger.manager.getLogger(name)
1740 else:
1741 return root
1742
Guido van Rossum57102f82002-11-13 16:15:58 +00001743def critical(msg, *args, **kwargs):
1744 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001745 Log a message with severity 'CRITICAL' on the root logger. If the logger
1746 has no handlers, call basicConfig() to add a console handler with a
1747 pre-defined 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.critical(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001752
1753fatal = critical
1754
1755def error(msg, *args, **kwargs):
1756 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001757 Log a message with severity 'ERROR' on the root logger. If the logger has
1758 no handlers, call basicConfig() to add a console handler with a pre-defined
1759 format.
Guido van Rossum57102f82002-11-13 16:15:58 +00001760 """
1761 if len(root.handlers) == 0:
1762 basicConfig()
Neal Norwitzd9108552006-03-17 08:00:19 +00001763 root.error(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001764
Vinay Sajip8593ae62010-11-14 21:33:04 +00001765def exception(msg, *args, **kwargs):
Guido van Rossum57102f82002-11-13 16:15:58 +00001766 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001767 Log a message with severity 'ERROR' on the root logger, with exception
1768 information. If the logger has no handlers, basicConfig() is called to add
1769 a console handler with a pre-defined format.
Guido van Rossum57102f82002-11-13 16:15:58 +00001770 """
Vinay Sajip8593ae62010-11-14 21:33:04 +00001771 kwargs['exc_info'] = True
1772 error(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001773
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001774def warning(msg, *args, **kwargs):
Guido van Rossum57102f82002-11-13 16:15:58 +00001775 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001776 Log a message with severity 'WARNING' on the root logger. If the logger has
1777 no handlers, call basicConfig() to add a console handler with a pre-defined
1778 format.
Guido van Rossum57102f82002-11-13 16:15:58 +00001779 """
1780 if len(root.handlers) == 0:
1781 basicConfig()
Neal Norwitzd9108552006-03-17 08:00:19 +00001782 root.warning(msg, *args, **kwargs)
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001783
Vinay Sajip04d5bc02011-10-21 07:33:42 +01001784def warn(msg, *args, **kwargs):
1785 warnings.warn("The 'warn' function is deprecated, "
Vinay Sajip0a889532011-10-22 13:34:48 +01001786 "use 'warning' instead", DeprecationWarning, 2)
Vinay Sajip04d5bc02011-10-21 07:33:42 +01001787 warning(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001788
1789def info(msg, *args, **kwargs):
1790 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001791 Log a message with severity 'INFO' on the root logger. If the logger has
1792 no handlers, call basicConfig() to add a console handler with a pre-defined
1793 format.
Guido van Rossum57102f82002-11-13 16:15:58 +00001794 """
1795 if len(root.handlers) == 0:
1796 basicConfig()
Neal Norwitzd9108552006-03-17 08:00:19 +00001797 root.info(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001798
1799def debug(msg, *args, **kwargs):
1800 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001801 Log a message with severity 'DEBUG' on the root logger. If the logger has
1802 no handlers, call basicConfig() to add a console handler with a pre-defined
1803 format.
Guido van Rossum57102f82002-11-13 16:15:58 +00001804 """
1805 if len(root.handlers) == 0:
1806 basicConfig()
Neal Norwitzd9108552006-03-17 08:00:19 +00001807 root.debug(msg, *args, **kwargs)
Guido van Rossum57102f82002-11-13 16:15:58 +00001808
Vinay Sajipb2635b22004-09-24 11:45:52 +00001809def log(level, msg, *args, **kwargs):
1810 """
Vinay Sajip5a27d402010-12-10 11:42:57 +00001811 Log 'msg % args' with the integer severity 'level' on the root logger. If
1812 the logger has no handlers, call basicConfig() to add a console handler
1813 with a pre-defined format.
Vinay Sajipb2635b22004-09-24 11:45:52 +00001814 """
1815 if len(root.handlers) == 0:
1816 basicConfig()
Neal Norwitzd9108552006-03-17 08:00:19 +00001817 root.log(level, msg, *args, **kwargs)
Vinay Sajipb2635b22004-09-24 11:45:52 +00001818
Guido van Rossum57102f82002-11-13 16:15:58 +00001819def disable(level):
1820 """
Benjamin Peterson886af962010-03-21 23:13:07 +00001821 Disable all logging calls of severity 'level' and below.
Guido van Rossum57102f82002-11-13 16:15:58 +00001822 """
1823 root.manager.disable = level
1824
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001825def shutdown(handlerList=_handlerList):
Guido van Rossum57102f82002-11-13 16:15:58 +00001826 """
1827 Perform any cleanup actions in the logging system (e.g. flushing
1828 buffers).
1829
1830 Should be called at application exit.
1831 """
Benjamin Peterson55549932009-11-25 17:19:56 +00001832 for wr in reversed(handlerList[:]):
Vinay Sajipe12f7152004-07-29 09:19:30 +00001833 #errors might occur, for example, if files are locked
Vinay Sajip260ce432006-02-09 08:34:14 +00001834 #we just ignore them if raiseExceptions is not set
Vinay Sajipe12f7152004-07-29 09:19:30 +00001835 try:
Benjamin Peterson55549932009-11-25 17:19:56 +00001836 h = wr()
Vinay Sajipde6e9d62010-08-23 17:50:30 +00001837 if h:
1838 try:
Vinay Sajipd9512e92011-03-08 22:53:21 +00001839 h.acquire()
Vinay Sajipde6e9d62010-08-23 17:50:30 +00001840 h.flush()
1841 h.close()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001842 except (OSError, ValueError):
Vinay Sajipde6e9d62010-08-23 17:50:30 +00001843 # Ignore errors which might be caused
1844 # because handlers have been closed but
1845 # references to them are still around at
1846 # application exit.
1847 pass
Vinay Sajipd9512e92011-03-08 22:53:21 +00001848 finally:
1849 h.release()
Vinay Sajip8cf4eb12012-10-09 08:06:13 +01001850 except: # ignore everything, as we're shutting down
Vinay Sajip260ce432006-02-09 08:34:14 +00001851 if raiseExceptions:
1852 raise
1853 #else, swallow
Vinay Sajiped6bb142004-02-20 13:18:36 +00001854
1855#Let's try and shutdown automatically on application exit...
Georg Brandl01e4d572010-02-06 22:27:51 +00001856import atexit
1857atexit.register(shutdown)
Georg Brandlf9734072008-12-07 15:30:06 +00001858
1859# Null handler
1860
1861class NullHandler(Handler):
1862 """
1863 This handler does nothing. It's intended to be used to avoid the
1864 "No handlers could be found for logger XXX" one-off warning. This is
1865 important for library code, which may contain code to log events. If a user
1866 of the library does not configure logging, the one-off warning might be
1867 produced; to avoid this, the library developer simply needs to instantiate
1868 a NullHandler and add it to the top-level logger of the library module or
1869 package.
1870 """
Vinay Sajip4fbe4b32010-09-26 11:04:10 +00001871 def handle(self, record):
Vinay Sajipe6c1eb92011-03-29 17:20:34 +01001872 """Stub."""
Vinay Sajip4fbe4b32010-09-26 11:04:10 +00001873
Georg Brandlf9734072008-12-07 15:30:06 +00001874 def emit(self, record):
Vinay Sajipe6c1eb92011-03-29 17:20:34 +01001875 """Stub."""
Georg Brandlf9734072008-12-07 15:30:06 +00001876
Vinay Sajip4fbe4b32010-09-26 11:04:10 +00001877 def createLock(self):
1878 self.lock = None
1879
Georg Brandlf9734072008-12-07 15:30:06 +00001880# Warnings integration
1881
1882_warnings_showwarning = None
1883
1884def _showwarning(message, category, filename, lineno, file=None, line=None):
1885 """
1886 Implementation of showwarnings which redirects to logging, which will first
1887 check to see if the file parameter is None. If a file is specified, it will
1888 delegate to the original warnings implementation of showwarning. Otherwise,
1889 it will call warnings.formatwarning and will log the resulting string to a
1890 warnings logger named "py.warnings" with level logging.WARNING.
1891 """
1892 if file is not None:
1893 if _warnings_showwarning is not None:
1894 _warnings_showwarning(message, category, filename, lineno, file, line)
1895 else:
1896 s = warnings.formatwarning(message, category, filename, lineno, line)
1897 logger = getLogger("py.warnings")
1898 if not logger.handlers:
1899 logger.addHandler(NullHandler())
1900 logger.warning("%s", s)
1901
1902def captureWarnings(capture):
1903 """
1904 If capture is true, redirect all warnings to the logging package.
1905 If capture is False, ensure that warnings are not redirected to logging
1906 but to their original destinations.
1907 """
1908 global _warnings_showwarning
1909 if capture:
1910 if _warnings_showwarning is None:
1911 _warnings_showwarning = warnings.showwarning
1912 warnings.showwarning = _showwarning
1913 else:
1914 if _warnings_showwarning is not None:
1915 warnings.showwarning = _warnings_showwarning
1916 _warnings_showwarning = None