Vinay Sajip | 9b727ec | 2012-01-25 17:49:45 +0000 | [diff] [blame] | 1 | # Copyright 2001-2012 by Vinay Sajip. All Rights Reserved. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 2 | # |
| 3 | # Permission to use, copy, modify, and distribute this software and its |
| 4 | # documentation for any purpose and without fee is hereby granted, |
| 5 | # provided that the above copyright notice appear in all copies and that |
| 6 | # both that copyright notice and this permission notice appear in |
| 7 | # supporting documentation, and that the name of Vinay Sajip |
| 8 | # not be used in advertising or publicity pertaining to distribution |
| 9 | # of the software without specific, written prior permission. |
| 10 | # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING |
| 11 | # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL |
| 12 | # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR |
| 13 | # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER |
| 14 | # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT |
| 15 | # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 16 | |
| 17 | """ |
| 18 | Logging package for Python. Based on PEP 282 and comments thereto in |
| 19 | comp.lang.python, and influenced by Apache's log4j system. |
| 20 | |
Vinay Sajip | e6c1eb9 | 2011-03-29 17:20:34 +0100 | [diff] [blame] | 21 | Copyright (C) 2001-2011 Vinay Sajip. All Rights Reserved. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 22 | |
| 23 | To use, simply 'import logging' and log away! |
| 24 | """ |
| 25 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 26 | import sys, os, time, io, traceback, warnings, weakref |
Vinay Sajip | 6a65c5d | 2010-10-26 13:16:11 +0000 | [diff] [blame] | 27 | from string import Template |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 28 | |
Christian Heimes | 18c6689 | 2008-02-17 13:31:39 +0000 | [diff] [blame] | 29 | __all__ = ['BASIC_FORMAT', 'BufferingFormatter', 'CRITICAL', 'DEBUG', 'ERROR', |
Vinay Sajip | ad5fa2f | 2009-04-27 13:55:05 +0000 | [diff] [blame] | 30 | '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 Sajip | 062d56b | 2010-10-19 15:26:24 +0000 | [diff] [blame] | 35 | 'info', 'log', 'makeLogRecord', 'setLoggerClass', 'warn', 'warning', |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 36 | 'getLogRecordFactory', 'setLogRecordFactory', 'lastResort'] |
Vinay Sajip | b89e7c9 | 2005-03-13 09:54:31 +0000 | [diff] [blame] | 37 | |
| 38 | try: |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 39 | import threading |
Vinay Sajip | 26fe4b7 | 2011-04-26 18:43:05 +0100 | [diff] [blame] | 40 | except ImportError: #pragma: no cover |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 41 | threading = None |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 42 | |
| 43 | __author__ = "Vinay Sajip <vinay_sajip@red-dove.com>" |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 44 | __status__ = "production" |
Vinay Sajip | db81c4c | 2010-02-25 23:13:06 +0000 | [diff] [blame] | 45 | __version__ = "0.5.1.2" |
| 46 | __date__ = "07 February 2010" |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 47 | |
| 48 | #--------------------------------------------------------------------------- |
| 49 | # Miscellaneous module data |
| 50 | #--------------------------------------------------------------------------- |
| 51 | |
| 52 | # |
Vinay Sajip | 829dc51 | 2005-02-18 11:53:32 +0000 | [diff] [blame] | 53 | # _srcfile is used when walking the stack to check when we've got the first |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 54 | # caller stack frame. |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 55 | # |
Vinay Sajip | c384fc2 | 2005-09-02 11:20:33 +0000 | [diff] [blame] | 56 | if hasattr(sys, 'frozen'): #support for py2exe |
| 57 | _srcfile = "logging%s__init__%s" % (os.sep, __file__[-4:]) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 58 | else: |
Guido van Rossum | 455ab77 | 2002-11-13 16:18:29 +0000 | [diff] [blame] | 59 | _srcfile = __file__ |
| 60 | _srcfile = os.path.normcase(_srcfile) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 61 | |
Vinay Sajip | 829dc51 | 2005-02-18 11:53:32 +0000 | [diff] [blame] | 62 | |
Vinay Sajip | 26fe4b7 | 2011-04-26 18:43:05 +0100 | [diff] [blame] | 63 | if hasattr(sys, '_getframe'): |
| 64 | currentframe = lambda: sys._getframe(3) |
| 65 | else: #pragma: no cover |
| 66 | def currentframe(): |
| 67 | """Return the frame object for the caller's stack frame.""" |
| 68 | try: |
| 69 | raise Exception |
| 70 | except: |
| 71 | return sys.exc_info()[2].tb_frame.f_back |
Vinay Sajip | 829dc51 | 2005-02-18 11:53:32 +0000 | [diff] [blame] | 72 | |
Jeremy Hylton | 250684d | 2003-01-23 18:29:29 +0000 | [diff] [blame] | 73 | # _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 Sajip | 829dc51 | 2005-02-18 11:53:32 +0000 | [diff] [blame] | 77 | #if not hasattr(sys, "_getframe"): |
| 78 | # _srcfile = None |
Jeremy Hylton | 250684d | 2003-01-23 18:29:29 +0000 | [diff] [blame] | 79 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 80 | # |
| 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 Sajip | 26fe4b7 | 2011-04-26 18:43:05 +0100 | [diff] [blame] | 89 | raiseExceptions = True |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 90 | |
Vinay Sajip | d364a07 | 2006-03-13 22:05:28 +0000 | [diff] [blame] | 91 | # |
| 92 | # If you don't want threading information in the log, set this to zero |
| 93 | # |
Vinay Sajip | 26fe4b7 | 2011-04-26 18:43:05 +0100 | [diff] [blame] | 94 | logThreads = True |
Vinay Sajip | d364a07 | 2006-03-13 22:05:28 +0000 | [diff] [blame] | 95 | |
| 96 | # |
Jesse Noller | 9a0fc97 | 2009-01-18 21:12:58 +0000 | [diff] [blame] | 97 | # If you don't want multiprocessing information in the log, set this to zero |
| 98 | # |
Vinay Sajip | 26fe4b7 | 2011-04-26 18:43:05 +0100 | [diff] [blame] | 99 | logMultiprocessing = True |
Jesse Noller | 9a0fc97 | 2009-01-18 21:12:58 +0000 | [diff] [blame] | 100 | |
| 101 | # |
Vinay Sajip | d364a07 | 2006-03-13 22:05:28 +0000 | [diff] [blame] | 102 | # If you don't want process information in the log, set this to zero |
| 103 | # |
Vinay Sajip | 26fe4b7 | 2011-04-26 18:43:05 +0100 | [diff] [blame] | 104 | logProcesses = True |
Vinay Sajip | d364a07 | 2006-03-13 22:05:28 +0000 | [diff] [blame] | 105 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 106 | #--------------------------------------------------------------------------- |
| 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 Sajip | b89e7c9 | 2005-03-13 09:54:31 +0000 | [diff] [blame] | 116 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 117 | CRITICAL = 50 |
| 118 | FATAL = CRITICAL |
| 119 | ERROR = 40 |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 120 | WARNING = 30 |
| 121 | WARN = WARNING |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 122 | INFO = 20 |
| 123 | DEBUG = 10 |
| 124 | NOTSET = 0 |
| 125 | |
| 126 | _levelNames = { |
| 127 | CRITICAL : 'CRITICAL', |
| 128 | ERROR : 'ERROR', |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 129 | WARNING : 'WARNING', |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 130 | INFO : 'INFO', |
| 131 | DEBUG : 'DEBUG', |
| 132 | NOTSET : 'NOTSET', |
| 133 | 'CRITICAL' : CRITICAL, |
| 134 | 'ERROR' : ERROR, |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 135 | 'WARN' : WARNING, |
| 136 | 'WARNING' : WARNING, |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 137 | 'INFO' : INFO, |
| 138 | 'DEBUG' : DEBUG, |
| 139 | 'NOTSET' : NOTSET, |
| 140 | } |
| 141 | |
| 142 | def getLevelName(level): |
| 143 | """ |
| 144 | Return the textual representation of logging level 'level'. |
| 145 | |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 146 | If the level is one of the predefined levels (CRITICAL, ERROR, WARNING, |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 147 | INFO, DEBUG) then you get the corresponding string. If you have |
| 148 | associated levels with names using addLevelName then the name you have |
Vinay Sajip | 779e0c9 | 2004-07-03 11:47:26 +0000 | [diff] [blame] | 149 | 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 Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 155 | """ |
| 156 | return _levelNames.get(level, ("Level %s" % level)) |
| 157 | |
| 158 | def 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 Sajip | d4fabf4 | 2009-07-13 11:28:25 +0000 | [diff] [blame] | 171 | def _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 Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 182 | #--------------------------------------------------------------------------- |
| 183 | # Thread-related stuff |
| 184 | #--------------------------------------------------------------------------- |
| 185 | |
| 186 | # |
| 187 | #_lock is used to serialize access to shared data structures in this module. |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 188 | #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 Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 191 | #the lock would already have been acquired - so we need an RLock. |
| 192 | #The same argument applies to Loggers and Manager.loggerDict. |
| 193 | # |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 194 | if threading: |
Vinay Sajip | 03f6c11 | 2009-11-27 14:03:36 +0000 | [diff] [blame] | 195 | _lock = threading.RLock() |
Vinay Sajip | 26fe4b7 | 2011-04-26 18:43:05 +0100 | [diff] [blame] | 196 | else: #pragma: no cover |
Vinay Sajip | 03f6c11 | 2009-11-27 14:03:36 +0000 | [diff] [blame] | 197 | _lock = None |
| 198 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 199 | |
| 200 | def _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 Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 206 | if _lock: |
| 207 | _lock.acquire() |
| 208 | |
| 209 | def _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 Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 220 | class LogRecord(object): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 221 | """ |
| 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 Sajip | ed1992f | 2006-02-09 08:48:36 +0000 | [diff] [blame] | 232 | def __init__(self, name, level, pathname, lineno, |
Vinay Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 233 | msg, args, exc_info, func=None, sinfo=None, **kwargs): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 234 | """ |
| 235 | Initialize a logging record with interesting information. |
| 236 | """ |
| 237 | ct = time.time() |
| 238 | self.name = name |
| 239 | self.msg = msg |
Vinay Sajip | 4ed315a | 2004-10-20 08:39:40 +0000 | [diff] [blame] | 240 | # |
| 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 Sajip | 0a88953 | 2011-10-22 13:34:48 +0100 | [diff] [blame] | 249 | # is done. For example, logger.warning('Value is %d', 0) would log |
Vinay Sajip | 4ed315a | 2004-10-20 08:39:40 +0000 | [diff] [blame] | 250 | # '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 Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 253 | if args and len(args) == 1 and isinstance(args[0], dict) and args[0]: |
Vinay Sajip | 4ed315a | 2004-10-20 08:39:40 +0000 | [diff] [blame] | 254 | args = args[0] |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 255 | 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 Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 262 | except (TypeError, ValueError, AttributeError): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 263 | self.filename = pathname |
| 264 | self.module = "Unknown module" |
| 265 | self.exc_info = exc_info |
Vinay Sajip | ed6bb14 | 2004-02-20 13:18:36 +0000 | [diff] [blame] | 266 | self.exc_text = None # used to cache the traceback text |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 267 | self.stack_info = sinfo |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 268 | self.lineno = lineno |
Vinay Sajip | ed1992f | 2006-02-09 08:48:36 +0000 | [diff] [blame] | 269 | self.funcName = func |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 270 | self.created = ct |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 271 | self.msecs = (ct - int(ct)) * 1000 |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 272 | self.relativeCreated = (self.created - _startTime) * 1000 |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 273 | if logThreads and threading: |
| 274 | self.thread = threading.get_ident() |
Benjamin Peterson | 7275370 | 2008-08-18 18:09:21 +0000 | [diff] [blame] | 275 | self.threadName = threading.current_thread().name |
Vinay Sajip | 26fe4b7 | 2011-04-26 18:43:05 +0100 | [diff] [blame] | 276 | else: # pragma: no cover |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 277 | self.thread = None |
Vinay Sajip | 4a70486 | 2005-03-31 20:16:55 +0000 | [diff] [blame] | 278 | self.threadName = None |
Vinay Sajip | 26fe4b7 | 2011-04-26 18:43:05 +0100 | [diff] [blame] | 279 | if not logMultiprocessing: # pragma: no cover |
Jesse Noller | 9a0fc97 | 2009-01-18 21:12:58 +0000 | [diff] [blame] | 280 | self.processName = None |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 281 | else: |
Benjamin Peterson | 22005fc | 2010-04-11 16:25:06 +0000 | [diff] [blame] | 282 | 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 Sajip | 9b727ec | 2012-01-25 17:49:45 +0000 | [diff] [blame] | 291 | except Exception: #pragma: no cover |
Benjamin Peterson | 22005fc | 2010-04-11 16:25:06 +0000 | [diff] [blame] | 292 | pass |
Vinay Sajip | d364a07 | 2006-03-13 22:05:28 +0000 | [diff] [blame] | 293 | if logProcesses and hasattr(os, 'getpid'): |
Jack Jansen | 4c641d0 | 2003-02-21 22:29:45 +0000 | [diff] [blame] | 294 | self.process = os.getpid() |
| 295 | else: |
| 296 | self.process = None |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 297 | |
| 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 Sajip | dc5097f | 2010-08-31 07:52:17 +0000 | [diff] [blame] | 309 | msg = str(self.msg) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 310 | if self.args: |
| 311 | msg = msg % self.args |
| 312 | return msg |
| 313 | |
Vinay Sajip | 062d56b | 2010-10-19 15:26:24 +0000 | [diff] [blame] | 314 | # |
| 315 | # Determine which class to use when instantiating log records. |
| 316 | # |
Vinay Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 317 | _logRecordFactory = LogRecord |
Vinay Sajip | 062d56b | 2010-10-19 15:26:24 +0000 | [diff] [blame] | 318 | |
Vinay Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 319 | def setLogRecordFactory(factory): |
Vinay Sajip | 062d56b | 2010-10-19 15:26:24 +0000 | [diff] [blame] | 320 | """ |
Vinay Sajip | fad058f | 2010-12-03 13:01:11 +0000 | [diff] [blame] | 321 | Set the factory to be used when instantiating a log record. |
Vinay Sajip | 062d56b | 2010-10-19 15:26:24 +0000 | [diff] [blame] | 322 | |
Vinay Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 323 | :param factory: A callable which will be called to instantiate |
| 324 | a log record. |
| 325 | """ |
| 326 | global _logRecordFactory |
| 327 | _logRecordFactory = factory |
| 328 | |
| 329 | def getLogRecordFactory(): |
Vinay Sajip | 062d56b | 2010-10-19 15:26:24 +0000 | [diff] [blame] | 330 | """ |
Vinay Sajip | fad058f | 2010-12-03 13:01:11 +0000 | [diff] [blame] | 331 | Return the factory to be used when instantiating a log record. |
Vinay Sajip | 062d56b | 2010-10-19 15:26:24 +0000 | [diff] [blame] | 332 | """ |
| 333 | |
Vinay Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 334 | return _logRecordFactory |
Vinay Sajip | 062d56b | 2010-10-19 15:26:24 +0000 | [diff] [blame] | 335 | |
Raymond Hettinger | 6f3eaa6 | 2003-06-27 21:43:39 +0000 | [diff] [blame] | 336 | def 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 Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 343 | rv = _logRecordFactory(None, None, "", 0, "", (), None, None) |
Raymond Hettinger | 6f3eaa6 | 2003-06-27 21:43:39 +0000 | [diff] [blame] | 344 | rv.__dict__.update(dict) |
| 345 | return rv |
| 346 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 347 | #--------------------------------------------------------------------------- |
| 348 | # Formatter classes and functions |
| 349 | #--------------------------------------------------------------------------- |
| 350 | |
Vinay Sajip | 6a65c5d | 2010-10-26 13:16:11 +0000 | [diff] [blame] | 351 | class PercentStyle(object): |
| 352 | |
| 353 | default_format = '%(message)s' |
| 354 | asctime_format = '%(asctime)s' |
Vinay Sajip | 10914b7 | 2011-02-26 14:15:48 +0000 | [diff] [blame] | 355 | asctime_search = '%(asctime)' |
Vinay Sajip | 6a65c5d | 2010-10-26 13:16:11 +0000 | [diff] [blame] | 356 | |
| 357 | def __init__(self, fmt): |
| 358 | self._fmt = fmt or self.default_format |
| 359 | |
| 360 | def usesTime(self): |
Vinay Sajip | 10914b7 | 2011-02-26 14:15:48 +0000 | [diff] [blame] | 361 | return self._fmt.find(self.asctime_search) >= 0 |
Vinay Sajip | 6a65c5d | 2010-10-26 13:16:11 +0000 | [diff] [blame] | 362 | |
| 363 | def format(self, record): |
| 364 | return self._fmt % record.__dict__ |
| 365 | |
| 366 | class StrFormatStyle(PercentStyle): |
| 367 | default_format = '{message}' |
| 368 | asctime_format = '{asctime}' |
Vinay Sajip | 10914b7 | 2011-02-26 14:15:48 +0000 | [diff] [blame] | 369 | asctime_search = '{asctime' |
Vinay Sajip | 6a65c5d | 2010-10-26 13:16:11 +0000 | [diff] [blame] | 370 | |
| 371 | def format(self, record): |
| 372 | return self._fmt.format(**record.__dict__) |
| 373 | |
| 374 | |
| 375 | class StringTemplateStyle(PercentStyle): |
| 376 | default_format = '${message}' |
| 377 | asctime_format = '${asctime}' |
Vinay Sajip | 89807a5 | 2011-02-26 16:06:02 +0000 | [diff] [blame] | 378 | asctime_search = '${asctime}' |
Vinay Sajip | 6a65c5d | 2010-10-26 13:16:11 +0000 | [diff] [blame] | 379 | |
| 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 Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 397 | class Formatter(object): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 398 | """ |
| 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 Sajip | 2a20dfc | 2010-10-20 20:05:38 +0000 | [diff] [blame] | 405 | default value of "%s(message)" is used. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 406 | |
| 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 Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 415 | WARNING, ERROR, CRITICAL) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 416 | %(levelname)s Text logging level for the message ("DEBUG", "INFO", |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 417 | "WARNING", "ERROR", "CRITICAL") |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 418 | %(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 Sajip | ed1992f | 2006-02-09 08:48:36 +0000 | [diff] [blame] | 424 | %(funcName)s Function name |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 425 | %(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 Sajip | 4a70486 | 2005-03-31 20:16:55 +0000 | [diff] [blame] | 433 | %(threadName)s Thread name (if available) |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 434 | %(process)d Process ID (if available) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 435 | %(message)s The result of record.getMessage(), computed just as |
| 436 | the record is emitted |
| 437 | """ |
| 438 | |
| 439 | converter = time.localtime |
| 440 | |
Vinay Sajip | a39c571 | 2010-10-25 13:57:39 +0000 | [diff] [blame] | 441 | def __init__(self, fmt=None, datefmt=None, style='%'): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 442 | """ |
| 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 Sajip | a39c571 | 2010-10-25 13:57:39 +0000 | [diff] [blame] | 448 | |
| 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 Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 455 | """ |
Vinay Sajip | 6a65c5d | 2010-10-26 13:16:11 +0000 | [diff] [blame] | 456 | 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 Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 461 | self.datefmt = datefmt |
| 462 | |
Vinay Sajip | ae5740f | 2011-06-09 18:42:19 +0100 | [diff] [blame] | 463 | default_time_format = '%Y-%m-%d %H:%M:%S' |
| 464 | default_msec_format = '%s,%03d' |
| 465 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 466 | 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 Sajip | ae5740f | 2011-06-09 18:42:19 +0100 | [diff] [blame] | 488 | t = time.strftime(self.default_time_format, ct) |
| 489 | s = self.default_msec_format % (t, record.msecs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 490 | 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 Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 499 | sio = io.StringIO() |
Vinay Sajip | 40d9a4e | 2010-08-30 18:10:03 +0000 | [diff] [blame] | 500 | 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 Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 505 | s = sio.getvalue() |
| 506 | sio.close() |
Guido van Rossum | 486364b | 2007-06-30 05:01:58 +0000 | [diff] [blame] | 507 | if s[-1:] == "\n": |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 508 | s = s[:-1] |
| 509 | return s |
| 510 | |
Benjamin Peterson | 9451a1c | 2010-03-13 22:30:34 +0000 | [diff] [blame] | 511 | def usesTime(self): |
| 512 | """ |
| 513 | Check if the format uses the creation time of the record. |
| 514 | """ |
Vinay Sajip | 6a65c5d | 2010-10-26 13:16:11 +0000 | [diff] [blame] | 515 | return self._style.usesTime() |
Benjamin Peterson | 9451a1c | 2010-03-13 22:30:34 +0000 | [diff] [blame] | 516 | |
Vinay Sajip | d0557bf | 2010-10-25 15:25:24 +0000 | [diff] [blame] | 517 | def formatMessage(self, record): |
Vinay Sajip | 6a65c5d | 2010-10-26 13:16:11 +0000 | [diff] [blame] | 518 | return self._style.format(record) |
Vinay Sajip | d0557bf | 2010-10-25 15:25:24 +0000 | [diff] [blame] | 519 | |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 520 | 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 Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 533 | 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 Peterson | 9451a1c | 2010-03-13 22:30:34 +0000 | [diff] [blame] | 541 | 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 Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 545 | """ |
| 546 | record.message = record.getMessage() |
Benjamin Peterson | 9451a1c | 2010-03-13 22:30:34 +0000 | [diff] [blame] | 547 | if self.usesTime(): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 548 | record.asctime = self.formatTime(record, self.datefmt) |
Vinay Sajip | d0557bf | 2010-10-25 15:25:24 +0000 | [diff] [blame] | 549 | s = self.formatMessage(record) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 550 | if record.exc_info: |
Vinay Sajip | ed6bb14 | 2004-02-20 13:18:36 +0000 | [diff] [blame] | 551 | # 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 Rossum | 486364b | 2007-06-30 05:01:58 +0000 | [diff] [blame] | 556 | if s[-1:] != "\n": |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 557 | s = s + "\n" |
Vinay Sajip | ed6bb14 | 2004-02-20 13:18:36 +0000 | [diff] [blame] | 558 | s = s + record.exc_text |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 559 | if record.stack_info: |
| 560 | if s[-1:] != "\n": |
| 561 | s = s + "\n" |
| 562 | s = s + self.formatStack(record.stack_info) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 563 | return s |
| 564 | |
| 565 | # |
| 566 | # The default formatter to use when no other is specified |
| 567 | # |
| 568 | _defaultFormatter = Formatter() |
| 569 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 570 | class BufferingFormatter(object): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 571 | """ |
| 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 Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 612 | class Filter(object): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 613 | """ |
| 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 Sajip | 26fe4b7 | 2011-04-26 18:43:05 +0100 | [diff] [blame] | 642 | return True |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 643 | elif self.name == record.name: |
Vinay Sajip | 26fe4b7 | 2011-04-26 18:43:05 +0100 | [diff] [blame] | 644 | return True |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 645 | elif record.name.find(self.name, 0, self.nlen) != 0: |
Vinay Sajip | 26fe4b7 | 2011-04-26 18:43:05 +0100 | [diff] [blame] | 646 | return False |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 647 | return (record.name[self.nlen] == ".") |
| 648 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 649 | class Filterer(object): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 650 | """ |
| 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 Sajip | 6dbed2e | 2010-10-19 20:53:01 +0000 | [diff] [blame] | 681 | |
| 682 | .. versionchanged: 3.2 |
| 683 | |
| 684 | Allow filters to be just callables. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 685 | """ |
Vinay Sajip | 312cc0d | 2011-04-30 21:51:51 +0100 | [diff] [blame] | 686 | rv = True |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 687 | for f in self.filters: |
Vinay Sajip | 6dbed2e | 2010-10-19 20:53:01 +0000 | [diff] [blame] | 688 | if hasattr(f, 'filter'): |
| 689 | result = f.filter(record) |
Vinay Sajip | 6dbed2e | 2010-10-19 20:53:01 +0000 | [diff] [blame] | 690 | else: |
Vinay Sajip | fc082ca | 2010-10-19 21:13:49 +0000 | [diff] [blame] | 691 | result = f(record) # assume callable - will raise if not |
Vinay Sajip | 6dbed2e | 2010-10-19 20:53:01 +0000 | [diff] [blame] | 692 | if not result: |
Vinay Sajip | 312cc0d | 2011-04-30 21:51:51 +0100 | [diff] [blame] | 693 | rv = False |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 694 | break |
| 695 | return rv |
| 696 | |
| 697 | #--------------------------------------------------------------------------- |
| 698 | # Handler classes and functions |
| 699 | #--------------------------------------------------------------------------- |
| 700 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 701 | _handlers = weakref.WeakValueDictionary() #map of handler names to handlers |
Vinay Sajip | 0ee9ba2 | 2005-09-08 18:14:16 +0000 | [diff] [blame] | 702 | _handlerList = [] # added to allow handlers to be removed in reverse of order initialized |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 703 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 704 | def _removeHandlerRef(wr): |
| 705 | """ |
| 706 | Remove a handler reference from the internal cleanup list. |
| 707 | """ |
Vinay Sajip | de6e9d6 | 2010-08-23 17:50:30 +0000 | [diff] [blame] | 708 | # 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. |
| 711 | if _acquireLock is not None: |
| 712 | _acquireLock() |
| 713 | try: |
| 714 | if wr in _handlerList: |
| 715 | _handlerList.remove(wr) |
| 716 | finally: |
| 717 | _releaseLock() |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 718 | |
| 719 | def _addHandlerRef(handler): |
| 720 | """ |
| 721 | Add a handler to the internal cleanup list using a weak reference. |
| 722 | """ |
| 723 | _acquireLock() |
| 724 | try: |
| 725 | _handlerList.append(weakref.ref(handler, _removeHandlerRef)) |
| 726 | finally: |
| 727 | _releaseLock() |
| 728 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 729 | class Handler(Filterer): |
| 730 | """ |
| 731 | Handler instances dispatch logging events to specific destinations. |
| 732 | |
| 733 | The base handler class. Acts as a placeholder which defines the Handler |
| 734 | interface. Handlers can optionally use Formatter instances to format |
| 735 | records as desired. By default, no formatter is specified; in this case, |
| 736 | the 'raw' message as determined by record.message is logged. |
| 737 | """ |
| 738 | def __init__(self, level=NOTSET): |
| 739 | """ |
| 740 | Initializes the instance - basically setting the formatter to None |
| 741 | and the filter list to empty. |
| 742 | """ |
| 743 | Filterer.__init__(self) |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 744 | self._name = None |
Vinay Sajip | d4fabf4 | 2009-07-13 11:28:25 +0000 | [diff] [blame] | 745 | self.level = _checkLevel(level) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 746 | self.formatter = None |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 747 | # Add the handler to the global _handlerList (for cleanup on shutdown) |
| 748 | _addHandlerRef(self) |
| 749 | self.createLock() |
| 750 | |
| 751 | def get_name(self): |
| 752 | return self._name |
| 753 | |
| 754 | def set_name(self, name): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 755 | _acquireLock() |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 756 | try: |
| 757 | if self._name in _handlers: |
| 758 | del _handlers[self._name] |
| 759 | self._name = name |
| 760 | if name: |
| 761 | _handlers[name] = self |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 762 | finally: |
| 763 | _releaseLock() |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 764 | |
| 765 | name = property(get_name, set_name) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 766 | |
| 767 | def createLock(self): |
| 768 | """ |
| 769 | Acquire a thread lock for serializing access to the underlying I/O. |
| 770 | """ |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 771 | if threading: |
Vinay Sajip | 4a70486 | 2005-03-31 20:16:55 +0000 | [diff] [blame] | 772 | self.lock = threading.RLock() |
Vinay Sajip | 26fe4b7 | 2011-04-26 18:43:05 +0100 | [diff] [blame] | 773 | else: #pragma: no cover |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 774 | self.lock = None |
| 775 | |
| 776 | def acquire(self): |
| 777 | """ |
| 778 | Acquire the I/O thread lock. |
| 779 | """ |
| 780 | if self.lock: |
| 781 | self.lock.acquire() |
| 782 | |
| 783 | def release(self): |
| 784 | """ |
| 785 | Release the I/O thread lock. |
| 786 | """ |
| 787 | if self.lock: |
| 788 | self.lock.release() |
| 789 | |
| 790 | def setLevel(self, level): |
| 791 | """ |
Gregory P. Smith | e85488c | 2011-12-17 12:36:34 -0800 | [diff] [blame] | 792 | Set the logging level of this handler. level must be an int or a str. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 793 | """ |
Vinay Sajip | d4fabf4 | 2009-07-13 11:28:25 +0000 | [diff] [blame] | 794 | self.level = _checkLevel(level) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 795 | |
| 796 | def format(self, record): |
| 797 | """ |
| 798 | Format the specified record. |
| 799 | |
| 800 | If a formatter is set, use it. Otherwise, use the default formatter |
| 801 | for the module. |
| 802 | """ |
| 803 | if self.formatter: |
| 804 | fmt = self.formatter |
| 805 | else: |
| 806 | fmt = _defaultFormatter |
| 807 | return fmt.format(record) |
| 808 | |
| 809 | def emit(self, record): |
| 810 | """ |
| 811 | Do whatever it takes to actually log the specified logging record. |
| 812 | |
| 813 | This version is intended to be implemented by subclasses and so |
| 814 | raises a NotImplementedError. |
| 815 | """ |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 816 | raise NotImplementedError('emit must be implemented ' |
| 817 | 'by Handler subclasses') |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 818 | |
| 819 | def handle(self, record): |
| 820 | """ |
| 821 | Conditionally emit the specified logging record. |
| 822 | |
| 823 | Emission depends on filters which may have been added to the handler. |
| 824 | Wrap the actual emission of the record with acquisition/release of |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 825 | the I/O thread lock. Returns whether the filter passed the record for |
| 826 | emission. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 827 | """ |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 828 | rv = self.filter(record) |
| 829 | if rv: |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 830 | self.acquire() |
| 831 | try: |
| 832 | self.emit(record) |
| 833 | finally: |
| 834 | self.release() |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 835 | return rv |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 836 | |
| 837 | def setFormatter(self, fmt): |
| 838 | """ |
| 839 | Set the formatter for this handler. |
| 840 | """ |
| 841 | self.formatter = fmt |
| 842 | |
| 843 | def flush(self): |
| 844 | """ |
| 845 | Ensure all logging output has been flushed. |
| 846 | |
| 847 | This version does nothing and is intended to be implemented by |
| 848 | subclasses. |
| 849 | """ |
| 850 | pass |
| 851 | |
| 852 | def close(self): |
| 853 | """ |
| 854 | Tidy up any resources used by the handler. |
| 855 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 856 | This version removes the handler from an internal map of handlers, |
| 857 | _handlers, which is used for handler lookup by name. Subclasses |
Vinay Sajip | ed6bb14 | 2004-02-20 13:18:36 +0000 | [diff] [blame] | 858 | should ensure that this gets called from overridden close() |
| 859 | methods. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 860 | """ |
Vinay Sajip | ed6bb14 | 2004-02-20 13:18:36 +0000 | [diff] [blame] | 861 | #get the module data lock, as we're updating a shared structure. |
| 862 | _acquireLock() |
| 863 | try: #unlikely to raise an exception, but you never know... |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 864 | if self._name and self._name in _handlers: |
| 865 | del _handlers[self._name] |
Vinay Sajip | ed6bb14 | 2004-02-20 13:18:36 +0000 | [diff] [blame] | 866 | finally: |
| 867 | _releaseLock() |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 868 | |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 869 | def handleError(self, record): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 870 | """ |
| 871 | Handle errors which occur during an emit() call. |
| 872 | |
| 873 | This method should be called from handlers when an exception is |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 874 | encountered during an emit() call. If raiseExceptions is false, |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 875 | exceptions get silently ignored. This is what is mostly wanted |
| 876 | for a logging system - most users will not care about errors in |
| 877 | the logging system, they are more interested in application errors. |
| 878 | You could, however, replace this with a custom handler if you wish. |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 879 | The record which was being processed is passed in to this method. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 880 | """ |
Vinay Sajip | 889bb29 | 2012-01-20 11:23:02 +0000 | [diff] [blame] | 881 | if raiseExceptions and sys.stderr: # see issue 13807 |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 882 | ei = sys.exc_info() |
Benjamin Peterson | fa0d703 | 2009-06-01 22:42:33 +0000 | [diff] [blame] | 883 | try: |
Vinay Sajip | db81c4c | 2010-02-25 23:13:06 +0000 | [diff] [blame] | 884 | traceback.print_exception(ei[0], ei[1], ei[2], |
| 885 | None, sys.stderr) |
| 886 | sys.stderr.write('Logged from file %s, line %s\n' % ( |
| 887 | record.filename, record.lineno)) |
Vinay Sajip | 985ef87 | 2011-04-26 19:34:04 +0100 | [diff] [blame] | 888 | except IOError: #pragma: no cover |
Benjamin Peterson | fa0d703 | 2009-06-01 22:42:33 +0000 | [diff] [blame] | 889 | pass # see issue 5971 |
| 890 | finally: |
| 891 | del ei |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 892 | |
| 893 | class StreamHandler(Handler): |
| 894 | """ |
| 895 | A handler class which writes logging records, appropriately formatted, |
| 896 | to a stream. Note that this class does not close the stream, as |
| 897 | sys.stdout or sys.stderr may be used. |
| 898 | """ |
Benjamin Peterson | 3e4f055 | 2008-09-02 00:31:15 +0000 | [diff] [blame] | 899 | |
Vinay Sajip | 2a20dfc | 2010-10-20 20:05:38 +0000 | [diff] [blame] | 900 | terminator = '\n' |
| 901 | |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 902 | def __init__(self, stream=None): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 903 | """ |
| 904 | Initialize the handler. |
| 905 | |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 906 | If stream is not specified, sys.stderr is used. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 907 | """ |
| 908 | Handler.__init__(self) |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 909 | if stream is None: |
| 910 | stream = sys.stderr |
| 911 | self.stream = stream |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 912 | |
| 913 | def flush(self): |
| 914 | """ |
| 915 | Flushes the stream. |
| 916 | """ |
Amaury Forgeot d'Arc | 35c8658 | 2008-06-17 21:11:29 +0000 | [diff] [blame] | 917 | if self.stream and hasattr(self.stream, "flush"): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 918 | self.stream.flush() |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 919 | |
| 920 | def emit(self, record): |
| 921 | """ |
| 922 | Emit a record. |
| 923 | |
| 924 | If a formatter is specified, it is used to format the record. |
Benjamin Peterson | 3e4f055 | 2008-09-02 00:31:15 +0000 | [diff] [blame] | 925 | The record is then written to the stream with a trailing newline. If |
| 926 | exception information is present, it is formatted using |
| 927 | traceback.print_exception and appended to the stream. If the stream |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 928 | has an 'encoding' attribute, it is used to determine how to do the |
Benjamin Peterson | 3e4f055 | 2008-09-02 00:31:15 +0000 | [diff] [blame] | 929 | output to the stream. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 930 | """ |
| 931 | try: |
| 932 | msg = self.format(record) |
Benjamin Peterson | f91df04 | 2009-02-13 02:50:59 +0000 | [diff] [blame] | 933 | stream = self.stream |
Vinay Sajip | 2a20dfc | 2010-10-20 20:05:38 +0000 | [diff] [blame] | 934 | stream.write(msg) |
| 935 | stream.write(self.terminator) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 936 | self.flush() |
Vinay Sajip | 26fe4b7 | 2011-04-26 18:43:05 +0100 | [diff] [blame] | 937 | except (KeyboardInterrupt, SystemExit): #pragma: no cover |
Vinay Sajip | 85c1909 | 2005-10-31 13:14:19 +0000 | [diff] [blame] | 938 | raise |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 939 | except: |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 940 | self.handleError(record) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 941 | |
| 942 | class FileHandler(StreamHandler): |
| 943 | """ |
| 944 | A handler class which writes formatted logging records to disk files. |
| 945 | """ |
Vinay Sajip | 26fe4b7 | 2011-04-26 18:43:05 +0100 | [diff] [blame] | 946 | def __init__(self, filename, mode='a', encoding=None, delay=False): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 947 | """ |
| 948 | Open the specified file and use it as the stream for logging. |
| 949 | """ |
Vinay Sajip | 4bbab2b | 2004-07-08 10:22:35 +0000 | [diff] [blame] | 950 | #keep the absolute path, otherwise derived classes which use this |
| 951 | #may come a cropper when the current directory changes |
| 952 | self.baseFilename = os.path.abspath(filename) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 953 | self.mode = mode |
Thomas Wouters | fc7bb8c | 2007-01-15 15:49:28 +0000 | [diff] [blame] | 954 | self.encoding = encoding |
Christian Heimes | e7a15bb | 2008-01-24 16:21:45 +0000 | [diff] [blame] | 955 | if delay: |
Vinay Sajip | 6268cbc | 2009-01-21 00:19:28 +0000 | [diff] [blame] | 956 | #We don't open the stream, but we still need to call the |
| 957 | #Handler constructor to set level, formatter, lock etc. |
| 958 | Handler.__init__(self) |
Christian Heimes | e7a15bb | 2008-01-24 16:21:45 +0000 | [diff] [blame] | 959 | self.stream = None |
| 960 | else: |
Vinay Sajip | 6268cbc | 2009-01-21 00:19:28 +0000 | [diff] [blame] | 961 | StreamHandler.__init__(self, self._open()) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 962 | |
| 963 | def close(self): |
| 964 | """ |
| 965 | Closes the stream. |
| 966 | """ |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 967 | if self.stream: |
| 968 | self.flush() |
Amaury Forgeot d'Arc | 35c8658 | 2008-06-17 21:11:29 +0000 | [diff] [blame] | 969 | if hasattr(self.stream, "close"): |
| 970 | self.stream.close() |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 971 | StreamHandler.close(self) |
| 972 | self.stream = None |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 973 | |
Thomas Wouters | fc7bb8c | 2007-01-15 15:49:28 +0000 | [diff] [blame] | 974 | def _open(self): |
| 975 | """ |
| 976 | Open the current base file with the (original) mode and encoding. |
| 977 | Return the resulting stream. |
| 978 | """ |
Florent Xicluna | 5252f9f | 2011-11-07 19:43:05 +0100 | [diff] [blame] | 979 | return open(self.baseFilename, self.mode, encoding=self.encoding) |
Thomas Wouters | fc7bb8c | 2007-01-15 15:49:28 +0000 | [diff] [blame] | 980 | |
Christian Heimes | e7a15bb | 2008-01-24 16:21:45 +0000 | [diff] [blame] | 981 | def emit(self, record): |
| 982 | """ |
| 983 | Emit a record. |
| 984 | |
| 985 | If the stream was not opened because 'delay' was specified in the |
| 986 | constructor, open it before calling the superclass's emit. |
| 987 | """ |
| 988 | if self.stream is None: |
Vinay Sajip | 6268cbc | 2009-01-21 00:19:28 +0000 | [diff] [blame] | 989 | self.stream = self._open() |
Christian Heimes | e7a15bb | 2008-01-24 16:21:45 +0000 | [diff] [blame] | 990 | StreamHandler.emit(self, record) |
| 991 | |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 992 | class _StderrHandler(StreamHandler): |
| 993 | """ |
| 994 | This class is like a StreamHandler using sys.stderr, but always uses |
| 995 | whatever sys.stderr is currently set to rather than the value of |
| 996 | sys.stderr at handler construction time. |
| 997 | """ |
| 998 | def __init__(self, level=NOTSET): |
| 999 | """ |
| 1000 | Initialize the handler. |
| 1001 | """ |
| 1002 | Handler.__init__(self, level) |
| 1003 | |
| 1004 | @property |
| 1005 | def stream(self): |
| 1006 | return sys.stderr |
| 1007 | |
| 1008 | |
| 1009 | _defaultLastResort = _StderrHandler(WARNING) |
| 1010 | lastResort = _defaultLastResort |
| 1011 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1012 | #--------------------------------------------------------------------------- |
| 1013 | # Manager classes and functions |
| 1014 | #--------------------------------------------------------------------------- |
| 1015 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 1016 | class PlaceHolder(object): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1017 | """ |
| 1018 | PlaceHolder instances are used in the Manager logger hierarchy to take |
Vinay Sajip | 3f74284 | 2004-02-28 16:07:46 +0000 | [diff] [blame] | 1019 | the place of nodes for which no loggers have been defined. This class is |
| 1020 | intended for internal use only and not as part of the public API. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1021 | """ |
| 1022 | def __init__(self, alogger): |
| 1023 | """ |
| 1024 | Initialize with the specified logger being a child of this placeholder. |
| 1025 | """ |
Vinay Sajip | 239322b | 2005-10-14 09:36:35 +0000 | [diff] [blame] | 1026 | self.loggerMap = { alogger : None } |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1027 | |
| 1028 | def append(self, alogger): |
| 1029 | """ |
| 1030 | Add the specified logger as a child of this placeholder. |
| 1031 | """ |
Guido van Rossum | 9366241 | 2006-08-19 16:09:41 +0000 | [diff] [blame] | 1032 | if alogger not in self.loggerMap: |
Vinay Sajip | 239322b | 2005-10-14 09:36:35 +0000 | [diff] [blame] | 1033 | self.loggerMap[alogger] = None |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1034 | |
| 1035 | # |
| 1036 | # Determine which class to use when instantiating loggers. |
| 1037 | # |
| 1038 | _loggerClass = None |
| 1039 | |
| 1040 | def setLoggerClass(klass): |
| 1041 | """ |
| 1042 | Set the class to be used when instantiating a logger. The class should |
| 1043 | define __init__() such that only a name argument is required, and the |
| 1044 | __init__() should call Logger.__init__() |
| 1045 | """ |
| 1046 | if klass != Logger: |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1047 | if not issubclass(klass, Logger): |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 1048 | raise TypeError("logger not derived from logging.Logger: " |
| 1049 | + klass.__name__) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1050 | global _loggerClass |
| 1051 | _loggerClass = klass |
| 1052 | |
Vinay Sajip | b959117 | 2004-09-22 12:39:26 +0000 | [diff] [blame] | 1053 | def getLoggerClass(): |
| 1054 | """ |
| 1055 | Return the class to be used when instantiating a logger. |
| 1056 | """ |
| 1057 | |
| 1058 | return _loggerClass |
| 1059 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 1060 | class Manager(object): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1061 | """ |
| 1062 | There is [under normal circumstances] just one Manager instance, which |
| 1063 | holds the hierarchy of loggers. |
| 1064 | """ |
Neal Norwitz | d1cade0 | 2002-11-15 23:31:28 +0000 | [diff] [blame] | 1065 | def __init__(self, rootnode): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1066 | """ |
| 1067 | Initialize the manager with the root node of the logger hierarchy. |
| 1068 | """ |
Neal Norwitz | d1cade0 | 2002-11-15 23:31:28 +0000 | [diff] [blame] | 1069 | self.root = rootnode |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1070 | self.disable = 0 |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1071 | self.emittedNoHandlerWarning = False |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1072 | self.loggerDict = {} |
Vinay Sajip | db81c4c | 2010-02-25 23:13:06 +0000 | [diff] [blame] | 1073 | self.loggerClass = None |
Vinay Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 1074 | self.logRecordFactory = None |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1075 | |
| 1076 | def getLogger(self, name): |
| 1077 | """ |
| 1078 | Get a logger with the specified name (channel name), creating it |
Vinay Sajip | b959117 | 2004-09-22 12:39:26 +0000 | [diff] [blame] | 1079 | if it doesn't yet exist. This name is a dot-separated hierarchical |
| 1080 | name, such as "a", "a.b", "a.b.c" or similar. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1081 | |
| 1082 | If a PlaceHolder existed for the specified name [i.e. the logger |
| 1083 | didn't exist but a child of it did], replace it with the created |
| 1084 | logger and fix up the parent/child references which pointed to the |
| 1085 | placeholder to now point to the logger. |
| 1086 | """ |
| 1087 | rv = None |
Vinay Sajip | 61b787e | 2011-11-07 08:53:03 +0000 | [diff] [blame] | 1088 | if not isinstance(name, str): |
Vinay Sajip | 3bd5638 | 2011-11-07 10:15:08 +0000 | [diff] [blame] | 1089 | raise TypeError('A logger name must be a string') |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1090 | _acquireLock() |
| 1091 | try: |
Guido van Rossum | 9366241 | 2006-08-19 16:09:41 +0000 | [diff] [blame] | 1092 | if name in self.loggerDict: |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1093 | rv = self.loggerDict[name] |
| 1094 | if isinstance(rv, PlaceHolder): |
| 1095 | ph = rv |
Vinay Sajip | db81c4c | 2010-02-25 23:13:06 +0000 | [diff] [blame] | 1096 | rv = (self.loggerClass or _loggerClass)(name) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1097 | rv.manager = self |
| 1098 | self.loggerDict[name] = rv |
| 1099 | self._fixupChildren(ph, rv) |
| 1100 | self._fixupParents(rv) |
| 1101 | else: |
Vinay Sajip | db81c4c | 2010-02-25 23:13:06 +0000 | [diff] [blame] | 1102 | rv = (self.loggerClass or _loggerClass)(name) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1103 | rv.manager = self |
| 1104 | self.loggerDict[name] = rv |
| 1105 | self._fixupParents(rv) |
| 1106 | finally: |
| 1107 | _releaseLock() |
| 1108 | return rv |
| 1109 | |
Vinay Sajip | db81c4c | 2010-02-25 23:13:06 +0000 | [diff] [blame] | 1110 | def setLoggerClass(self, klass): |
| 1111 | """ |
| 1112 | Set the class to be used when instantiating a logger with this Manager. |
| 1113 | """ |
| 1114 | if klass != Logger: |
| 1115 | if not issubclass(klass, Logger): |
| 1116 | raise TypeError("logger not derived from logging.Logger: " |
| 1117 | + klass.__name__) |
| 1118 | self.loggerClass = klass |
| 1119 | |
Vinay Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 1120 | def setLogRecordFactory(self, factory): |
Vinay Sajip | 6fac817 | 2010-10-19 20:44:14 +0000 | [diff] [blame] | 1121 | """ |
Vinay Sajip | fad058f | 2010-12-03 13:01:11 +0000 | [diff] [blame] | 1122 | Set the factory to be used when instantiating a log record with this |
Vinay Sajip | 6fac817 | 2010-10-19 20:44:14 +0000 | [diff] [blame] | 1123 | Manager. |
| 1124 | """ |
Vinay Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 1125 | self.logRecordFactory = factory |
Vinay Sajip | 6fac817 | 2010-10-19 20:44:14 +0000 | [diff] [blame] | 1126 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1127 | def _fixupParents(self, alogger): |
| 1128 | """ |
| 1129 | Ensure that there are either loggers or placeholders all the way |
| 1130 | from the specified logger to the root of the logger hierarchy. |
| 1131 | """ |
| 1132 | name = alogger.name |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 1133 | i = name.rfind(".") |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1134 | rv = None |
| 1135 | while (i > 0) and not rv: |
| 1136 | substr = name[:i] |
Guido van Rossum | 9366241 | 2006-08-19 16:09:41 +0000 | [diff] [blame] | 1137 | if substr not in self.loggerDict: |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1138 | self.loggerDict[substr] = PlaceHolder(alogger) |
| 1139 | else: |
| 1140 | obj = self.loggerDict[substr] |
| 1141 | if isinstance(obj, Logger): |
| 1142 | rv = obj |
| 1143 | else: |
| 1144 | assert isinstance(obj, PlaceHolder) |
| 1145 | obj.append(alogger) |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 1146 | i = name.rfind(".", 0, i - 1) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1147 | if not rv: |
| 1148 | rv = self.root |
| 1149 | alogger.parent = rv |
| 1150 | |
| 1151 | def _fixupChildren(self, ph, alogger): |
| 1152 | """ |
| 1153 | Ensure that children of the placeholder ph are connected to the |
| 1154 | specified logger. |
| 1155 | """ |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1156 | name = alogger.name |
| 1157 | namelen = len(name) |
Vinay Sajip | 239322b | 2005-10-14 09:36:35 +0000 | [diff] [blame] | 1158 | for c in ph.loggerMap.keys(): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1159 | #The if means ... if not c.parent.name.startswith(nm) |
| 1160 | if c.parent.name[:namelen] != name: |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1161 | alogger.parent = c.parent |
| 1162 | c.parent = alogger |
| 1163 | |
| 1164 | #--------------------------------------------------------------------------- |
| 1165 | # Logger classes and functions |
| 1166 | #--------------------------------------------------------------------------- |
| 1167 | |
| 1168 | class Logger(Filterer): |
| 1169 | """ |
| 1170 | Instances of the Logger class represent a single logging channel. A |
| 1171 | "logging channel" indicates an area of an application. Exactly how an |
| 1172 | "area" is defined is up to the application developer. Since an |
| 1173 | application can have any number of areas, logging channels are identified |
| 1174 | by a unique string. Application areas can be nested (e.g. an area |
| 1175 | of "input processing" might include sub-areas "read CSV files", "read |
| 1176 | XLS files" and "read Gnumeric files"). To cater for this natural nesting, |
| 1177 | channel names are organized into a namespace hierarchy where levels are |
| 1178 | separated by periods, much like the Java or Python package namespace. So |
| 1179 | in the instance given above, channel names might be "input" for the upper |
| 1180 | level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels. |
| 1181 | There is no arbitrary limit to the depth of nesting. |
| 1182 | """ |
| 1183 | def __init__(self, name, level=NOTSET): |
| 1184 | """ |
| 1185 | Initialize the logger with a name and an optional level. |
| 1186 | """ |
| 1187 | Filterer.__init__(self) |
| 1188 | self.name = name |
Vinay Sajip | d4fabf4 | 2009-07-13 11:28:25 +0000 | [diff] [blame] | 1189 | self.level = _checkLevel(level) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1190 | self.parent = None |
Vinay Sajip | 312cc0d | 2011-04-30 21:51:51 +0100 | [diff] [blame] | 1191 | self.propagate = True |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1192 | self.handlers = [] |
Vinay Sajip | 312cc0d | 2011-04-30 21:51:51 +0100 | [diff] [blame] | 1193 | self.disabled = False |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1194 | |
| 1195 | def setLevel(self, level): |
| 1196 | """ |
Gregory P. Smith | e85488c | 2011-12-17 12:36:34 -0800 | [diff] [blame] | 1197 | Set the logging level of this logger. level must be an int or a str. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1198 | """ |
Vinay Sajip | d4fabf4 | 2009-07-13 11:28:25 +0000 | [diff] [blame] | 1199 | self.level = _checkLevel(level) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1200 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1201 | def debug(self, msg, *args, **kwargs): |
| 1202 | """ |
| 1203 | Log 'msg % args' with severity 'DEBUG'. |
| 1204 | |
| 1205 | To pass exception information, use the keyword argument exc_info with |
| 1206 | a true value, e.g. |
| 1207 | |
| 1208 | logger.debug("Houston, we have a %s", "thorny problem", exc_info=1) |
| 1209 | """ |
Guido van Rossum | 04110fb | 2007-08-24 16:32:05 +0000 | [diff] [blame] | 1210 | if self.isEnabledFor(DEBUG): |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1211 | self._log(DEBUG, msg, args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1212 | |
| 1213 | def info(self, msg, *args, **kwargs): |
| 1214 | """ |
| 1215 | Log 'msg % args' with severity 'INFO'. |
| 1216 | |
| 1217 | To pass exception information, use the keyword argument exc_info with |
| 1218 | a true value, e.g. |
| 1219 | |
| 1220 | logger.info("Houston, we have a %s", "interesting problem", exc_info=1) |
| 1221 | """ |
Guido van Rossum | 04110fb | 2007-08-24 16:32:05 +0000 | [diff] [blame] | 1222 | if self.isEnabledFor(INFO): |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1223 | self._log(INFO, msg, args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1224 | |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 1225 | def warning(self, msg, *args, **kwargs): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1226 | """ |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 1227 | Log 'msg % args' with severity 'WARNING'. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1228 | |
| 1229 | To pass exception information, use the keyword argument exc_info with |
| 1230 | a true value, e.g. |
| 1231 | |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 1232 | logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1233 | """ |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 1234 | if self.isEnabledFor(WARNING): |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1235 | self._log(WARNING, msg, args, **kwargs) |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 1236 | |
Vinay Sajip | 04d5bc0 | 2011-10-21 07:33:42 +0100 | [diff] [blame] | 1237 | def warn(self, msg, *args, **kwargs): |
| 1238 | warnings.warn("The 'warn' method is deprecated, " |
Vinay Sajip | 0a88953 | 2011-10-22 13:34:48 +0100 | [diff] [blame] | 1239 | "use 'warning' instead", DeprecationWarning, 2) |
Vinay Sajip | 04d5bc0 | 2011-10-21 07:33:42 +0100 | [diff] [blame] | 1240 | self.warning(msg, *args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1241 | |
| 1242 | def error(self, msg, *args, **kwargs): |
| 1243 | """ |
| 1244 | Log 'msg % args' with severity 'ERROR'. |
| 1245 | |
| 1246 | To pass exception information, use the keyword argument exc_info with |
| 1247 | a true value, e.g. |
| 1248 | |
| 1249 | logger.error("Houston, we have a %s", "major problem", exc_info=1) |
| 1250 | """ |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1251 | if self.isEnabledFor(ERROR): |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1252 | self._log(ERROR, msg, args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1253 | |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1254 | def exception(self, msg, *args, **kwargs): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1255 | """ |
| 1256 | Convenience method for logging an ERROR with exception information. |
| 1257 | """ |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1258 | kwargs['exc_info'] = True |
| 1259 | self.error(msg, *args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1260 | |
| 1261 | def critical(self, msg, *args, **kwargs): |
| 1262 | """ |
| 1263 | Log 'msg % args' with severity 'CRITICAL'. |
| 1264 | |
| 1265 | To pass exception information, use the keyword argument exc_info with |
| 1266 | a true value, e.g. |
| 1267 | |
| 1268 | logger.critical("Houston, we have a %s", "major disaster", exc_info=1) |
| 1269 | """ |
Guido van Rossum | 04110fb | 2007-08-24 16:32:05 +0000 | [diff] [blame] | 1270 | if self.isEnabledFor(CRITICAL): |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1271 | self._log(CRITICAL, msg, args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1272 | |
| 1273 | fatal = critical |
| 1274 | |
| 1275 | def log(self, level, msg, *args, **kwargs): |
| 1276 | """ |
Vinay Sajip | eb477d0 | 2004-08-04 08:38:08 +0000 | [diff] [blame] | 1277 | Log 'msg % args' with the integer severity 'level'. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1278 | |
| 1279 | To pass exception information, use the keyword argument exc_info with |
| 1280 | a true value, e.g. |
| 1281 | |
| 1282 | logger.log(level, "We have a %s", "mysterious problem", exc_info=1) |
| 1283 | """ |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 1284 | if not isinstance(level, int): |
Vinay Sajip | 779e0c9 | 2004-07-03 11:47:26 +0000 | [diff] [blame] | 1285 | if raiseExceptions: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 1286 | raise TypeError("level must be an integer") |
Vinay Sajip | 779e0c9 | 2004-07-03 11:47:26 +0000 | [diff] [blame] | 1287 | else: |
| 1288 | return |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1289 | if self.isEnabledFor(level): |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1290 | self._log(level, msg, args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1291 | |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1292 | def findCaller(self, stack_info=False): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1293 | """ |
| 1294 | Find the stack frame of the caller so that we can note the source |
Vinay Sajip | 829dc51 | 2005-02-18 11:53:32 +0000 | [diff] [blame] | 1295 | file name, line number and function name. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1296 | """ |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 1297 | f = currentframe() |
| 1298 | #On some versions of IronPython, currentframe() returns None if |
| 1299 | #IronPython isn't run with -X:Frames. |
| 1300 | if f is not None: |
| 1301 | f = f.f_back |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1302 | rv = "(unknown file)", 0, "(unknown function)", None |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 1303 | while hasattr(f, "f_code"): |
Jeremy Hylton | 250684d | 2003-01-23 18:29:29 +0000 | [diff] [blame] | 1304 | co = f.f_code |
| 1305 | filename = os.path.normcase(co.co_filename) |
| 1306 | if filename == _srcfile: |
| 1307 | f = f.f_back |
| 1308 | continue |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1309 | sinfo = None |
| 1310 | if stack_info: |
| 1311 | sio = io.StringIO() |
| 1312 | sio.write('Stack (most recent call last):\n') |
| 1313 | traceback.print_stack(f, file=sio) |
| 1314 | sinfo = sio.getvalue() |
| 1315 | if sinfo[-1] == '\n': |
| 1316 | sinfo = sinfo[:-1] |
| 1317 | sio.close() |
| 1318 | rv = (co.co_filename, f.f_lineno, co.co_name, sinfo) |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 1319 | break |
| 1320 | return rv |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1321 | |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1322 | def makeRecord(self, name, level, fn, lno, msg, args, exc_info, |
| 1323 | func=None, extra=None, sinfo=None): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1324 | """ |
| 1325 | A factory method which can be overridden in subclasses to create |
| 1326 | specialized LogRecords. |
| 1327 | """ |
Vinay Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 1328 | rv = _logRecordFactory(name, level, fn, lno, msg, args, exc_info, func, |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1329 | sinfo) |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1330 | if extra is not None: |
Vinay Sajip | 260ce43 | 2006-02-09 08:34:14 +0000 | [diff] [blame] | 1331 | for key in extra: |
| 1332 | if (key in ["message", "asctime"]) or (key in rv.__dict__): |
| 1333 | raise KeyError("Attempt to overwrite %r in LogRecord" % key) |
| 1334 | rv.__dict__[key] = extra[key] |
| 1335 | return rv |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1336 | |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1337 | def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1338 | """ |
| 1339 | Low-level logging routine which creates a LogRecord and then calls |
| 1340 | all the handlers of this logger to handle the record. |
| 1341 | """ |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1342 | sinfo = None |
Jeremy Hylton | 250684d | 2003-01-23 18:29:29 +0000 | [diff] [blame] | 1343 | if _srcfile: |
Vinay Sajip | b672b6d | 2009-02-19 12:36:11 +0000 | [diff] [blame] | 1344 | #IronPython doesn't track Python frames, so findCaller throws an |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 1345 | #exception on some versions of IronPython. We trap it here so that |
| 1346 | #IronPython can use logging. |
Vinay Sajip | b672b6d | 2009-02-19 12:36:11 +0000 | [diff] [blame] | 1347 | try: |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1348 | fn, lno, func, sinfo = self.findCaller(stack_info) |
Vinay Sajip | 26fe4b7 | 2011-04-26 18:43:05 +0100 | [diff] [blame] | 1349 | except ValueError: # pragma: no cover |
Vinay Sajip | b672b6d | 2009-02-19 12:36:11 +0000 | [diff] [blame] | 1350 | fn, lno, func = "(unknown file)", 0, "(unknown function)" |
Vinay Sajip | 26fe4b7 | 2011-04-26 18:43:05 +0100 | [diff] [blame] | 1351 | else: # pragma: no cover |
Vinay Sajip | 829dc51 | 2005-02-18 11:53:32 +0000 | [diff] [blame] | 1352 | fn, lno, func = "(unknown file)", 0, "(unknown function)" |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1353 | if exc_info: |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 1354 | if not isinstance(exc_info, tuple): |
Vinay Sajip | ed6bb14 | 2004-02-20 13:18:36 +0000 | [diff] [blame] | 1355 | exc_info = sys.exc_info() |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1356 | record = self.makeRecord(self.name, level, fn, lno, msg, args, |
| 1357 | exc_info, func, extra, sinfo) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1358 | self.handle(record) |
| 1359 | |
| 1360 | def handle(self, record): |
| 1361 | """ |
| 1362 | Call the handlers for the specified record. |
| 1363 | |
| 1364 | This method is used for unpickled records received from a socket, as |
| 1365 | well as those created locally. Logger-level filtering is applied. |
| 1366 | """ |
| 1367 | if (not self.disabled) and self.filter(record): |
| 1368 | self.callHandlers(record) |
| 1369 | |
| 1370 | def addHandler(self, hdlr): |
| 1371 | """ |
| 1372 | Add the specified handler to this logger. |
| 1373 | """ |
Vinay Sajip | 32fb6a8 | 2010-09-25 17:42:36 +0000 | [diff] [blame] | 1374 | _acquireLock() |
| 1375 | try: |
| 1376 | if not (hdlr in self.handlers): |
| 1377 | self.handlers.append(hdlr) |
| 1378 | finally: |
| 1379 | _releaseLock() |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1380 | |
| 1381 | def removeHandler(self, hdlr): |
| 1382 | """ |
| 1383 | Remove the specified handler from this logger. |
| 1384 | """ |
Vinay Sajip | 32fb6a8 | 2010-09-25 17:42:36 +0000 | [diff] [blame] | 1385 | _acquireLock() |
| 1386 | try: |
| 1387 | if hdlr in self.handlers: |
Vinay Sajip | 116f16e | 2005-09-16 10:33:40 +0000 | [diff] [blame] | 1388 | self.handlers.remove(hdlr) |
Vinay Sajip | 32fb6a8 | 2010-09-25 17:42:36 +0000 | [diff] [blame] | 1389 | finally: |
| 1390 | _releaseLock() |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1391 | |
Vinay Sajip | b4a0809 | 2010-09-20 09:55:00 +0000 | [diff] [blame] | 1392 | def hasHandlers(self): |
| 1393 | """ |
| 1394 | See if this logger has any handlers configured. |
| 1395 | |
| 1396 | Loop through all handlers for this logger and its parents in the |
| 1397 | logger hierarchy. Return True if a handler was found, else False. |
| 1398 | Stop searching up the hierarchy whenever a logger with the "propagate" |
| 1399 | attribute set to zero is found - that will be the last logger which |
| 1400 | is checked for the existence of handlers. |
| 1401 | """ |
| 1402 | c = self |
| 1403 | rv = False |
| 1404 | while c: |
| 1405 | if c.handlers: |
| 1406 | rv = True |
| 1407 | break |
| 1408 | if not c.propagate: |
| 1409 | break |
| 1410 | else: |
| 1411 | c = c.parent |
| 1412 | return rv |
| 1413 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1414 | def callHandlers(self, record): |
| 1415 | """ |
| 1416 | Pass a record to all relevant handlers. |
| 1417 | |
| 1418 | Loop through all handlers for this logger and its parents in the |
| 1419 | logger hierarchy. If no handler was found, output a one-off error |
| 1420 | message to sys.stderr. Stop searching up the hierarchy whenever a |
| 1421 | logger with the "propagate" attribute set to zero is found - that |
| 1422 | will be the last logger whose handlers are called. |
| 1423 | """ |
| 1424 | c = self |
| 1425 | found = 0 |
| 1426 | while c: |
| 1427 | for hdlr in c.handlers: |
| 1428 | found = found + 1 |
| 1429 | if record.levelno >= hdlr.level: |
| 1430 | hdlr.handle(record) |
| 1431 | if not c.propagate: |
| 1432 | c = None #break out |
| 1433 | else: |
| 1434 | c = c.parent |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1435 | if (found == 0): |
| 1436 | if lastResort: |
Vinay Sajip | 45dedaa | 2011-07-25 19:53:28 +0100 | [diff] [blame] | 1437 | if record.levelno >= lastResort.level: |
| 1438 | lastResort.handle(record) |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1439 | elif raiseExceptions and not self.manager.emittedNoHandlerWarning: |
| 1440 | sys.stderr.write("No handlers could be found for logger" |
| 1441 | " \"%s\"\n" % self.name) |
| 1442 | self.manager.emittedNoHandlerWarning = True |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1443 | |
| 1444 | def getEffectiveLevel(self): |
| 1445 | """ |
| 1446 | Get the effective level for this logger. |
| 1447 | |
| 1448 | Loop through this logger and its parents in the logger hierarchy, |
| 1449 | looking for a non-zero logging level. Return the first one found. |
| 1450 | """ |
| 1451 | logger = self |
| 1452 | while logger: |
| 1453 | if logger.level: |
| 1454 | return logger.level |
| 1455 | logger = logger.parent |
| 1456 | return NOTSET |
| 1457 | |
| 1458 | def isEnabledFor(self, level): |
| 1459 | """ |
| 1460 | Is this logger enabled for level 'level'? |
| 1461 | """ |
| 1462 | if self.manager.disable >= level: |
Vinay Sajip | 26fe4b7 | 2011-04-26 18:43:05 +0100 | [diff] [blame] | 1463 | return False |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1464 | return level >= self.getEffectiveLevel() |
| 1465 | |
Benjamin Peterson | 22005fc | 2010-04-11 16:25:06 +0000 | [diff] [blame] | 1466 | def getChild(self, suffix): |
| 1467 | """ |
| 1468 | Get a logger which is a descendant to this one. |
| 1469 | |
| 1470 | This is a convenience method, such that |
| 1471 | |
| 1472 | logging.getLogger('abc').getChild('def.ghi') |
| 1473 | |
| 1474 | is the same as |
| 1475 | |
| 1476 | logging.getLogger('abc.def.ghi') |
| 1477 | |
| 1478 | It's useful, for example, when the parent logger is named using |
| 1479 | __name__ rather than a literal string. |
| 1480 | """ |
| 1481 | if self.root is not self: |
| 1482 | suffix = '.'.join((self.name, suffix)) |
| 1483 | return self.manager.getLogger(suffix) |
| 1484 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1485 | class RootLogger(Logger): |
| 1486 | """ |
| 1487 | A root logger is not that different to any other logger, except that |
| 1488 | it must have a logging level and there is only one instance of it in |
| 1489 | the hierarchy. |
| 1490 | """ |
| 1491 | def __init__(self, level): |
| 1492 | """ |
| 1493 | Initialize the logger with the name "root". |
| 1494 | """ |
| 1495 | Logger.__init__(self, "root", level) |
| 1496 | |
| 1497 | _loggerClass = Logger |
| 1498 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 1499 | class LoggerAdapter(object): |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1500 | """ |
| 1501 | An adapter for loggers which makes it easier to specify contextual |
| 1502 | information in logging output. |
| 1503 | """ |
| 1504 | |
| 1505 | def __init__(self, logger, extra): |
| 1506 | """ |
| 1507 | Initialize the adapter with a logger and a dict-like object which |
| 1508 | provides contextual information. This constructor signature allows |
| 1509 | easy stacking of LoggerAdapters, if so desired. |
| 1510 | |
| 1511 | You can effectively pass keyword arguments as shown in the |
| 1512 | following example: |
| 1513 | |
| 1514 | adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2")) |
| 1515 | """ |
| 1516 | self.logger = logger |
| 1517 | self.extra = extra |
| 1518 | |
| 1519 | def process(self, msg, kwargs): |
| 1520 | """ |
| 1521 | Process the logging message and keyword arguments passed in to |
| 1522 | a logging call to insert contextual information. You can either |
| 1523 | manipulate the message itself, the keyword args or both. Return |
| 1524 | the message and kwargs modified (or not) to suit your needs. |
| 1525 | |
| 1526 | Normally, you'll only need to override this one method in a |
| 1527 | LoggerAdapter subclass for your specific needs. |
| 1528 | """ |
| 1529 | kwargs["extra"] = self.extra |
| 1530 | return msg, kwargs |
| 1531 | |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1532 | # |
| 1533 | # Boilerplate convenience methods |
| 1534 | # |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1535 | def debug(self, msg, *args, **kwargs): |
| 1536 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1537 | Delegate a debug call to the underlying logger. |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1538 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1539 | self.log(DEBUG, msg, *args, **kwargs) |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1540 | |
| 1541 | def info(self, msg, *args, **kwargs): |
| 1542 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1543 | Delegate an info call to the underlying logger. |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1544 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1545 | self.log(INFO, msg, *args, **kwargs) |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1546 | |
| 1547 | def warning(self, msg, *args, **kwargs): |
| 1548 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1549 | Delegate a warning call to the underlying logger. |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1550 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1551 | self.log(WARNING, msg, *args, **kwargs) |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1552 | |
Vinay Sajip | 04d5bc0 | 2011-10-21 07:33:42 +0100 | [diff] [blame] | 1553 | def warn(self, msg, *args, **kwargs): |
| 1554 | warnings.warn("The 'warn' method is deprecated, " |
Vinay Sajip | 0a88953 | 2011-10-22 13:34:48 +0100 | [diff] [blame] | 1555 | "use 'warning' instead", DeprecationWarning, 2) |
Vinay Sajip | 04d5bc0 | 2011-10-21 07:33:42 +0100 | [diff] [blame] | 1556 | self.warning(msg, *args, **kwargs) |
Vinay Sajip | c84f016 | 2010-09-21 11:25:39 +0000 | [diff] [blame] | 1557 | |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1558 | def error(self, msg, *args, **kwargs): |
| 1559 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1560 | Delegate an error call to the underlying logger. |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1561 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1562 | self.log(ERROR, msg, *args, **kwargs) |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1563 | |
| 1564 | def exception(self, msg, *args, **kwargs): |
| 1565 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1566 | Delegate an exception call to the underlying logger. |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1567 | """ |
Vinay Sajip | 312cc0d | 2011-04-30 21:51:51 +0100 | [diff] [blame] | 1568 | kwargs["exc_info"] = True |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1569 | self.log(ERROR, msg, *args, **kwargs) |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1570 | |
| 1571 | def critical(self, msg, *args, **kwargs): |
| 1572 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1573 | Delegate a critical call to the underlying logger. |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1574 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1575 | self.log(CRITICAL, msg, *args, **kwargs) |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1576 | |
| 1577 | def log(self, level, msg, *args, **kwargs): |
| 1578 | """ |
| 1579 | Delegate a log call to the underlying logger, after adding |
| 1580 | contextual information from this adapter instance. |
| 1581 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1582 | if self.isEnabledFor(level): |
| 1583 | msg, kwargs = self.process(msg, kwargs) |
| 1584 | self.logger._log(level, msg, args, **kwargs) |
| 1585 | |
| 1586 | def isEnabledFor(self, level): |
| 1587 | """ |
| 1588 | Is this logger enabled for level 'level'? |
| 1589 | """ |
| 1590 | if self.logger.manager.disable >= level: |
| 1591 | return False |
| 1592 | return level >= self.getEffectiveLevel() |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1593 | |
Vinay Sajip | c84f016 | 2010-09-21 11:25:39 +0000 | [diff] [blame] | 1594 | def setLevel(self, level): |
| 1595 | """ |
| 1596 | Set the specified level on the underlying logger. |
| 1597 | """ |
| 1598 | self.logger.setLevel(level) |
| 1599 | |
Vinay Sajip | c84f016 | 2010-09-21 11:25:39 +0000 | [diff] [blame] | 1600 | def getEffectiveLevel(self): |
| 1601 | """ |
| 1602 | Get the effective level for the underlying logger. |
| 1603 | """ |
| 1604 | return self.logger.getEffectiveLevel() |
| 1605 | |
Vinay Sajip | 61c3f0d | 2010-09-20 10:13:13 +0000 | [diff] [blame] | 1606 | def hasHandlers(self): |
| 1607 | """ |
| 1608 | See if the underlying logger has any handlers. |
| 1609 | """ |
| 1610 | return self.logger.hasHandlers() |
| 1611 | |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 1612 | root = RootLogger(WARNING) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1613 | Logger.root = root |
| 1614 | Logger.manager = Manager(Logger.root) |
| 1615 | |
| 1616 | #--------------------------------------------------------------------------- |
| 1617 | # Configuration classes and functions |
| 1618 | #--------------------------------------------------------------------------- |
| 1619 | |
| 1620 | BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s" |
| 1621 | |
Vinay Sajip | 779e0c9 | 2004-07-03 11:47:26 +0000 | [diff] [blame] | 1622 | def basicConfig(**kwargs): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1623 | """ |
Vinay Sajip | 779e0c9 | 2004-07-03 11:47:26 +0000 | [diff] [blame] | 1624 | Do basic configuration for the logging system. |
| 1625 | |
| 1626 | This function does nothing if the root logger already has handlers |
| 1627 | configured. It is a convenience method intended for use by simple scripts |
| 1628 | to do one-shot configuration of the logging package. |
| 1629 | |
| 1630 | The default behaviour is to create a StreamHandler which writes to |
| 1631 | sys.stderr, set a formatter using the BASIC_FORMAT format string, and |
| 1632 | add the handler to the root logger. |
| 1633 | |
| 1634 | A number of optional keyword arguments may be specified, which can alter |
| 1635 | the default behaviour. |
| 1636 | |
| 1637 | filename Specifies that a FileHandler be created, using the specified |
| 1638 | filename, rather than a StreamHandler. |
| 1639 | filemode Specifies the mode to open the file, if filename is specified |
Vinay Sajip | b89e7c9 | 2005-03-13 09:54:31 +0000 | [diff] [blame] | 1640 | (if filemode is unspecified, it defaults to 'a'). |
Vinay Sajip | 779e0c9 | 2004-07-03 11:47:26 +0000 | [diff] [blame] | 1641 | format Use the specified format string for the handler. |
| 1642 | datefmt Use the specified date/time format. |
Vinay Sajip | c5b2730 | 2010-10-31 14:59:16 +0000 | [diff] [blame] | 1643 | style If a format string is specified, use this to specify the |
| 1644 | type of format string (possible values '%', '{', '$', for |
| 1645 | %-formatting, :meth:`str.format` and :class:`string.Template` |
| 1646 | - defaults to '%'). |
Vinay Sajip | 779e0c9 | 2004-07-03 11:47:26 +0000 | [diff] [blame] | 1647 | level Set the root logger level to the specified level. |
| 1648 | stream Use the specified stream to initialize the StreamHandler. Note |
| 1649 | that this argument is incompatible with 'filename' - if both |
| 1650 | are present, 'stream' is ignored. |
Vinay Sajip | 4a0a31d | 2011-04-11 08:42:07 +0100 | [diff] [blame] | 1651 | handlers If specified, this should be an iterable of already created |
| 1652 | handlers, which will be added to the root handler. Any handler |
| 1653 | in the list which does not have a formatter assigned will be |
| 1654 | assigned the formatter created in this function. |
Vinay Sajip | 779e0c9 | 2004-07-03 11:47:26 +0000 | [diff] [blame] | 1655 | |
| 1656 | Note that you could specify a stream created using open(filename, mode) |
| 1657 | rather than passing the filename and mode in. However, it should be |
| 1658 | remembered that StreamHandler does not close its stream (since it may be |
| 1659 | using sys.stdout or sys.stderr), whereas FileHandler closes its stream |
| 1660 | when the handler is closed. |
Vinay Sajip | c5b2730 | 2010-10-31 14:59:16 +0000 | [diff] [blame] | 1661 | |
Vinay Sajip | 4a0a31d | 2011-04-11 08:42:07 +0100 | [diff] [blame] | 1662 | .. versionchanged:: 3.2 |
Vinay Sajip | c5b2730 | 2010-10-31 14:59:16 +0000 | [diff] [blame] | 1663 | Added the ``style`` parameter. |
Vinay Sajip | a3359ee | 2011-04-11 08:43:52 +0100 | [diff] [blame] | 1664 | |
Vinay Sajip | 4a0a31d | 2011-04-11 08:42:07 +0100 | [diff] [blame] | 1665 | .. versionchanged:: 3.3 |
| 1666 | Added the ``handlers`` parameter. A ``ValueError`` is now thrown for |
| 1667 | incompatible arguments (e.g. ``handlers`` specified together with |
| 1668 | ``filename``/``filemode``, or ``filename``/``filemode`` specified |
| 1669 | together with ``stream``, or ``handlers`` specified together with |
| 1670 | ``stream``. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1671 | """ |
Vinay Sajip | 2314fc7 | 2010-09-10 08:25:13 +0000 | [diff] [blame] | 1672 | # Add thread safety in case someone mistakenly calls |
| 1673 | # basicConfig() from multiple threads |
| 1674 | _acquireLock() |
| 1675 | try: |
| 1676 | if len(root.handlers) == 0: |
Vinay Sajip | 4a0a31d | 2011-04-11 08:42:07 +0100 | [diff] [blame] | 1677 | handlers = kwargs.get("handlers") |
| 1678 | if handlers is None: |
| 1679 | if "stream" in kwargs and "filename" in kwargs: |
| 1680 | raise ValueError("'stream' and 'filename' should not be " |
| 1681 | "specified together") |
Vinay Sajip | 2314fc7 | 2010-09-10 08:25:13 +0000 | [diff] [blame] | 1682 | else: |
Vinay Sajip | 4a0a31d | 2011-04-11 08:42:07 +0100 | [diff] [blame] | 1683 | if "stream" in kwargs or "filename" in kwargs: |
| 1684 | raise ValueError("'stream' or 'filename' should not be " |
| 1685 | "specified together with 'handlers'") |
| 1686 | if handlers is None: |
| 1687 | filename = kwargs.get("filename") |
| 1688 | if filename: |
| 1689 | mode = kwargs.get("filemode", 'a') |
| 1690 | h = FileHandler(filename, mode) |
| 1691 | else: |
| 1692 | stream = kwargs.get("stream") |
| 1693 | h = StreamHandler(stream) |
| 1694 | handlers = [h] |
Vinay Sajip | 2314fc7 | 2010-09-10 08:25:13 +0000 | [diff] [blame] | 1695 | fs = kwargs.get("format", BASIC_FORMAT) |
| 1696 | dfs = kwargs.get("datefmt", None) |
Vinay Sajip | c5b2730 | 2010-10-31 14:59:16 +0000 | [diff] [blame] | 1697 | style = kwargs.get("style", '%') |
| 1698 | fmt = Formatter(fs, dfs, style) |
Vinay Sajip | 4a0a31d | 2011-04-11 08:42:07 +0100 | [diff] [blame] | 1699 | for h in handlers: |
| 1700 | if h.formatter is None: |
| 1701 | h.setFormatter(fmt) |
| 1702 | root.addHandler(h) |
Vinay Sajip | 2314fc7 | 2010-09-10 08:25:13 +0000 | [diff] [blame] | 1703 | level = kwargs.get("level") |
| 1704 | if level is not None: |
| 1705 | root.setLevel(level) |
| 1706 | finally: |
| 1707 | _releaseLock() |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1708 | |
| 1709 | #--------------------------------------------------------------------------- |
| 1710 | # Utility functions at module level. |
| 1711 | # Basically delegate everything to the root logger. |
| 1712 | #--------------------------------------------------------------------------- |
| 1713 | |
| 1714 | def getLogger(name=None): |
| 1715 | """ |
| 1716 | Return a logger with the specified name, creating it if necessary. |
| 1717 | |
| 1718 | If no name is specified, return the root logger. |
| 1719 | """ |
| 1720 | if name: |
| 1721 | return Logger.manager.getLogger(name) |
| 1722 | else: |
| 1723 | return root |
| 1724 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1725 | def critical(msg, *args, **kwargs): |
| 1726 | """ |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1727 | Log a message with severity 'CRITICAL' on the root logger. If the logger |
| 1728 | has no handlers, call basicConfig() to add a console handler with a |
| 1729 | pre-defined format. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1730 | """ |
| 1731 | if len(root.handlers) == 0: |
| 1732 | basicConfig() |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1733 | root.critical(msg, *args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1734 | |
| 1735 | fatal = critical |
| 1736 | |
| 1737 | def error(msg, *args, **kwargs): |
| 1738 | """ |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1739 | Log a message with severity 'ERROR' on the root logger. If the logger has |
| 1740 | no handlers, call basicConfig() to add a console handler with a pre-defined |
| 1741 | format. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1742 | """ |
| 1743 | if len(root.handlers) == 0: |
| 1744 | basicConfig() |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1745 | root.error(msg, *args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1746 | |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1747 | def exception(msg, *args, **kwargs): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1748 | """ |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1749 | Log a message with severity 'ERROR' on the root logger, with exception |
| 1750 | information. If the logger has no handlers, basicConfig() is called to add |
| 1751 | a console handler with a pre-defined format. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1752 | """ |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1753 | kwargs['exc_info'] = True |
| 1754 | error(msg, *args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1755 | |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 1756 | def warning(msg, *args, **kwargs): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1757 | """ |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1758 | Log a message with severity 'WARNING' on the root logger. If the logger has |
| 1759 | no handlers, call basicConfig() to add a console handler with a pre-defined |
| 1760 | format. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1761 | """ |
| 1762 | if len(root.handlers) == 0: |
| 1763 | basicConfig() |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1764 | root.warning(msg, *args, **kwargs) |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 1765 | |
Vinay Sajip | 04d5bc0 | 2011-10-21 07:33:42 +0100 | [diff] [blame] | 1766 | def warn(msg, *args, **kwargs): |
| 1767 | warnings.warn("The 'warn' function is deprecated, " |
Vinay Sajip | 0a88953 | 2011-10-22 13:34:48 +0100 | [diff] [blame] | 1768 | "use 'warning' instead", DeprecationWarning, 2) |
Vinay Sajip | 04d5bc0 | 2011-10-21 07:33:42 +0100 | [diff] [blame] | 1769 | warning(msg, *args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1770 | |
| 1771 | def info(msg, *args, **kwargs): |
| 1772 | """ |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1773 | Log a message with severity 'INFO' on the root logger. If the logger has |
| 1774 | no handlers, call basicConfig() to add a console handler with a pre-defined |
| 1775 | format. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1776 | """ |
| 1777 | if len(root.handlers) == 0: |
| 1778 | basicConfig() |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1779 | root.info(msg, *args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1780 | |
| 1781 | def debug(msg, *args, **kwargs): |
| 1782 | """ |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1783 | Log a message with severity 'DEBUG' on the root logger. If the logger has |
| 1784 | no handlers, call basicConfig() to add a console handler with a pre-defined |
| 1785 | format. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1786 | """ |
| 1787 | if len(root.handlers) == 0: |
| 1788 | basicConfig() |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1789 | root.debug(msg, *args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1790 | |
Vinay Sajip | b2635b2 | 2004-09-24 11:45:52 +0000 | [diff] [blame] | 1791 | def log(level, msg, *args, **kwargs): |
| 1792 | """ |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1793 | Log 'msg % args' with the integer severity 'level' on the root logger. If |
| 1794 | the logger has no handlers, call basicConfig() to add a console handler |
| 1795 | with a pre-defined format. |
Vinay Sajip | b2635b2 | 2004-09-24 11:45:52 +0000 | [diff] [blame] | 1796 | """ |
| 1797 | if len(root.handlers) == 0: |
| 1798 | basicConfig() |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1799 | root.log(level, msg, *args, **kwargs) |
Vinay Sajip | b2635b2 | 2004-09-24 11:45:52 +0000 | [diff] [blame] | 1800 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1801 | def disable(level): |
| 1802 | """ |
Benjamin Peterson | 886af96 | 2010-03-21 23:13:07 +0000 | [diff] [blame] | 1803 | Disable all logging calls of severity 'level' and below. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1804 | """ |
| 1805 | root.manager.disable = level |
| 1806 | |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 1807 | def shutdown(handlerList=_handlerList): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1808 | """ |
| 1809 | Perform any cleanup actions in the logging system (e.g. flushing |
| 1810 | buffers). |
| 1811 | |
| 1812 | Should be called at application exit. |
| 1813 | """ |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 1814 | for wr in reversed(handlerList[:]): |
Vinay Sajip | e12f715 | 2004-07-29 09:19:30 +0000 | [diff] [blame] | 1815 | #errors might occur, for example, if files are locked |
Vinay Sajip | 260ce43 | 2006-02-09 08:34:14 +0000 | [diff] [blame] | 1816 | #we just ignore them if raiseExceptions is not set |
Vinay Sajip | e12f715 | 2004-07-29 09:19:30 +0000 | [diff] [blame] | 1817 | try: |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 1818 | h = wr() |
Vinay Sajip | de6e9d6 | 2010-08-23 17:50:30 +0000 | [diff] [blame] | 1819 | if h: |
| 1820 | try: |
Vinay Sajip | d9512e9 | 2011-03-08 22:53:21 +0000 | [diff] [blame] | 1821 | h.acquire() |
Vinay Sajip | de6e9d6 | 2010-08-23 17:50:30 +0000 | [diff] [blame] | 1822 | h.flush() |
| 1823 | h.close() |
| 1824 | except (IOError, ValueError): |
| 1825 | # Ignore errors which might be caused |
| 1826 | # because handlers have been closed but |
| 1827 | # references to them are still around at |
| 1828 | # application exit. |
| 1829 | pass |
Vinay Sajip | d9512e9 | 2011-03-08 22:53:21 +0000 | [diff] [blame] | 1830 | finally: |
| 1831 | h.release() |
Vinay Sajip | e12f715 | 2004-07-29 09:19:30 +0000 | [diff] [blame] | 1832 | except: |
Vinay Sajip | 260ce43 | 2006-02-09 08:34:14 +0000 | [diff] [blame] | 1833 | if raiseExceptions: |
| 1834 | raise |
| 1835 | #else, swallow |
Vinay Sajip | ed6bb14 | 2004-02-20 13:18:36 +0000 | [diff] [blame] | 1836 | |
| 1837 | #Let's try and shutdown automatically on application exit... |
Georg Brandl | 01e4d57 | 2010-02-06 22:27:51 +0000 | [diff] [blame] | 1838 | import atexit |
| 1839 | atexit.register(shutdown) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 1840 | |
| 1841 | # Null handler |
| 1842 | |
| 1843 | class NullHandler(Handler): |
| 1844 | """ |
| 1845 | This handler does nothing. It's intended to be used to avoid the |
| 1846 | "No handlers could be found for logger XXX" one-off warning. This is |
| 1847 | important for library code, which may contain code to log events. If a user |
| 1848 | of the library does not configure logging, the one-off warning might be |
| 1849 | produced; to avoid this, the library developer simply needs to instantiate |
| 1850 | a NullHandler and add it to the top-level logger of the library module or |
| 1851 | package. |
| 1852 | """ |
Vinay Sajip | 4fbe4b3 | 2010-09-26 11:04:10 +0000 | [diff] [blame] | 1853 | def handle(self, record): |
Vinay Sajip | e6c1eb9 | 2011-03-29 17:20:34 +0100 | [diff] [blame] | 1854 | """Stub.""" |
Vinay Sajip | 4fbe4b3 | 2010-09-26 11:04:10 +0000 | [diff] [blame] | 1855 | |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 1856 | def emit(self, record): |
Vinay Sajip | e6c1eb9 | 2011-03-29 17:20:34 +0100 | [diff] [blame] | 1857 | """Stub.""" |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 1858 | |
Vinay Sajip | 4fbe4b3 | 2010-09-26 11:04:10 +0000 | [diff] [blame] | 1859 | def createLock(self): |
| 1860 | self.lock = None |
| 1861 | |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 1862 | # Warnings integration |
| 1863 | |
| 1864 | _warnings_showwarning = None |
| 1865 | |
| 1866 | def _showwarning(message, category, filename, lineno, file=None, line=None): |
| 1867 | """ |
| 1868 | Implementation of showwarnings which redirects to logging, which will first |
| 1869 | check to see if the file parameter is None. If a file is specified, it will |
| 1870 | delegate to the original warnings implementation of showwarning. Otherwise, |
| 1871 | it will call warnings.formatwarning and will log the resulting string to a |
| 1872 | warnings logger named "py.warnings" with level logging.WARNING. |
| 1873 | """ |
| 1874 | if file is not None: |
| 1875 | if _warnings_showwarning is not None: |
| 1876 | _warnings_showwarning(message, category, filename, lineno, file, line) |
| 1877 | else: |
| 1878 | s = warnings.formatwarning(message, category, filename, lineno, line) |
| 1879 | logger = getLogger("py.warnings") |
| 1880 | if not logger.handlers: |
| 1881 | logger.addHandler(NullHandler()) |
| 1882 | logger.warning("%s", s) |
| 1883 | |
| 1884 | def captureWarnings(capture): |
| 1885 | """ |
| 1886 | If capture is true, redirect all warnings to the logging package. |
| 1887 | If capture is False, ensure that warnings are not redirected to logging |
| 1888 | but to their original destinations. |
| 1889 | """ |
| 1890 | global _warnings_showwarning |
| 1891 | if capture: |
| 1892 | if _warnings_showwarning is None: |
| 1893 | _warnings_showwarning = warnings.showwarning |
| 1894 | warnings.showwarning = _showwarning |
| 1895 | else: |
| 1896 | if _warnings_showwarning is not None: |
| 1897 | warnings.showwarning = _warnings_showwarning |
| 1898 | _warnings_showwarning = None |