Vinay Sajip | db81c4c | 2010-02-25 23:13:06 +0000 | [diff] [blame] | 1 | # Copyright 2001-2010 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 | |
Benjamin Peterson | 46a9900 | 2010-01-09 18:45:30 +0000 | [diff] [blame] | 21 | Copyright (C) 2001-2010 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: |
| 39 | import codecs |
| 40 | except ImportError: |
| 41 | codecs = None |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 42 | |
| 43 | try: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 44 | import _thread as thread |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 45 | import threading |
| 46 | except ImportError: |
| 47 | thread = None |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 48 | |
| 49 | __author__ = "Vinay Sajip <vinay_sajip@red-dove.com>" |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 50 | __status__ = "production" |
Vinay Sajip | db81c4c | 2010-02-25 23:13:06 +0000 | [diff] [blame] | 51 | __version__ = "0.5.1.2" |
| 52 | __date__ = "07 February 2010" |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 53 | |
| 54 | #--------------------------------------------------------------------------- |
| 55 | # Miscellaneous module data |
| 56 | #--------------------------------------------------------------------------- |
| 57 | |
| 58 | # |
Vinay Sajip | 829dc51 | 2005-02-18 11:53:32 +0000 | [diff] [blame] | 59 | # _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] | 60 | # caller stack frame. |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 61 | # |
Vinay Sajip | c384fc2 | 2005-09-02 11:20:33 +0000 | [diff] [blame] | 62 | if hasattr(sys, 'frozen'): #support for py2exe |
| 63 | _srcfile = "logging%s__init__%s" % (os.sep, __file__[-4:]) |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 64 | elif __file__[-4:].lower() in ['.pyc', '.pyo']: |
Guido van Rossum | 455ab77 | 2002-11-13 16:18:29 +0000 | [diff] [blame] | 65 | _srcfile = __file__[:-4] + '.py' |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 66 | else: |
Guido van Rossum | 455ab77 | 2002-11-13 16:18:29 +0000 | [diff] [blame] | 67 | _srcfile = __file__ |
| 68 | _srcfile = os.path.normcase(_srcfile) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 69 | |
Vinay Sajip | 829dc51 | 2005-02-18 11:53:32 +0000 | [diff] [blame] | 70 | # next bit filched from 1.5.2's inspect.py |
| 71 | def currentframe(): |
| 72 | """Return the frame object for the caller's stack frame.""" |
| 73 | try: |
Neal Norwitz | 1e8659b | 2005-10-21 06:00:24 +0000 | [diff] [blame] | 74 | raise Exception |
Vinay Sajip | 829dc51 | 2005-02-18 11:53:32 +0000 | [diff] [blame] | 75 | except: |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 76 | return sys.exc_info()[2].tb_frame.f_back |
Vinay Sajip | 829dc51 | 2005-02-18 11:53:32 +0000 | [diff] [blame] | 77 | |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 78 | if hasattr(sys, '_getframe'): currentframe = lambda: sys._getframe(3) |
Vinay Sajip | 829dc51 | 2005-02-18 11:53:32 +0000 | [diff] [blame] | 79 | # done filching |
| 80 | |
Jeremy Hylton | 250684d | 2003-01-23 18:29:29 +0000 | [diff] [blame] | 81 | # _srcfile is only used in conjunction with sys._getframe(). |
| 82 | # To provide compatibility with older versions of Python, set _srcfile |
| 83 | # to None if _getframe() is not available; this value will prevent |
| 84 | # findCaller() from being called. |
Vinay Sajip | 829dc51 | 2005-02-18 11:53:32 +0000 | [diff] [blame] | 85 | #if not hasattr(sys, "_getframe"): |
| 86 | # _srcfile = None |
Jeremy Hylton | 250684d | 2003-01-23 18:29:29 +0000 | [diff] [blame] | 87 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 88 | # |
| 89 | #_startTime is used as the base when calculating the relative time of events |
| 90 | # |
| 91 | _startTime = time.time() |
| 92 | |
| 93 | # |
| 94 | #raiseExceptions is used to see if exceptions during handling should be |
| 95 | #propagated |
| 96 | # |
| 97 | raiseExceptions = 1 |
| 98 | |
Vinay Sajip | d364a07 | 2006-03-13 22:05:28 +0000 | [diff] [blame] | 99 | # |
| 100 | # If you don't want threading information in the log, set this to zero |
| 101 | # |
| 102 | logThreads = 1 |
| 103 | |
| 104 | # |
Jesse Noller | 9a0fc97 | 2009-01-18 21:12:58 +0000 | [diff] [blame] | 105 | # If you don't want multiprocessing information in the log, set this to zero |
| 106 | # |
| 107 | logMultiprocessing = 1 |
| 108 | |
| 109 | # |
Vinay Sajip | d364a07 | 2006-03-13 22:05:28 +0000 | [diff] [blame] | 110 | # If you don't want process information in the log, set this to zero |
| 111 | # |
| 112 | logProcesses = 1 |
| 113 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 114 | #--------------------------------------------------------------------------- |
| 115 | # Level related stuff |
| 116 | #--------------------------------------------------------------------------- |
| 117 | # |
| 118 | # Default levels and level names, these can be replaced with any positive set |
| 119 | # of values having corresponding names. There is a pseudo-level, NOTSET, which |
| 120 | # is only really there as a lower limit for user-defined levels. Handlers and |
| 121 | # loggers are initialized with NOTSET so that they will log all messages, even |
| 122 | # at user-defined levels. |
| 123 | # |
Vinay Sajip | b89e7c9 | 2005-03-13 09:54:31 +0000 | [diff] [blame] | 124 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 125 | CRITICAL = 50 |
| 126 | FATAL = CRITICAL |
| 127 | ERROR = 40 |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 128 | WARNING = 30 |
| 129 | WARN = WARNING |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 130 | INFO = 20 |
| 131 | DEBUG = 10 |
| 132 | NOTSET = 0 |
| 133 | |
| 134 | _levelNames = { |
| 135 | CRITICAL : 'CRITICAL', |
| 136 | ERROR : 'ERROR', |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 137 | WARNING : 'WARNING', |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 138 | INFO : 'INFO', |
| 139 | DEBUG : 'DEBUG', |
| 140 | NOTSET : 'NOTSET', |
| 141 | 'CRITICAL' : CRITICAL, |
| 142 | 'ERROR' : ERROR, |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 143 | 'WARN' : WARNING, |
| 144 | 'WARNING' : WARNING, |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 145 | 'INFO' : INFO, |
| 146 | 'DEBUG' : DEBUG, |
| 147 | 'NOTSET' : NOTSET, |
| 148 | } |
| 149 | |
| 150 | def getLevelName(level): |
| 151 | """ |
| 152 | Return the textual representation of logging level 'level'. |
| 153 | |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 154 | 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] | 155 | INFO, DEBUG) then you get the corresponding string. If you have |
| 156 | associated levels with names using addLevelName then the name you have |
Vinay Sajip | 779e0c9 | 2004-07-03 11:47:26 +0000 | [diff] [blame] | 157 | associated with 'level' is returned. |
| 158 | |
| 159 | If a numeric value corresponding to one of the defined levels is passed |
| 160 | in, the corresponding string representation is returned. |
| 161 | |
| 162 | Otherwise, the string "Level %s" % level is returned. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 163 | """ |
| 164 | return _levelNames.get(level, ("Level %s" % level)) |
| 165 | |
| 166 | def addLevelName(level, levelName): |
| 167 | """ |
| 168 | Associate 'levelName' with 'level'. |
| 169 | |
| 170 | This is used when converting levels to text during message formatting. |
| 171 | """ |
| 172 | _acquireLock() |
| 173 | try: #unlikely to cause an exception, but you never know... |
| 174 | _levelNames[level] = levelName |
| 175 | _levelNames[levelName] = level |
| 176 | finally: |
| 177 | _releaseLock() |
| 178 | |
Vinay Sajip | d4fabf4 | 2009-07-13 11:28:25 +0000 | [diff] [blame] | 179 | def _checkLevel(level): |
| 180 | if isinstance(level, int): |
| 181 | rv = level |
| 182 | elif str(level) == level: |
| 183 | if level not in _levelNames: |
| 184 | raise ValueError("Unknown level: %r" % level) |
| 185 | rv = _levelNames[level] |
| 186 | else: |
| 187 | raise TypeError("Level not an integer or a valid string: %r" % level) |
| 188 | return rv |
| 189 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 190 | #--------------------------------------------------------------------------- |
| 191 | # Thread-related stuff |
| 192 | #--------------------------------------------------------------------------- |
| 193 | |
| 194 | # |
| 195 | #_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] | 196 | #This needs to be an RLock because fileConfig() creates and configures |
| 197 | #Handlers, and so might arbitrary user threads. Since Handler code updates the |
| 198 | #shared dictionary _handlers, it needs to acquire the lock. But if configuring, |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 199 | #the lock would already have been acquired - so we need an RLock. |
| 200 | #The same argument applies to Loggers and Manager.loggerDict. |
| 201 | # |
Vinay Sajip | 03f6c11 | 2009-11-27 14:03:36 +0000 | [diff] [blame] | 202 | if thread: |
| 203 | _lock = threading.RLock() |
| 204 | else: |
| 205 | _lock = None |
| 206 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 207 | |
| 208 | def _acquireLock(): |
| 209 | """ |
| 210 | Acquire the module-level lock for serializing access to shared data. |
| 211 | |
| 212 | This should be released with _releaseLock(). |
| 213 | """ |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 214 | if _lock: |
| 215 | _lock.acquire() |
| 216 | |
| 217 | def _releaseLock(): |
| 218 | """ |
| 219 | Release the module-level lock acquired by calling _acquireLock(). |
| 220 | """ |
| 221 | if _lock: |
| 222 | _lock.release() |
| 223 | |
| 224 | #--------------------------------------------------------------------------- |
| 225 | # The logging record |
| 226 | #--------------------------------------------------------------------------- |
| 227 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 228 | class LogRecord(object): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 229 | """ |
| 230 | A LogRecord instance represents an event being logged. |
| 231 | |
| 232 | LogRecord instances are created every time something is logged. They |
| 233 | contain all the information pertinent to the event being logged. The |
| 234 | main information passed in is in msg and args, which are combined |
| 235 | using str(msg) % args to create the message field of the record. The |
| 236 | record also includes information such as when the record was created, |
| 237 | the source line where the logging call was made, and any exception |
| 238 | information to be logged. |
| 239 | """ |
Vinay Sajip | ed1992f | 2006-02-09 08:48:36 +0000 | [diff] [blame] | 240 | def __init__(self, name, level, pathname, lineno, |
Vinay Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 241 | msg, args, exc_info, func=None, sinfo=None, **kwargs): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 242 | """ |
| 243 | Initialize a logging record with interesting information. |
| 244 | """ |
| 245 | ct = time.time() |
| 246 | self.name = name |
| 247 | self.msg = msg |
Vinay Sajip | 4ed315a | 2004-10-20 08:39:40 +0000 | [diff] [blame] | 248 | # |
| 249 | # The following statement allows passing of a dictionary as a sole |
| 250 | # argument, so that you can do something like |
| 251 | # logging.debug("a %(a)d b %(b)s", {'a':1, 'b':2}) |
| 252 | # Suggested by Stefan Behnel. |
| 253 | # Note that without the test for args[0], we get a problem because |
| 254 | # during formatting, we test to see if the arg is present using |
| 255 | # 'if self.args:'. If the event being logged is e.g. 'Value is %d' |
| 256 | # and if the passed arg fails 'if self.args:' then no formatting |
| 257 | # is done. For example, logger.warn('Value is %d', 0) would log |
| 258 | # 'Value is %d' instead of 'Value is 0'. |
| 259 | # For the use case of passing a dictionary, this should not be a |
| 260 | # problem. |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 261 | 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] | 262 | args = args[0] |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 263 | self.args = args |
| 264 | self.levelname = getLevelName(level) |
| 265 | self.levelno = level |
| 266 | self.pathname = pathname |
| 267 | try: |
| 268 | self.filename = os.path.basename(pathname) |
| 269 | self.module = os.path.splitext(self.filename)[0] |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 270 | except (TypeError, ValueError, AttributeError): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 271 | self.filename = pathname |
| 272 | self.module = "Unknown module" |
| 273 | self.exc_info = exc_info |
Vinay Sajip | ed6bb14 | 2004-02-20 13:18:36 +0000 | [diff] [blame] | 274 | self.exc_text = None # used to cache the traceback text |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 275 | self.stack_info = sinfo |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 276 | self.lineno = lineno |
Vinay Sajip | ed1992f | 2006-02-09 08:48:36 +0000 | [diff] [blame] | 277 | self.funcName = func |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 278 | self.created = ct |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 279 | self.msecs = (ct - int(ct)) * 1000 |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 280 | self.relativeCreated = (self.created - _startTime) * 1000 |
Vinay Sajip | d364a07 | 2006-03-13 22:05:28 +0000 | [diff] [blame] | 281 | if logThreads and thread: |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 282 | self.thread = thread.get_ident() |
Benjamin Peterson | 7275370 | 2008-08-18 18:09:21 +0000 | [diff] [blame] | 283 | self.threadName = threading.current_thread().name |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 284 | else: |
| 285 | self.thread = None |
Vinay Sajip | 4a70486 | 2005-03-31 20:16:55 +0000 | [diff] [blame] | 286 | self.threadName = None |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 287 | if not logMultiprocessing: |
Jesse Noller | 9a0fc97 | 2009-01-18 21:12:58 +0000 | [diff] [blame] | 288 | self.processName = None |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 289 | else: |
Benjamin Peterson | 22005fc | 2010-04-11 16:25:06 +0000 | [diff] [blame] | 290 | self.processName = 'MainProcess' |
| 291 | mp = sys.modules.get('multiprocessing') |
| 292 | if mp is not None: |
| 293 | # Errors may occur if multiprocessing has not finished loading |
| 294 | # yet - e.g. if a custom import hook causes third-party code |
| 295 | # to run when multiprocessing calls import. See issue 8200 |
| 296 | # for an example |
| 297 | try: |
| 298 | self.processName = mp.current_process().name |
| 299 | except StandardError: |
| 300 | pass |
Vinay Sajip | d364a07 | 2006-03-13 22:05:28 +0000 | [diff] [blame] | 301 | if logProcesses and hasattr(os, 'getpid'): |
Jack Jansen | 4c641d0 | 2003-02-21 22:29:45 +0000 | [diff] [blame] | 302 | self.process = os.getpid() |
| 303 | else: |
| 304 | self.process = None |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 305 | |
| 306 | def __str__(self): |
| 307 | return '<LogRecord: %s, %s, %s, %s, "%s">'%(self.name, self.levelno, |
| 308 | self.pathname, self.lineno, self.msg) |
| 309 | |
| 310 | def getMessage(self): |
| 311 | """ |
| 312 | Return the message for this LogRecord. |
| 313 | |
| 314 | Return the message for this LogRecord after merging any user-supplied |
| 315 | arguments with the message. |
| 316 | """ |
Vinay Sajip | dc5097f | 2010-08-31 07:52:17 +0000 | [diff] [blame] | 317 | msg = str(self.msg) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 318 | if self.args: |
| 319 | msg = msg % self.args |
| 320 | return msg |
| 321 | |
Vinay Sajip | 062d56b | 2010-10-19 15:26:24 +0000 | [diff] [blame] | 322 | # |
| 323 | # Determine which class to use when instantiating log records. |
| 324 | # |
Vinay Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 325 | _logRecordFactory = LogRecord |
Vinay Sajip | 062d56b | 2010-10-19 15:26:24 +0000 | [diff] [blame] | 326 | |
Vinay Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 327 | def setLogRecordFactory(factory): |
Vinay Sajip | 062d56b | 2010-10-19 15:26:24 +0000 | [diff] [blame] | 328 | """ |
Vinay Sajip | fad058f | 2010-12-03 13:01:11 +0000 | [diff] [blame] | 329 | Set the factory to be used when instantiating a log record. |
Vinay Sajip | 062d56b | 2010-10-19 15:26:24 +0000 | [diff] [blame] | 330 | |
Vinay Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 331 | :param factory: A callable which will be called to instantiate |
| 332 | a log record. |
| 333 | """ |
| 334 | global _logRecordFactory |
| 335 | _logRecordFactory = factory |
| 336 | |
| 337 | def getLogRecordFactory(): |
Vinay Sajip | 062d56b | 2010-10-19 15:26:24 +0000 | [diff] [blame] | 338 | """ |
Vinay Sajip | fad058f | 2010-12-03 13:01:11 +0000 | [diff] [blame] | 339 | Return the factory to be used when instantiating a log record. |
Vinay Sajip | 062d56b | 2010-10-19 15:26:24 +0000 | [diff] [blame] | 340 | """ |
| 341 | |
Vinay Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 342 | return _logRecordFactory |
Vinay Sajip | 062d56b | 2010-10-19 15:26:24 +0000 | [diff] [blame] | 343 | |
Raymond Hettinger | 6f3eaa6 | 2003-06-27 21:43:39 +0000 | [diff] [blame] | 344 | def makeLogRecord(dict): |
| 345 | """ |
| 346 | Make a LogRecord whose attributes are defined by the specified dictionary, |
| 347 | This function is useful for converting a logging event received over |
| 348 | a socket connection (which is sent as a dictionary) into a LogRecord |
| 349 | instance. |
| 350 | """ |
Vinay Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 351 | rv = _logRecordFactory(None, None, "", 0, "", (), None, None) |
Raymond Hettinger | 6f3eaa6 | 2003-06-27 21:43:39 +0000 | [diff] [blame] | 352 | rv.__dict__.update(dict) |
| 353 | return rv |
| 354 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 355 | #--------------------------------------------------------------------------- |
| 356 | # Formatter classes and functions |
| 357 | #--------------------------------------------------------------------------- |
| 358 | |
Vinay Sajip | 6a65c5d | 2010-10-26 13:16:11 +0000 | [diff] [blame] | 359 | class PercentStyle(object): |
| 360 | |
| 361 | default_format = '%(message)s' |
| 362 | asctime_format = '%(asctime)s' |
| 363 | |
| 364 | def __init__(self, fmt): |
| 365 | self._fmt = fmt or self.default_format |
| 366 | |
| 367 | def usesTime(self): |
| 368 | return self._fmt.find(self.asctime_format) >= 0 |
| 369 | |
| 370 | def format(self, record): |
| 371 | return self._fmt % record.__dict__ |
| 372 | |
| 373 | class StrFormatStyle(PercentStyle): |
| 374 | default_format = '{message}' |
| 375 | asctime_format = '{asctime}' |
| 376 | |
| 377 | def format(self, record): |
| 378 | return self._fmt.format(**record.__dict__) |
| 379 | |
| 380 | |
| 381 | class StringTemplateStyle(PercentStyle): |
| 382 | default_format = '${message}' |
| 383 | asctime_format = '${asctime}' |
| 384 | |
| 385 | def __init__(self, fmt): |
| 386 | self._fmt = fmt or self.default_format |
| 387 | self._tpl = Template(self._fmt) |
| 388 | |
| 389 | def usesTime(self): |
| 390 | fmt = self._fmt |
| 391 | return fmt.find('$asctime') >= 0 or fmt.find(self.asctime_format) >= 0 |
| 392 | |
| 393 | def format(self, record): |
| 394 | return self._tpl.substitute(**record.__dict__) |
| 395 | |
| 396 | _STYLES = { |
| 397 | '%': PercentStyle, |
| 398 | '{': StrFormatStyle, |
| 399 | '$': StringTemplateStyle |
| 400 | } |
| 401 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 402 | class Formatter(object): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 403 | """ |
| 404 | Formatter instances are used to convert a LogRecord to text. |
| 405 | |
| 406 | Formatters need to know how a LogRecord is constructed. They are |
| 407 | responsible for converting a LogRecord to (usually) a string which can |
| 408 | be interpreted by either a human or an external system. The base Formatter |
| 409 | allows a formatting string to be specified. If none is supplied, the |
Vinay Sajip | 2a20dfc | 2010-10-20 20:05:38 +0000 | [diff] [blame] | 410 | default value of "%s(message)" is used. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 411 | |
| 412 | The Formatter can be initialized with a format string which makes use of |
| 413 | knowledge of the LogRecord attributes - e.g. the default value mentioned |
| 414 | above makes use of the fact that the user's message and arguments are pre- |
| 415 | formatted into a LogRecord's message attribute. Currently, the useful |
| 416 | attributes in a LogRecord are described by: |
| 417 | |
| 418 | %(name)s Name of the logger (logging channel) |
| 419 | %(levelno)s Numeric logging level for the message (DEBUG, INFO, |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 420 | WARNING, ERROR, CRITICAL) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 421 | %(levelname)s Text logging level for the message ("DEBUG", "INFO", |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 422 | "WARNING", "ERROR", "CRITICAL") |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 423 | %(pathname)s Full pathname of the source file where the logging |
| 424 | call was issued (if available) |
| 425 | %(filename)s Filename portion of pathname |
| 426 | %(module)s Module (name portion of filename) |
| 427 | %(lineno)d Source line number where the logging call was issued |
| 428 | (if available) |
Vinay Sajip | ed1992f | 2006-02-09 08:48:36 +0000 | [diff] [blame] | 429 | %(funcName)s Function name |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 430 | %(created)f Time when the LogRecord was created (time.time() |
| 431 | return value) |
| 432 | %(asctime)s Textual time when the LogRecord was created |
| 433 | %(msecs)d Millisecond portion of the creation time |
| 434 | %(relativeCreated)d Time in milliseconds when the LogRecord was created, |
| 435 | relative to the time the logging module was loaded |
| 436 | (typically at application startup time) |
| 437 | %(thread)d Thread ID (if available) |
Vinay Sajip | 4a70486 | 2005-03-31 20:16:55 +0000 | [diff] [blame] | 438 | %(threadName)s Thread name (if available) |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 439 | %(process)d Process ID (if available) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 440 | %(message)s The result of record.getMessage(), computed just as |
| 441 | the record is emitted |
| 442 | """ |
| 443 | |
| 444 | converter = time.localtime |
| 445 | |
Vinay Sajip | a39c571 | 2010-10-25 13:57:39 +0000 | [diff] [blame] | 446 | def __init__(self, fmt=None, datefmt=None, style='%'): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 447 | """ |
| 448 | Initialize the formatter with specified format strings. |
| 449 | |
| 450 | Initialize the formatter either with the specified format string, or a |
| 451 | default as described above. Allow for specialized date formatting with |
| 452 | the optional datefmt argument (if omitted, you get the ISO8601 format). |
Vinay Sajip | a39c571 | 2010-10-25 13:57:39 +0000 | [diff] [blame] | 453 | |
| 454 | Use a style parameter of '%', '{' or '$' to specify that you want to |
| 455 | use one of %-formatting, :meth:`str.format` (``{}``) formatting or |
| 456 | :class:`string.Template` formatting in your format string. |
| 457 | |
| 458 | .. versionchanged: 3.2 |
| 459 | Added the ``style`` parameter. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 460 | """ |
Vinay Sajip | 6a65c5d | 2010-10-26 13:16:11 +0000 | [diff] [blame] | 461 | if style not in _STYLES: |
| 462 | raise ValueError('Style must be one of: %s' % ','.join( |
| 463 | _STYLES.keys())) |
| 464 | self._style = _STYLES[style](fmt) |
| 465 | self._fmt = self._style._fmt |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 466 | self.datefmt = datefmt |
| 467 | |
| 468 | def formatTime(self, record, datefmt=None): |
| 469 | """ |
| 470 | Return the creation time of the specified LogRecord as formatted text. |
| 471 | |
| 472 | This method should be called from format() by a formatter which |
| 473 | wants to make use of a formatted time. This method can be overridden |
| 474 | in formatters to provide for any specific requirement, but the |
| 475 | basic behaviour is as follows: if datefmt (a string) is specified, |
| 476 | it is used with time.strftime() to format the creation time of the |
| 477 | record. Otherwise, the ISO8601 format is used. The resulting |
| 478 | string is returned. This function uses a user-configurable function |
| 479 | to convert the creation time to a tuple. By default, time.localtime() |
| 480 | is used; to change this for a particular formatter instance, set the |
| 481 | 'converter' attribute to a function with the same signature as |
| 482 | time.localtime() or time.gmtime(). To change it for all formatters, |
| 483 | for example if you want all logging times to be shown in GMT, |
| 484 | set the 'converter' attribute in the Formatter class. |
| 485 | """ |
| 486 | ct = self.converter(record.created) |
| 487 | if datefmt: |
| 488 | s = time.strftime(datefmt, ct) |
| 489 | else: |
| 490 | t = time.strftime("%Y-%m-%d %H:%M:%S", ct) |
Vinay Sajip | a39c571 | 2010-10-25 13:57:39 +0000 | [diff] [blame] | 491 | s = "%s,%03d" % (t, record.msecs) # the use of % here is internal |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 492 | return s |
| 493 | |
| 494 | def formatException(self, ei): |
| 495 | """ |
| 496 | Format and return the specified exception information as a string. |
| 497 | |
| 498 | This default implementation just uses |
| 499 | traceback.print_exception() |
| 500 | """ |
Guido van Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 501 | sio = io.StringIO() |
Vinay Sajip | 40d9a4e | 2010-08-30 18:10:03 +0000 | [diff] [blame] | 502 | tb = ei[2] |
| 503 | # See issues #9427, #1553375. Commented out for now. |
| 504 | #if getattr(self, 'fullstack', False): |
| 505 | # traceback.print_stack(tb.tb_frame.f_back, file=sio) |
| 506 | traceback.print_exception(ei[0], ei[1], tb, None, sio) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 507 | s = sio.getvalue() |
| 508 | sio.close() |
Guido van Rossum | 486364b | 2007-06-30 05:01:58 +0000 | [diff] [blame] | 509 | if s[-1:] == "\n": |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 510 | s = s[:-1] |
| 511 | return s |
| 512 | |
Benjamin Peterson | 9451a1c | 2010-03-13 22:30:34 +0000 | [diff] [blame] | 513 | def usesTime(self): |
| 514 | """ |
| 515 | Check if the format uses the creation time of the record. |
| 516 | """ |
Vinay Sajip | 6a65c5d | 2010-10-26 13:16:11 +0000 | [diff] [blame] | 517 | return self._style.usesTime() |
Benjamin Peterson | 9451a1c | 2010-03-13 22:30:34 +0000 | [diff] [blame] | 518 | |
Vinay Sajip | d0557bf | 2010-10-25 15:25:24 +0000 | [diff] [blame] | 519 | def formatMessage(self, record): |
Vinay Sajip | 6a65c5d | 2010-10-26 13:16:11 +0000 | [diff] [blame] | 520 | return self._style.format(record) |
Vinay Sajip | d0557bf | 2010-10-25 15:25:24 +0000 | [diff] [blame] | 521 | |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 522 | def formatStack(self, stack_info): |
| 523 | """ |
| 524 | This method is provided as an extension point for specialized |
| 525 | formatting of stack information. |
| 526 | |
| 527 | The input data is a string as returned from a call to |
| 528 | :func:`traceback.print_stack`, but with the last trailing newline |
| 529 | removed. |
| 530 | |
| 531 | The base implementation just returns the value passed in. |
| 532 | """ |
| 533 | return stack_info |
| 534 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 535 | def format(self, record): |
| 536 | """ |
| 537 | Format the specified record as text. |
| 538 | |
| 539 | The record's attribute dictionary is used as the operand to a |
| 540 | string formatting operation which yields the returned string. |
| 541 | Before formatting the dictionary, a couple of preparatory steps |
| 542 | are carried out. The message attribute of the record is computed |
Benjamin Peterson | 9451a1c | 2010-03-13 22:30:34 +0000 | [diff] [blame] | 543 | using LogRecord.getMessage(). If the formatting string uses the |
| 544 | time (as determined by a call to usesTime(), formatTime() is |
| 545 | called to format the event time. If there is exception information, |
| 546 | it is formatted using formatException() and appended to the message. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 547 | """ |
| 548 | record.message = record.getMessage() |
Benjamin Peterson | 9451a1c | 2010-03-13 22:30:34 +0000 | [diff] [blame] | 549 | if self.usesTime(): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 550 | record.asctime = self.formatTime(record, self.datefmt) |
Vinay Sajip | d0557bf | 2010-10-25 15:25:24 +0000 | [diff] [blame] | 551 | s = self.formatMessage(record) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 552 | if record.exc_info: |
Vinay Sajip | ed6bb14 | 2004-02-20 13:18:36 +0000 | [diff] [blame] | 553 | # Cache the traceback text to avoid converting it multiple times |
| 554 | # (it's constant anyway) |
| 555 | if not record.exc_text: |
| 556 | record.exc_text = self.formatException(record.exc_info) |
| 557 | if record.exc_text: |
Guido van Rossum | 486364b | 2007-06-30 05:01:58 +0000 | [diff] [blame] | 558 | if s[-1:] != "\n": |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 559 | s = s + "\n" |
Vinay Sajip | ed6bb14 | 2004-02-20 13:18:36 +0000 | [diff] [blame] | 560 | s = s + record.exc_text |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 561 | if record.stack_info: |
| 562 | if s[-1:] != "\n": |
| 563 | s = s + "\n" |
| 564 | s = s + self.formatStack(record.stack_info) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 565 | return s |
| 566 | |
| 567 | # |
| 568 | # The default formatter to use when no other is specified |
| 569 | # |
| 570 | _defaultFormatter = Formatter() |
| 571 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 572 | class BufferingFormatter(object): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 573 | """ |
| 574 | A formatter suitable for formatting a number of records. |
| 575 | """ |
| 576 | def __init__(self, linefmt=None): |
| 577 | """ |
| 578 | Optionally specify a formatter which will be used to format each |
| 579 | individual record. |
| 580 | """ |
| 581 | if linefmt: |
| 582 | self.linefmt = linefmt |
| 583 | else: |
| 584 | self.linefmt = _defaultFormatter |
| 585 | |
| 586 | def formatHeader(self, records): |
| 587 | """ |
| 588 | Return the header string for the specified records. |
| 589 | """ |
| 590 | return "" |
| 591 | |
| 592 | def formatFooter(self, records): |
| 593 | """ |
| 594 | Return the footer string for the specified records. |
| 595 | """ |
| 596 | return "" |
| 597 | |
| 598 | def format(self, records): |
| 599 | """ |
| 600 | Format the specified records and return the result as a string. |
| 601 | """ |
| 602 | rv = "" |
| 603 | if len(records) > 0: |
| 604 | rv = rv + self.formatHeader(records) |
| 605 | for record in records: |
| 606 | rv = rv + self.linefmt.format(record) |
| 607 | rv = rv + self.formatFooter(records) |
| 608 | return rv |
| 609 | |
| 610 | #--------------------------------------------------------------------------- |
| 611 | # Filter classes and functions |
| 612 | #--------------------------------------------------------------------------- |
| 613 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 614 | class Filter(object): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 615 | """ |
| 616 | Filter instances are used to perform arbitrary filtering of LogRecords. |
| 617 | |
| 618 | Loggers and Handlers can optionally use Filter instances to filter |
| 619 | records as desired. The base filter class only allows events which are |
| 620 | below a certain point in the logger hierarchy. For example, a filter |
| 621 | initialized with "A.B" will allow events logged by loggers "A.B", |
| 622 | "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If |
| 623 | initialized with the empty string, all events are passed. |
| 624 | """ |
| 625 | def __init__(self, name=''): |
| 626 | """ |
| 627 | Initialize a filter. |
| 628 | |
| 629 | Initialize with the name of the logger which, together with its |
| 630 | children, will have its events allowed through the filter. If no |
| 631 | name is specified, allow every event. |
| 632 | """ |
| 633 | self.name = name |
| 634 | self.nlen = len(name) |
| 635 | |
| 636 | def filter(self, record): |
| 637 | """ |
| 638 | Determine if the specified record is to be logged. |
| 639 | |
| 640 | Is the specified record to be logged? Returns 0 for no, nonzero for |
| 641 | yes. If deemed appropriate, the record may be modified in-place. |
| 642 | """ |
| 643 | if self.nlen == 0: |
| 644 | return 1 |
| 645 | elif self.name == record.name: |
| 646 | return 1 |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 647 | elif record.name.find(self.name, 0, self.nlen) != 0: |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 648 | return 0 |
| 649 | return (record.name[self.nlen] == ".") |
| 650 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 651 | class Filterer(object): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 652 | """ |
| 653 | A base class for loggers and handlers which allows them to share |
| 654 | common code. |
| 655 | """ |
| 656 | def __init__(self): |
| 657 | """ |
| 658 | Initialize the list of filters to be an empty list. |
| 659 | """ |
| 660 | self.filters = [] |
| 661 | |
| 662 | def addFilter(self, filter): |
| 663 | """ |
| 664 | Add the specified filter to this handler. |
| 665 | """ |
| 666 | if not (filter in self.filters): |
| 667 | self.filters.append(filter) |
| 668 | |
| 669 | def removeFilter(self, filter): |
| 670 | """ |
| 671 | Remove the specified filter from this handler. |
| 672 | """ |
| 673 | if filter in self.filters: |
| 674 | self.filters.remove(filter) |
| 675 | |
| 676 | def filter(self, record): |
| 677 | """ |
| 678 | Determine if a record is loggable by consulting all the filters. |
| 679 | |
| 680 | The default is to allow the record to be logged; any filter can veto |
| 681 | this and the record is then dropped. Returns a zero value if a record |
| 682 | is to be dropped, else non-zero. |
Vinay Sajip | 6dbed2e | 2010-10-19 20:53:01 +0000 | [diff] [blame] | 683 | |
| 684 | .. versionchanged: 3.2 |
| 685 | |
| 686 | Allow filters to be just callables. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 687 | """ |
| 688 | rv = 1 |
| 689 | for f in self.filters: |
Vinay Sajip | 6dbed2e | 2010-10-19 20:53:01 +0000 | [diff] [blame] | 690 | if hasattr(f, 'filter'): |
| 691 | result = f.filter(record) |
Vinay Sajip | 6dbed2e | 2010-10-19 20:53:01 +0000 | [diff] [blame] | 692 | else: |
Vinay Sajip | fc082ca | 2010-10-19 21:13:49 +0000 | [diff] [blame] | 693 | result = f(record) # assume callable - will raise if not |
Vinay Sajip | 6dbed2e | 2010-10-19 20:53:01 +0000 | [diff] [blame] | 694 | if not result: |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 695 | rv = 0 |
| 696 | break |
| 697 | return rv |
| 698 | |
| 699 | #--------------------------------------------------------------------------- |
| 700 | # Handler classes and functions |
| 701 | #--------------------------------------------------------------------------- |
| 702 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 703 | _handlers = weakref.WeakValueDictionary() #map of handler names to handlers |
Vinay Sajip | 0ee9ba2 | 2005-09-08 18:14:16 +0000 | [diff] [blame] | 704 | _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] | 705 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 706 | def _removeHandlerRef(wr): |
| 707 | """ |
| 708 | Remove a handler reference from the internal cleanup list. |
| 709 | """ |
Vinay Sajip | de6e9d6 | 2010-08-23 17:50:30 +0000 | [diff] [blame] | 710 | # This function can be called during module teardown, when globals are |
| 711 | # set to None. If _acquireLock is None, assume this is the case and do |
| 712 | # nothing. |
| 713 | if _acquireLock is not None: |
| 714 | _acquireLock() |
| 715 | try: |
| 716 | if wr in _handlerList: |
| 717 | _handlerList.remove(wr) |
| 718 | finally: |
| 719 | _releaseLock() |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 720 | |
| 721 | def _addHandlerRef(handler): |
| 722 | """ |
| 723 | Add a handler to the internal cleanup list using a weak reference. |
| 724 | """ |
| 725 | _acquireLock() |
| 726 | try: |
| 727 | _handlerList.append(weakref.ref(handler, _removeHandlerRef)) |
| 728 | finally: |
| 729 | _releaseLock() |
| 730 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 731 | class Handler(Filterer): |
| 732 | """ |
| 733 | Handler instances dispatch logging events to specific destinations. |
| 734 | |
| 735 | The base handler class. Acts as a placeholder which defines the Handler |
| 736 | interface. Handlers can optionally use Formatter instances to format |
| 737 | records as desired. By default, no formatter is specified; in this case, |
| 738 | the 'raw' message as determined by record.message is logged. |
| 739 | """ |
| 740 | def __init__(self, level=NOTSET): |
| 741 | """ |
| 742 | Initializes the instance - basically setting the formatter to None |
| 743 | and the filter list to empty. |
| 744 | """ |
| 745 | Filterer.__init__(self) |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 746 | self._name = None |
Vinay Sajip | d4fabf4 | 2009-07-13 11:28:25 +0000 | [diff] [blame] | 747 | self.level = _checkLevel(level) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 748 | self.formatter = None |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 749 | # Add the handler to the global _handlerList (for cleanup on shutdown) |
| 750 | _addHandlerRef(self) |
| 751 | self.createLock() |
| 752 | |
| 753 | def get_name(self): |
| 754 | return self._name |
| 755 | |
| 756 | def set_name(self, name): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 757 | _acquireLock() |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 758 | try: |
| 759 | if self._name in _handlers: |
| 760 | del _handlers[self._name] |
| 761 | self._name = name |
| 762 | if name: |
| 763 | _handlers[name] = self |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 764 | finally: |
| 765 | _releaseLock() |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 766 | |
| 767 | name = property(get_name, set_name) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 768 | |
| 769 | def createLock(self): |
| 770 | """ |
| 771 | Acquire a thread lock for serializing access to the underlying I/O. |
| 772 | """ |
| 773 | if thread: |
Vinay Sajip | 4a70486 | 2005-03-31 20:16:55 +0000 | [diff] [blame] | 774 | self.lock = threading.RLock() |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 775 | else: |
| 776 | self.lock = None |
| 777 | |
| 778 | def acquire(self): |
| 779 | """ |
| 780 | Acquire the I/O thread lock. |
| 781 | """ |
| 782 | if self.lock: |
| 783 | self.lock.acquire() |
| 784 | |
| 785 | def release(self): |
| 786 | """ |
| 787 | Release the I/O thread lock. |
| 788 | """ |
| 789 | if self.lock: |
| 790 | self.lock.release() |
| 791 | |
| 792 | def setLevel(self, level): |
| 793 | """ |
| 794 | Set the logging level of this handler. |
| 795 | """ |
Vinay Sajip | d4fabf4 | 2009-07-13 11:28:25 +0000 | [diff] [blame] | 796 | self.level = _checkLevel(level) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 797 | |
| 798 | def format(self, record): |
| 799 | """ |
| 800 | Format the specified record. |
| 801 | |
| 802 | If a formatter is set, use it. Otherwise, use the default formatter |
| 803 | for the module. |
| 804 | """ |
| 805 | if self.formatter: |
| 806 | fmt = self.formatter |
| 807 | else: |
| 808 | fmt = _defaultFormatter |
| 809 | return fmt.format(record) |
| 810 | |
| 811 | def emit(self, record): |
| 812 | """ |
| 813 | Do whatever it takes to actually log the specified logging record. |
| 814 | |
| 815 | This version is intended to be implemented by subclasses and so |
| 816 | raises a NotImplementedError. |
| 817 | """ |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 818 | raise NotImplementedError('emit must be implemented ' |
| 819 | 'by Handler subclasses') |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 820 | |
| 821 | def handle(self, record): |
| 822 | """ |
| 823 | Conditionally emit the specified logging record. |
| 824 | |
| 825 | Emission depends on filters which may have been added to the handler. |
| 826 | Wrap the actual emission of the record with acquisition/release of |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 827 | the I/O thread lock. Returns whether the filter passed the record for |
| 828 | emission. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 829 | """ |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 830 | rv = self.filter(record) |
| 831 | if rv: |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 832 | self.acquire() |
| 833 | try: |
| 834 | self.emit(record) |
| 835 | finally: |
| 836 | self.release() |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 837 | return rv |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 838 | |
| 839 | def setFormatter(self, fmt): |
| 840 | """ |
| 841 | Set the formatter for this handler. |
| 842 | """ |
| 843 | self.formatter = fmt |
| 844 | |
| 845 | def flush(self): |
| 846 | """ |
| 847 | Ensure all logging output has been flushed. |
| 848 | |
| 849 | This version does nothing and is intended to be implemented by |
| 850 | subclasses. |
| 851 | """ |
| 852 | pass |
| 853 | |
| 854 | def close(self): |
| 855 | """ |
| 856 | Tidy up any resources used by the handler. |
| 857 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 858 | This version removes the handler from an internal map of handlers, |
| 859 | _handlers, which is used for handler lookup by name. Subclasses |
Vinay Sajip | ed6bb14 | 2004-02-20 13:18:36 +0000 | [diff] [blame] | 860 | should ensure that this gets called from overridden close() |
| 861 | methods. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 862 | """ |
Vinay Sajip | ed6bb14 | 2004-02-20 13:18:36 +0000 | [diff] [blame] | 863 | #get the module data lock, as we're updating a shared structure. |
| 864 | _acquireLock() |
| 865 | try: #unlikely to raise an exception, but you never know... |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 866 | if self._name and self._name in _handlers: |
| 867 | del _handlers[self._name] |
Vinay Sajip | ed6bb14 | 2004-02-20 13:18:36 +0000 | [diff] [blame] | 868 | finally: |
| 869 | _releaseLock() |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 870 | |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 871 | def handleError(self, record): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 872 | """ |
| 873 | Handle errors which occur during an emit() call. |
| 874 | |
| 875 | This method should be called from handlers when an exception is |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 876 | encountered during an emit() call. If raiseExceptions is false, |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 877 | exceptions get silently ignored. This is what is mostly wanted |
| 878 | for a logging system - most users will not care about errors in |
| 879 | the logging system, they are more interested in application errors. |
| 880 | You could, however, replace this with a custom handler if you wish. |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 881 | 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] | 882 | """ |
| 883 | if raiseExceptions: |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 884 | ei = sys.exc_info() |
Benjamin Peterson | fa0d703 | 2009-06-01 22:42:33 +0000 | [diff] [blame] | 885 | try: |
Vinay Sajip | db81c4c | 2010-02-25 23:13:06 +0000 | [diff] [blame] | 886 | traceback.print_exception(ei[0], ei[1], ei[2], |
| 887 | None, sys.stderr) |
| 888 | sys.stderr.write('Logged from file %s, line %s\n' % ( |
| 889 | record.filename, record.lineno)) |
Benjamin Peterson | fa0d703 | 2009-06-01 22:42:33 +0000 | [diff] [blame] | 890 | except IOError: |
| 891 | pass # see issue 5971 |
| 892 | finally: |
| 893 | del ei |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 894 | |
| 895 | class StreamHandler(Handler): |
| 896 | """ |
| 897 | A handler class which writes logging records, appropriately formatted, |
| 898 | to a stream. Note that this class does not close the stream, as |
| 899 | sys.stdout or sys.stderr may be used. |
| 900 | """ |
Benjamin Peterson | 3e4f055 | 2008-09-02 00:31:15 +0000 | [diff] [blame] | 901 | |
Vinay Sajip | 2a20dfc | 2010-10-20 20:05:38 +0000 | [diff] [blame] | 902 | terminator = '\n' |
| 903 | |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 904 | def __init__(self, stream=None): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 905 | """ |
| 906 | Initialize the handler. |
| 907 | |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 908 | If stream is not specified, sys.stderr is used. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 909 | """ |
| 910 | Handler.__init__(self) |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 911 | if stream is None: |
| 912 | stream = sys.stderr |
| 913 | self.stream = stream |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 914 | |
| 915 | def flush(self): |
| 916 | """ |
| 917 | Flushes the stream. |
| 918 | """ |
Amaury Forgeot d'Arc | 35c8658 | 2008-06-17 21:11:29 +0000 | [diff] [blame] | 919 | if self.stream and hasattr(self.stream, "flush"): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 920 | self.stream.flush() |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 921 | |
| 922 | def emit(self, record): |
| 923 | """ |
| 924 | Emit a record. |
| 925 | |
| 926 | If a formatter is specified, it is used to format the record. |
Benjamin Peterson | 3e4f055 | 2008-09-02 00:31:15 +0000 | [diff] [blame] | 927 | The record is then written to the stream with a trailing newline. If |
| 928 | exception information is present, it is formatted using |
| 929 | traceback.print_exception and appended to the stream. If the stream |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 930 | 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] | 931 | output to the stream. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 932 | """ |
| 933 | try: |
| 934 | msg = self.format(record) |
Benjamin Peterson | f91df04 | 2009-02-13 02:50:59 +0000 | [diff] [blame] | 935 | stream = self.stream |
Vinay Sajip | 2a20dfc | 2010-10-20 20:05:38 +0000 | [diff] [blame] | 936 | stream.write(msg) |
| 937 | stream.write(self.terminator) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 938 | self.flush() |
Vinay Sajip | 85c1909 | 2005-10-31 13:14:19 +0000 | [diff] [blame] | 939 | except (KeyboardInterrupt, SystemExit): |
| 940 | raise |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 941 | except: |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 942 | self.handleError(record) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 943 | |
| 944 | class FileHandler(StreamHandler): |
| 945 | """ |
| 946 | A handler class which writes formatted logging records to disk files. |
| 947 | """ |
Christian Heimes | e7a15bb | 2008-01-24 16:21:45 +0000 | [diff] [blame] | 948 | def __init__(self, filename, mode='a', encoding=None, delay=0): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 949 | """ |
| 950 | Open the specified file and use it as the stream for logging. |
| 951 | """ |
Vinay Sajip | 4bbab2b | 2004-07-08 10:22:35 +0000 | [diff] [blame] | 952 | #keep the absolute path, otherwise derived classes which use this |
| 953 | #may come a cropper when the current directory changes |
Thomas Wouters | fc7bb8c | 2007-01-15 15:49:28 +0000 | [diff] [blame] | 954 | if codecs is None: |
| 955 | encoding = None |
Vinay Sajip | 4bbab2b | 2004-07-08 10:22:35 +0000 | [diff] [blame] | 956 | self.baseFilename = os.path.abspath(filename) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 957 | self.mode = mode |
Thomas Wouters | fc7bb8c | 2007-01-15 15:49:28 +0000 | [diff] [blame] | 958 | self.encoding = encoding |
Christian Heimes | e7a15bb | 2008-01-24 16:21:45 +0000 | [diff] [blame] | 959 | if delay: |
Vinay Sajip | 6268cbc | 2009-01-21 00:19:28 +0000 | [diff] [blame] | 960 | #We don't open the stream, but we still need to call the |
| 961 | #Handler constructor to set level, formatter, lock etc. |
| 962 | Handler.__init__(self) |
Christian Heimes | e7a15bb | 2008-01-24 16:21:45 +0000 | [diff] [blame] | 963 | self.stream = None |
| 964 | else: |
Vinay Sajip | 6268cbc | 2009-01-21 00:19:28 +0000 | [diff] [blame] | 965 | StreamHandler.__init__(self, self._open()) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 966 | |
| 967 | def close(self): |
| 968 | """ |
| 969 | Closes the stream. |
| 970 | """ |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 971 | if self.stream: |
| 972 | self.flush() |
Amaury Forgeot d'Arc | 35c8658 | 2008-06-17 21:11:29 +0000 | [diff] [blame] | 973 | if hasattr(self.stream, "close"): |
| 974 | self.stream.close() |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 975 | StreamHandler.close(self) |
| 976 | self.stream = None |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 977 | |
Thomas Wouters | fc7bb8c | 2007-01-15 15:49:28 +0000 | [diff] [blame] | 978 | def _open(self): |
| 979 | """ |
| 980 | Open the current base file with the (original) mode and encoding. |
| 981 | Return the resulting stream. |
| 982 | """ |
| 983 | if self.encoding is None: |
| 984 | stream = open(self.baseFilename, self.mode) |
| 985 | else: |
| 986 | stream = codecs.open(self.baseFilename, self.mode, self.encoding) |
| 987 | return stream |
| 988 | |
Christian Heimes | e7a15bb | 2008-01-24 16:21:45 +0000 | [diff] [blame] | 989 | def emit(self, record): |
| 990 | """ |
| 991 | Emit a record. |
| 992 | |
| 993 | If the stream was not opened because 'delay' was specified in the |
| 994 | constructor, open it before calling the superclass's emit. |
| 995 | """ |
| 996 | if self.stream is None: |
Vinay Sajip | 6268cbc | 2009-01-21 00:19:28 +0000 | [diff] [blame] | 997 | self.stream = self._open() |
Christian Heimes | e7a15bb | 2008-01-24 16:21:45 +0000 | [diff] [blame] | 998 | StreamHandler.emit(self, record) |
| 999 | |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1000 | class _StderrHandler(StreamHandler): |
| 1001 | """ |
| 1002 | This class is like a StreamHandler using sys.stderr, but always uses |
| 1003 | whatever sys.stderr is currently set to rather than the value of |
| 1004 | sys.stderr at handler construction time. |
| 1005 | """ |
| 1006 | def __init__(self, level=NOTSET): |
| 1007 | """ |
| 1008 | Initialize the handler. |
| 1009 | """ |
| 1010 | Handler.__init__(self, level) |
| 1011 | |
| 1012 | @property |
| 1013 | def stream(self): |
| 1014 | return sys.stderr |
| 1015 | |
| 1016 | |
| 1017 | _defaultLastResort = _StderrHandler(WARNING) |
| 1018 | lastResort = _defaultLastResort |
| 1019 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1020 | #--------------------------------------------------------------------------- |
| 1021 | # Manager classes and functions |
| 1022 | #--------------------------------------------------------------------------- |
| 1023 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 1024 | class PlaceHolder(object): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1025 | """ |
| 1026 | PlaceHolder instances are used in the Manager logger hierarchy to take |
Vinay Sajip | 3f74284 | 2004-02-28 16:07:46 +0000 | [diff] [blame] | 1027 | the place of nodes for which no loggers have been defined. This class is |
| 1028 | intended for internal use only and not as part of the public API. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1029 | """ |
| 1030 | def __init__(self, alogger): |
| 1031 | """ |
| 1032 | Initialize with the specified logger being a child of this placeholder. |
| 1033 | """ |
Vinay Sajip | 239322b | 2005-10-14 09:36:35 +0000 | [diff] [blame] | 1034 | self.loggerMap = { alogger : None } |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1035 | |
| 1036 | def append(self, alogger): |
| 1037 | """ |
| 1038 | Add the specified logger as a child of this placeholder. |
| 1039 | """ |
Guido van Rossum | 9366241 | 2006-08-19 16:09:41 +0000 | [diff] [blame] | 1040 | if alogger not in self.loggerMap: |
Vinay Sajip | 239322b | 2005-10-14 09:36:35 +0000 | [diff] [blame] | 1041 | self.loggerMap[alogger] = None |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1042 | |
| 1043 | # |
| 1044 | # Determine which class to use when instantiating loggers. |
| 1045 | # |
| 1046 | _loggerClass = None |
| 1047 | |
| 1048 | def setLoggerClass(klass): |
| 1049 | """ |
| 1050 | Set the class to be used when instantiating a logger. The class should |
| 1051 | define __init__() such that only a name argument is required, and the |
| 1052 | __init__() should call Logger.__init__() |
| 1053 | """ |
| 1054 | if klass != Logger: |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1055 | if not issubclass(klass, Logger): |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 1056 | raise TypeError("logger not derived from logging.Logger: " |
| 1057 | + klass.__name__) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1058 | global _loggerClass |
| 1059 | _loggerClass = klass |
| 1060 | |
Vinay Sajip | b959117 | 2004-09-22 12:39:26 +0000 | [diff] [blame] | 1061 | def getLoggerClass(): |
| 1062 | """ |
| 1063 | Return the class to be used when instantiating a logger. |
| 1064 | """ |
| 1065 | |
| 1066 | return _loggerClass |
| 1067 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 1068 | class Manager(object): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1069 | """ |
| 1070 | There is [under normal circumstances] just one Manager instance, which |
| 1071 | holds the hierarchy of loggers. |
| 1072 | """ |
Neal Norwitz | d1cade0 | 2002-11-15 23:31:28 +0000 | [diff] [blame] | 1073 | def __init__(self, rootnode): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1074 | """ |
| 1075 | Initialize the manager with the root node of the logger hierarchy. |
| 1076 | """ |
Neal Norwitz | d1cade0 | 2002-11-15 23:31:28 +0000 | [diff] [blame] | 1077 | self.root = rootnode |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1078 | self.disable = 0 |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1079 | self.emittedNoHandlerWarning = False |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1080 | self.loggerDict = {} |
Vinay Sajip | db81c4c | 2010-02-25 23:13:06 +0000 | [diff] [blame] | 1081 | self.loggerClass = None |
Vinay Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 1082 | self.logRecordFactory = None |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1083 | |
| 1084 | def getLogger(self, name): |
| 1085 | """ |
| 1086 | Get a logger with the specified name (channel name), creating it |
Vinay Sajip | b959117 | 2004-09-22 12:39:26 +0000 | [diff] [blame] | 1087 | if it doesn't yet exist. This name is a dot-separated hierarchical |
| 1088 | name, such as "a", "a.b", "a.b.c" or similar. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1089 | |
| 1090 | If a PlaceHolder existed for the specified name [i.e. the logger |
| 1091 | didn't exist but a child of it did], replace it with the created |
| 1092 | logger and fix up the parent/child references which pointed to the |
| 1093 | placeholder to now point to the logger. |
| 1094 | """ |
| 1095 | rv = None |
| 1096 | _acquireLock() |
| 1097 | try: |
Guido van Rossum | 9366241 | 2006-08-19 16:09:41 +0000 | [diff] [blame] | 1098 | if name in self.loggerDict: |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1099 | rv = self.loggerDict[name] |
| 1100 | if isinstance(rv, PlaceHolder): |
| 1101 | ph = rv |
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._fixupChildren(ph, rv) |
| 1106 | self._fixupParents(rv) |
| 1107 | else: |
Vinay Sajip | db81c4c | 2010-02-25 23:13:06 +0000 | [diff] [blame] | 1108 | rv = (self.loggerClass or _loggerClass)(name) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1109 | rv.manager = self |
| 1110 | self.loggerDict[name] = rv |
| 1111 | self._fixupParents(rv) |
| 1112 | finally: |
| 1113 | _releaseLock() |
| 1114 | return rv |
| 1115 | |
Vinay Sajip | db81c4c | 2010-02-25 23:13:06 +0000 | [diff] [blame] | 1116 | def setLoggerClass(self, klass): |
| 1117 | """ |
| 1118 | Set the class to be used when instantiating a logger with this Manager. |
| 1119 | """ |
| 1120 | if klass != Logger: |
| 1121 | if not issubclass(klass, Logger): |
| 1122 | raise TypeError("logger not derived from logging.Logger: " |
| 1123 | + klass.__name__) |
| 1124 | self.loggerClass = klass |
| 1125 | |
Vinay Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 1126 | def setLogRecordFactory(self, factory): |
Vinay Sajip | 6fac817 | 2010-10-19 20:44:14 +0000 | [diff] [blame] | 1127 | """ |
Vinay Sajip | fad058f | 2010-12-03 13:01:11 +0000 | [diff] [blame] | 1128 | 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] | 1129 | Manager. |
| 1130 | """ |
Vinay Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 1131 | self.logRecordFactory = factory |
Vinay Sajip | 6fac817 | 2010-10-19 20:44:14 +0000 | [diff] [blame] | 1132 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1133 | def _fixupParents(self, alogger): |
| 1134 | """ |
| 1135 | Ensure that there are either loggers or placeholders all the way |
| 1136 | from the specified logger to the root of the logger hierarchy. |
| 1137 | """ |
| 1138 | name = alogger.name |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 1139 | i = name.rfind(".") |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1140 | rv = None |
| 1141 | while (i > 0) and not rv: |
| 1142 | substr = name[:i] |
Guido van Rossum | 9366241 | 2006-08-19 16:09:41 +0000 | [diff] [blame] | 1143 | if substr not in self.loggerDict: |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1144 | self.loggerDict[substr] = PlaceHolder(alogger) |
| 1145 | else: |
| 1146 | obj = self.loggerDict[substr] |
| 1147 | if isinstance(obj, Logger): |
| 1148 | rv = obj |
| 1149 | else: |
| 1150 | assert isinstance(obj, PlaceHolder) |
| 1151 | obj.append(alogger) |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 1152 | i = name.rfind(".", 0, i - 1) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1153 | if not rv: |
| 1154 | rv = self.root |
| 1155 | alogger.parent = rv |
| 1156 | |
| 1157 | def _fixupChildren(self, ph, alogger): |
| 1158 | """ |
| 1159 | Ensure that children of the placeholder ph are connected to the |
| 1160 | specified logger. |
| 1161 | """ |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1162 | name = alogger.name |
| 1163 | namelen = len(name) |
Vinay Sajip | 239322b | 2005-10-14 09:36:35 +0000 | [diff] [blame] | 1164 | for c in ph.loggerMap.keys(): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1165 | #The if means ... if not c.parent.name.startswith(nm) |
| 1166 | if c.parent.name[:namelen] != name: |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1167 | alogger.parent = c.parent |
| 1168 | c.parent = alogger |
| 1169 | |
| 1170 | #--------------------------------------------------------------------------- |
| 1171 | # Logger classes and functions |
| 1172 | #--------------------------------------------------------------------------- |
| 1173 | |
| 1174 | class Logger(Filterer): |
| 1175 | """ |
| 1176 | Instances of the Logger class represent a single logging channel. A |
| 1177 | "logging channel" indicates an area of an application. Exactly how an |
| 1178 | "area" is defined is up to the application developer. Since an |
| 1179 | application can have any number of areas, logging channels are identified |
| 1180 | by a unique string. Application areas can be nested (e.g. an area |
| 1181 | of "input processing" might include sub-areas "read CSV files", "read |
| 1182 | XLS files" and "read Gnumeric files"). To cater for this natural nesting, |
| 1183 | channel names are organized into a namespace hierarchy where levels are |
| 1184 | separated by periods, much like the Java or Python package namespace. So |
| 1185 | in the instance given above, channel names might be "input" for the upper |
| 1186 | level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels. |
| 1187 | There is no arbitrary limit to the depth of nesting. |
| 1188 | """ |
| 1189 | def __init__(self, name, level=NOTSET): |
| 1190 | """ |
| 1191 | Initialize the logger with a name and an optional level. |
| 1192 | """ |
| 1193 | Filterer.__init__(self) |
| 1194 | self.name = name |
Vinay Sajip | d4fabf4 | 2009-07-13 11:28:25 +0000 | [diff] [blame] | 1195 | self.level = _checkLevel(level) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1196 | self.parent = None |
| 1197 | self.propagate = 1 |
| 1198 | self.handlers = [] |
| 1199 | self.disabled = 0 |
| 1200 | |
| 1201 | def setLevel(self, level): |
| 1202 | """ |
| 1203 | Set the logging level of this logger. |
| 1204 | """ |
Vinay Sajip | d4fabf4 | 2009-07-13 11:28:25 +0000 | [diff] [blame] | 1205 | self.level = _checkLevel(level) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1206 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1207 | def debug(self, msg, *args, **kwargs): |
| 1208 | """ |
| 1209 | Log 'msg % args' with severity 'DEBUG'. |
| 1210 | |
| 1211 | To pass exception information, use the keyword argument exc_info with |
| 1212 | a true value, e.g. |
| 1213 | |
| 1214 | logger.debug("Houston, we have a %s", "thorny problem", exc_info=1) |
| 1215 | """ |
Guido van Rossum | 04110fb | 2007-08-24 16:32:05 +0000 | [diff] [blame] | 1216 | if self.isEnabledFor(DEBUG): |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1217 | self._log(DEBUG, msg, args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1218 | |
| 1219 | def info(self, msg, *args, **kwargs): |
| 1220 | """ |
| 1221 | Log 'msg % args' with severity 'INFO'. |
| 1222 | |
| 1223 | To pass exception information, use the keyword argument exc_info with |
| 1224 | a true value, e.g. |
| 1225 | |
| 1226 | logger.info("Houston, we have a %s", "interesting problem", exc_info=1) |
| 1227 | """ |
Guido van Rossum | 04110fb | 2007-08-24 16:32:05 +0000 | [diff] [blame] | 1228 | if self.isEnabledFor(INFO): |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1229 | self._log(INFO, msg, args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1230 | |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 1231 | def warning(self, msg, *args, **kwargs): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1232 | """ |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 1233 | Log 'msg % args' with severity 'WARNING'. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1234 | |
| 1235 | To pass exception information, use the keyword argument exc_info with |
| 1236 | a true value, e.g. |
| 1237 | |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 1238 | 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] | 1239 | """ |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 1240 | if self.isEnabledFor(WARNING): |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1241 | self._log(WARNING, msg, args, **kwargs) |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 1242 | |
| 1243 | warn = warning |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1244 | |
| 1245 | def error(self, msg, *args, **kwargs): |
| 1246 | """ |
| 1247 | Log 'msg % args' with severity 'ERROR'. |
| 1248 | |
| 1249 | To pass exception information, use the keyword argument exc_info with |
| 1250 | a true value, e.g. |
| 1251 | |
| 1252 | logger.error("Houston, we have a %s", "major problem", exc_info=1) |
| 1253 | """ |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1254 | if self.isEnabledFor(ERROR): |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1255 | self._log(ERROR, msg, args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1256 | |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1257 | def exception(self, msg, *args, **kwargs): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1258 | """ |
| 1259 | Convenience method for logging an ERROR with exception information. |
| 1260 | """ |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1261 | kwargs['exc_info'] = True |
| 1262 | self.error(msg, *args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1263 | |
| 1264 | def critical(self, msg, *args, **kwargs): |
| 1265 | """ |
| 1266 | Log 'msg % args' with severity 'CRITICAL'. |
| 1267 | |
| 1268 | To pass exception information, use the keyword argument exc_info with |
| 1269 | a true value, e.g. |
| 1270 | |
| 1271 | logger.critical("Houston, we have a %s", "major disaster", exc_info=1) |
| 1272 | """ |
Guido van Rossum | 04110fb | 2007-08-24 16:32:05 +0000 | [diff] [blame] | 1273 | if self.isEnabledFor(CRITICAL): |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1274 | self._log(CRITICAL, msg, args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1275 | |
| 1276 | fatal = critical |
| 1277 | |
| 1278 | def log(self, level, msg, *args, **kwargs): |
| 1279 | """ |
Vinay Sajip | eb477d0 | 2004-08-04 08:38:08 +0000 | [diff] [blame] | 1280 | Log 'msg % args' with the integer severity 'level'. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1281 | |
| 1282 | To pass exception information, use the keyword argument exc_info with |
| 1283 | a true value, e.g. |
| 1284 | |
| 1285 | logger.log(level, "We have a %s", "mysterious problem", exc_info=1) |
| 1286 | """ |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 1287 | if not isinstance(level, int): |
Vinay Sajip | 779e0c9 | 2004-07-03 11:47:26 +0000 | [diff] [blame] | 1288 | if raiseExceptions: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 1289 | raise TypeError("level must be an integer") |
Vinay Sajip | 779e0c9 | 2004-07-03 11:47:26 +0000 | [diff] [blame] | 1290 | else: |
| 1291 | return |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1292 | if self.isEnabledFor(level): |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1293 | self._log(level, msg, args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1294 | |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1295 | def findCaller(self, stack_info=False): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1296 | """ |
| 1297 | 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] | 1298 | file name, line number and function name. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1299 | """ |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 1300 | f = currentframe() |
| 1301 | #On some versions of IronPython, currentframe() returns None if |
| 1302 | #IronPython isn't run with -X:Frames. |
| 1303 | if f is not None: |
| 1304 | f = f.f_back |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1305 | rv = "(unknown file)", 0, "(unknown function)", None |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 1306 | while hasattr(f, "f_code"): |
Jeremy Hylton | 250684d | 2003-01-23 18:29:29 +0000 | [diff] [blame] | 1307 | co = f.f_code |
| 1308 | filename = os.path.normcase(co.co_filename) |
| 1309 | if filename == _srcfile: |
| 1310 | f = f.f_back |
| 1311 | continue |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1312 | sinfo = None |
| 1313 | if stack_info: |
| 1314 | sio = io.StringIO() |
| 1315 | sio.write('Stack (most recent call last):\n') |
| 1316 | traceback.print_stack(f, file=sio) |
| 1317 | sinfo = sio.getvalue() |
| 1318 | if sinfo[-1] == '\n': |
| 1319 | sinfo = sinfo[:-1] |
| 1320 | sio.close() |
| 1321 | rv = (co.co_filename, f.f_lineno, co.co_name, sinfo) |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 1322 | break |
| 1323 | return rv |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1324 | |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1325 | def makeRecord(self, name, level, fn, lno, msg, args, exc_info, |
| 1326 | func=None, extra=None, sinfo=None): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1327 | """ |
| 1328 | A factory method which can be overridden in subclasses to create |
| 1329 | specialized LogRecords. |
| 1330 | """ |
Vinay Sajip | 6156152 | 2010-12-03 11:50:38 +0000 | [diff] [blame] | 1331 | rv = _logRecordFactory(name, level, fn, lno, msg, args, exc_info, func, |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1332 | sinfo) |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1333 | if extra is not None: |
Vinay Sajip | 260ce43 | 2006-02-09 08:34:14 +0000 | [diff] [blame] | 1334 | for key in extra: |
| 1335 | if (key in ["message", "asctime"]) or (key in rv.__dict__): |
| 1336 | raise KeyError("Attempt to overwrite %r in LogRecord" % key) |
| 1337 | rv.__dict__[key] = extra[key] |
| 1338 | return rv |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1339 | |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1340 | 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] | 1341 | """ |
| 1342 | Low-level logging routine which creates a LogRecord and then calls |
| 1343 | all the handlers of this logger to handle the record. |
| 1344 | """ |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1345 | sinfo = None |
Jeremy Hylton | 250684d | 2003-01-23 18:29:29 +0000 | [diff] [blame] | 1346 | if _srcfile: |
Vinay Sajip | b672b6d | 2009-02-19 12:36:11 +0000 | [diff] [blame] | 1347 | #IronPython doesn't track Python frames, so findCaller throws an |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 1348 | #exception on some versions of IronPython. We trap it here so that |
| 1349 | #IronPython can use logging. |
Vinay Sajip | b672b6d | 2009-02-19 12:36:11 +0000 | [diff] [blame] | 1350 | try: |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1351 | fn, lno, func, sinfo = self.findCaller(stack_info) |
Vinay Sajip | b672b6d | 2009-02-19 12:36:11 +0000 | [diff] [blame] | 1352 | except ValueError: |
| 1353 | fn, lno, func = "(unknown file)", 0, "(unknown function)" |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1354 | else: |
Vinay Sajip | 829dc51 | 2005-02-18 11:53:32 +0000 | [diff] [blame] | 1355 | fn, lno, func = "(unknown file)", 0, "(unknown function)" |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1356 | if exc_info: |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 1357 | if not isinstance(exc_info, tuple): |
Vinay Sajip | ed6bb14 | 2004-02-20 13:18:36 +0000 | [diff] [blame] | 1358 | exc_info = sys.exc_info() |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1359 | record = self.makeRecord(self.name, level, fn, lno, msg, args, |
| 1360 | exc_info, func, extra, sinfo) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1361 | self.handle(record) |
| 1362 | |
| 1363 | def handle(self, record): |
| 1364 | """ |
| 1365 | Call the handlers for the specified record. |
| 1366 | |
| 1367 | This method is used for unpickled records received from a socket, as |
| 1368 | well as those created locally. Logger-level filtering is applied. |
| 1369 | """ |
| 1370 | if (not self.disabled) and self.filter(record): |
| 1371 | self.callHandlers(record) |
| 1372 | |
| 1373 | def addHandler(self, hdlr): |
| 1374 | """ |
| 1375 | Add the specified handler to this logger. |
| 1376 | """ |
Vinay Sajip | 32fb6a8 | 2010-09-25 17:42:36 +0000 | [diff] [blame] | 1377 | _acquireLock() |
| 1378 | try: |
| 1379 | if not (hdlr in self.handlers): |
| 1380 | self.handlers.append(hdlr) |
| 1381 | finally: |
| 1382 | _releaseLock() |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1383 | |
| 1384 | def removeHandler(self, hdlr): |
| 1385 | """ |
| 1386 | Remove the specified handler from this logger. |
| 1387 | """ |
Vinay Sajip | 32fb6a8 | 2010-09-25 17:42:36 +0000 | [diff] [blame] | 1388 | _acquireLock() |
| 1389 | try: |
| 1390 | if hdlr in self.handlers: |
Vinay Sajip | 116f16e | 2005-09-16 10:33:40 +0000 | [diff] [blame] | 1391 | self.handlers.remove(hdlr) |
Vinay Sajip | 32fb6a8 | 2010-09-25 17:42:36 +0000 | [diff] [blame] | 1392 | finally: |
| 1393 | _releaseLock() |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1394 | |
Vinay Sajip | b4a0809 | 2010-09-20 09:55:00 +0000 | [diff] [blame] | 1395 | def hasHandlers(self): |
| 1396 | """ |
| 1397 | See if this logger has any handlers configured. |
| 1398 | |
| 1399 | Loop through all handlers for this logger and its parents in the |
| 1400 | logger hierarchy. Return True if a handler was found, else False. |
| 1401 | Stop searching up the hierarchy whenever a logger with the "propagate" |
| 1402 | attribute set to zero is found - that will be the last logger which |
| 1403 | is checked for the existence of handlers. |
| 1404 | """ |
| 1405 | c = self |
| 1406 | rv = False |
| 1407 | while c: |
| 1408 | if c.handlers: |
| 1409 | rv = True |
| 1410 | break |
| 1411 | if not c.propagate: |
| 1412 | break |
| 1413 | else: |
| 1414 | c = c.parent |
| 1415 | return rv |
| 1416 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1417 | def callHandlers(self, record): |
| 1418 | """ |
| 1419 | Pass a record to all relevant handlers. |
| 1420 | |
| 1421 | Loop through all handlers for this logger and its parents in the |
| 1422 | logger hierarchy. If no handler was found, output a one-off error |
| 1423 | message to sys.stderr. Stop searching up the hierarchy whenever a |
| 1424 | logger with the "propagate" attribute set to zero is found - that |
| 1425 | will be the last logger whose handlers are called. |
| 1426 | """ |
| 1427 | c = self |
| 1428 | found = 0 |
| 1429 | while c: |
| 1430 | for hdlr in c.handlers: |
| 1431 | found = found + 1 |
| 1432 | if record.levelno >= hdlr.level: |
| 1433 | hdlr.handle(record) |
| 1434 | if not c.propagate: |
| 1435 | c = None #break out |
| 1436 | else: |
| 1437 | c = c.parent |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1438 | if (found == 0): |
| 1439 | if lastResort: |
| 1440 | lastResort.handle(record) |
| 1441 | elif raiseExceptions and not self.manager.emittedNoHandlerWarning: |
| 1442 | sys.stderr.write("No handlers could be found for logger" |
| 1443 | " \"%s\"\n" % self.name) |
| 1444 | self.manager.emittedNoHandlerWarning = True |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1445 | |
| 1446 | def getEffectiveLevel(self): |
| 1447 | """ |
| 1448 | Get the effective level for this logger. |
| 1449 | |
| 1450 | Loop through this logger and its parents in the logger hierarchy, |
| 1451 | looking for a non-zero logging level. Return the first one found. |
| 1452 | """ |
| 1453 | logger = self |
| 1454 | while logger: |
| 1455 | if logger.level: |
| 1456 | return logger.level |
| 1457 | logger = logger.parent |
| 1458 | return NOTSET |
| 1459 | |
| 1460 | def isEnabledFor(self, level): |
| 1461 | """ |
| 1462 | Is this logger enabled for level 'level'? |
| 1463 | """ |
| 1464 | if self.manager.disable >= level: |
| 1465 | return 0 |
| 1466 | return level >= self.getEffectiveLevel() |
| 1467 | |
Benjamin Peterson | 22005fc | 2010-04-11 16:25:06 +0000 | [diff] [blame] | 1468 | def getChild(self, suffix): |
| 1469 | """ |
| 1470 | Get a logger which is a descendant to this one. |
| 1471 | |
| 1472 | This is a convenience method, such that |
| 1473 | |
| 1474 | logging.getLogger('abc').getChild('def.ghi') |
| 1475 | |
| 1476 | is the same as |
| 1477 | |
| 1478 | logging.getLogger('abc.def.ghi') |
| 1479 | |
| 1480 | It's useful, for example, when the parent logger is named using |
| 1481 | __name__ rather than a literal string. |
| 1482 | """ |
| 1483 | if self.root is not self: |
| 1484 | suffix = '.'.join((self.name, suffix)) |
| 1485 | return self.manager.getLogger(suffix) |
| 1486 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1487 | class RootLogger(Logger): |
| 1488 | """ |
| 1489 | A root logger is not that different to any other logger, except that |
| 1490 | it must have a logging level and there is only one instance of it in |
| 1491 | the hierarchy. |
| 1492 | """ |
| 1493 | def __init__(self, level): |
| 1494 | """ |
| 1495 | Initialize the logger with the name "root". |
| 1496 | """ |
| 1497 | Logger.__init__(self, "root", level) |
| 1498 | |
| 1499 | _loggerClass = Logger |
| 1500 | |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 1501 | class LoggerAdapter(object): |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1502 | """ |
| 1503 | An adapter for loggers which makes it easier to specify contextual |
| 1504 | information in logging output. |
| 1505 | """ |
| 1506 | |
| 1507 | def __init__(self, logger, extra): |
| 1508 | """ |
| 1509 | Initialize the adapter with a logger and a dict-like object which |
| 1510 | provides contextual information. This constructor signature allows |
| 1511 | easy stacking of LoggerAdapters, if so desired. |
| 1512 | |
| 1513 | You can effectively pass keyword arguments as shown in the |
| 1514 | following example: |
| 1515 | |
| 1516 | adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2")) |
| 1517 | """ |
| 1518 | self.logger = logger |
| 1519 | self.extra = extra |
| 1520 | |
| 1521 | def process(self, msg, kwargs): |
| 1522 | """ |
| 1523 | Process the logging message and keyword arguments passed in to |
| 1524 | a logging call to insert contextual information. You can either |
| 1525 | manipulate the message itself, the keyword args or both. Return |
| 1526 | the message and kwargs modified (or not) to suit your needs. |
| 1527 | |
| 1528 | Normally, you'll only need to override this one method in a |
| 1529 | LoggerAdapter subclass for your specific needs. |
| 1530 | """ |
| 1531 | kwargs["extra"] = self.extra |
| 1532 | return msg, kwargs |
| 1533 | |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1534 | # |
| 1535 | # Boilerplate convenience methods |
| 1536 | # |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1537 | def debug(self, msg, *args, **kwargs): |
| 1538 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1539 | Delegate a debug call to the underlying logger. |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1540 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1541 | self.log(DEBUG, msg, *args, **kwargs) |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1542 | |
| 1543 | def info(self, msg, *args, **kwargs): |
| 1544 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1545 | Delegate an info call to the underlying logger. |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1546 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1547 | self.log(INFO, msg, *args, **kwargs) |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1548 | |
| 1549 | def warning(self, msg, *args, **kwargs): |
| 1550 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1551 | Delegate a warning call to the underlying logger. |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1552 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1553 | self.log(WARNING, msg, *args, **kwargs) |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1554 | |
Vinay Sajip | c84f016 | 2010-09-21 11:25:39 +0000 | [diff] [blame] | 1555 | warn = warning |
| 1556 | |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1557 | def error(self, msg, *args, **kwargs): |
| 1558 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1559 | Delegate an error call to the underlying logger. |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1560 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1561 | self.log(ERROR, msg, *args, **kwargs) |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1562 | |
| 1563 | def exception(self, msg, *args, **kwargs): |
| 1564 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1565 | Delegate an exception call to the underlying logger. |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1566 | """ |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1567 | kwargs["exc_info"] = 1 |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1568 | self.log(ERROR, msg, *args, **kwargs) |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1569 | |
| 1570 | def critical(self, msg, *args, **kwargs): |
| 1571 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1572 | Delegate a critical call to the underlying logger. |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1573 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1574 | self.log(CRITICAL, msg, *args, **kwargs) |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1575 | |
| 1576 | def log(self, level, msg, *args, **kwargs): |
| 1577 | """ |
| 1578 | Delegate a log call to the underlying logger, after adding |
| 1579 | contextual information from this adapter instance. |
| 1580 | """ |
Vinay Sajip | 212b590 | 2010-09-21 11:31:32 +0000 | [diff] [blame] | 1581 | if self.isEnabledFor(level): |
| 1582 | msg, kwargs = self.process(msg, kwargs) |
| 1583 | self.logger._log(level, msg, args, **kwargs) |
| 1584 | |
| 1585 | def isEnabledFor(self, level): |
| 1586 | """ |
| 1587 | Is this logger enabled for level 'level'? |
| 1588 | """ |
| 1589 | if self.logger.manager.disable >= level: |
| 1590 | return False |
| 1591 | return level >= self.getEffectiveLevel() |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 1592 | |
Vinay Sajip | c84f016 | 2010-09-21 11:25:39 +0000 | [diff] [blame] | 1593 | def setLevel(self, level): |
| 1594 | """ |
| 1595 | Set the specified level on the underlying logger. |
| 1596 | """ |
| 1597 | self.logger.setLevel(level) |
| 1598 | |
Vinay Sajip | c84f016 | 2010-09-21 11:25:39 +0000 | [diff] [blame] | 1599 | def getEffectiveLevel(self): |
| 1600 | """ |
| 1601 | Get the effective level for the underlying logger. |
| 1602 | """ |
| 1603 | return self.logger.getEffectiveLevel() |
| 1604 | |
Vinay Sajip | 61c3f0d | 2010-09-20 10:13:13 +0000 | [diff] [blame] | 1605 | def hasHandlers(self): |
| 1606 | """ |
| 1607 | See if the underlying logger has any handlers. |
| 1608 | """ |
| 1609 | return self.logger.hasHandlers() |
| 1610 | |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 1611 | root = RootLogger(WARNING) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1612 | Logger.root = root |
| 1613 | Logger.manager = Manager(Logger.root) |
| 1614 | |
| 1615 | #--------------------------------------------------------------------------- |
| 1616 | # Configuration classes and functions |
| 1617 | #--------------------------------------------------------------------------- |
| 1618 | |
| 1619 | BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s" |
| 1620 | |
Vinay Sajip | 779e0c9 | 2004-07-03 11:47:26 +0000 | [diff] [blame] | 1621 | def basicConfig(**kwargs): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1622 | """ |
Vinay Sajip | 779e0c9 | 2004-07-03 11:47:26 +0000 | [diff] [blame] | 1623 | Do basic configuration for the logging system. |
| 1624 | |
| 1625 | This function does nothing if the root logger already has handlers |
| 1626 | configured. It is a convenience method intended for use by simple scripts |
| 1627 | to do one-shot configuration of the logging package. |
| 1628 | |
| 1629 | The default behaviour is to create a StreamHandler which writes to |
| 1630 | sys.stderr, set a formatter using the BASIC_FORMAT format string, and |
| 1631 | add the handler to the root logger. |
| 1632 | |
| 1633 | A number of optional keyword arguments may be specified, which can alter |
| 1634 | the default behaviour. |
| 1635 | |
| 1636 | filename Specifies that a FileHandler be created, using the specified |
| 1637 | filename, rather than a StreamHandler. |
| 1638 | filemode Specifies the mode to open the file, if filename is specified |
Vinay Sajip | b89e7c9 | 2005-03-13 09:54:31 +0000 | [diff] [blame] | 1639 | (if filemode is unspecified, it defaults to 'a'). |
Vinay Sajip | 779e0c9 | 2004-07-03 11:47:26 +0000 | [diff] [blame] | 1640 | format Use the specified format string for the handler. |
| 1641 | datefmt Use the specified date/time format. |
Vinay Sajip | c5b2730 | 2010-10-31 14:59:16 +0000 | [diff] [blame] | 1642 | style If a format string is specified, use this to specify the |
| 1643 | type of format string (possible values '%', '{', '$', for |
| 1644 | %-formatting, :meth:`str.format` and :class:`string.Template` |
| 1645 | - defaults to '%'). |
Vinay Sajip | 779e0c9 | 2004-07-03 11:47:26 +0000 | [diff] [blame] | 1646 | level Set the root logger level to the specified level. |
| 1647 | stream Use the specified stream to initialize the StreamHandler. Note |
| 1648 | that this argument is incompatible with 'filename' - if both |
| 1649 | are present, 'stream' is ignored. |
| 1650 | |
| 1651 | Note that you could specify a stream created using open(filename, mode) |
| 1652 | rather than passing the filename and mode in. However, it should be |
| 1653 | remembered that StreamHandler does not close its stream (since it may be |
| 1654 | using sys.stdout or sys.stderr), whereas FileHandler closes its stream |
| 1655 | when the handler is closed. |
Vinay Sajip | c5b2730 | 2010-10-31 14:59:16 +0000 | [diff] [blame] | 1656 | |
| 1657 | .. versionchanged: 3.2 |
| 1658 | Added the ``style`` parameter. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1659 | """ |
Vinay Sajip | 2314fc7 | 2010-09-10 08:25:13 +0000 | [diff] [blame] | 1660 | # Add thread safety in case someone mistakenly calls |
| 1661 | # basicConfig() from multiple threads |
| 1662 | _acquireLock() |
| 1663 | try: |
| 1664 | if len(root.handlers) == 0: |
| 1665 | filename = kwargs.get("filename") |
| 1666 | if filename: |
| 1667 | mode = kwargs.get("filemode", 'a') |
| 1668 | hdlr = FileHandler(filename, mode) |
| 1669 | else: |
| 1670 | stream = kwargs.get("stream") |
| 1671 | hdlr = StreamHandler(stream) |
| 1672 | fs = kwargs.get("format", BASIC_FORMAT) |
| 1673 | dfs = kwargs.get("datefmt", None) |
Vinay Sajip | c5b2730 | 2010-10-31 14:59:16 +0000 | [diff] [blame] | 1674 | style = kwargs.get("style", '%') |
| 1675 | fmt = Formatter(fs, dfs, style) |
Vinay Sajip | 2314fc7 | 2010-09-10 08:25:13 +0000 | [diff] [blame] | 1676 | hdlr.setFormatter(fmt) |
| 1677 | root.addHandler(hdlr) |
| 1678 | level = kwargs.get("level") |
| 1679 | if level is not None: |
| 1680 | root.setLevel(level) |
| 1681 | finally: |
| 1682 | _releaseLock() |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1683 | |
| 1684 | #--------------------------------------------------------------------------- |
| 1685 | # Utility functions at module level. |
| 1686 | # Basically delegate everything to the root logger. |
| 1687 | #--------------------------------------------------------------------------- |
| 1688 | |
| 1689 | def getLogger(name=None): |
| 1690 | """ |
| 1691 | Return a logger with the specified name, creating it if necessary. |
| 1692 | |
| 1693 | If no name is specified, return the root logger. |
| 1694 | """ |
| 1695 | if name: |
| 1696 | return Logger.manager.getLogger(name) |
| 1697 | else: |
| 1698 | return root |
| 1699 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1700 | def critical(msg, *args, **kwargs): |
| 1701 | """ |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1702 | Log a message with severity 'CRITICAL' on the root logger. If the logger |
| 1703 | has no handlers, call basicConfig() to add a console handler with a |
| 1704 | pre-defined format. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1705 | """ |
| 1706 | if len(root.handlers) == 0: |
| 1707 | basicConfig() |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1708 | root.critical(msg, *args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1709 | |
| 1710 | fatal = critical |
| 1711 | |
| 1712 | def error(msg, *args, **kwargs): |
| 1713 | """ |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1714 | Log a message with severity 'ERROR' on the root logger. If the logger has |
| 1715 | no handlers, call basicConfig() to add a console handler with a pre-defined |
| 1716 | format. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1717 | """ |
| 1718 | if len(root.handlers) == 0: |
| 1719 | basicConfig() |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1720 | root.error(msg, *args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1721 | |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1722 | def exception(msg, *args, **kwargs): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1723 | """ |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1724 | Log a message with severity 'ERROR' on the root logger, with exception |
| 1725 | information. If the logger has no handlers, basicConfig() is called to add |
| 1726 | a console handler with a pre-defined format. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1727 | """ |
Vinay Sajip | 8593ae6 | 2010-11-14 21:33:04 +0000 | [diff] [blame] | 1728 | kwargs['exc_info'] = True |
| 1729 | error(msg, *args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1730 | |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 1731 | def warning(msg, *args, **kwargs): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1732 | """ |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1733 | Log a message with severity 'WARNING' on the root logger. If the logger has |
| 1734 | no handlers, call basicConfig() to add a console handler with a pre-defined |
| 1735 | format. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1736 | """ |
| 1737 | if len(root.handlers) == 0: |
| 1738 | basicConfig() |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1739 | root.warning(msg, *args, **kwargs) |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 1740 | |
| 1741 | warn = warning |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1742 | |
| 1743 | def info(msg, *args, **kwargs): |
| 1744 | """ |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1745 | Log a message with severity 'INFO' on the root logger. If the logger has |
| 1746 | no handlers, call basicConfig() to add a console handler with a pre-defined |
| 1747 | format. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1748 | """ |
| 1749 | if len(root.handlers) == 0: |
| 1750 | basicConfig() |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1751 | root.info(msg, *args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1752 | |
| 1753 | def debug(msg, *args, **kwargs): |
| 1754 | """ |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1755 | Log a message with severity 'DEBUG' on the root logger. If the logger has |
| 1756 | no handlers, call basicConfig() to add a console handler with a pre-defined |
| 1757 | format. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1758 | """ |
| 1759 | if len(root.handlers) == 0: |
| 1760 | basicConfig() |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1761 | root.debug(msg, *args, **kwargs) |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1762 | |
Vinay Sajip | b2635b2 | 2004-09-24 11:45:52 +0000 | [diff] [blame] | 1763 | def log(level, msg, *args, **kwargs): |
| 1764 | """ |
Vinay Sajip | 5a27d40 | 2010-12-10 11:42:57 +0000 | [diff] [blame] | 1765 | Log 'msg % args' with the integer severity 'level' on the root logger. If |
| 1766 | the logger has no handlers, call basicConfig() to add a console handler |
| 1767 | with a pre-defined format. |
Vinay Sajip | b2635b2 | 2004-09-24 11:45:52 +0000 | [diff] [blame] | 1768 | """ |
| 1769 | if len(root.handlers) == 0: |
| 1770 | basicConfig() |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 1771 | root.log(level, msg, *args, **kwargs) |
Vinay Sajip | b2635b2 | 2004-09-24 11:45:52 +0000 | [diff] [blame] | 1772 | |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1773 | def disable(level): |
| 1774 | """ |
Benjamin Peterson | 886af96 | 2010-03-21 23:13:07 +0000 | [diff] [blame] | 1775 | Disable all logging calls of severity 'level' and below. |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1776 | """ |
| 1777 | root.manager.disable = level |
| 1778 | |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 1779 | def shutdown(handlerList=_handlerList): |
Guido van Rossum | 57102f8 | 2002-11-13 16:15:58 +0000 | [diff] [blame] | 1780 | """ |
| 1781 | Perform any cleanup actions in the logging system (e.g. flushing |
| 1782 | buffers). |
| 1783 | |
| 1784 | Should be called at application exit. |
| 1785 | """ |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 1786 | for wr in reversed(handlerList[:]): |
Vinay Sajip | e12f715 | 2004-07-29 09:19:30 +0000 | [diff] [blame] | 1787 | #errors might occur, for example, if files are locked |
Vinay Sajip | 260ce43 | 2006-02-09 08:34:14 +0000 | [diff] [blame] | 1788 | #we just ignore them if raiseExceptions is not set |
Vinay Sajip | e12f715 | 2004-07-29 09:19:30 +0000 | [diff] [blame] | 1789 | try: |
Benjamin Peterson | 5554993 | 2009-11-25 17:19:56 +0000 | [diff] [blame] | 1790 | h = wr() |
Vinay Sajip | de6e9d6 | 2010-08-23 17:50:30 +0000 | [diff] [blame] | 1791 | if h: |
| 1792 | try: |
| 1793 | h.flush() |
| 1794 | h.close() |
| 1795 | except (IOError, ValueError): |
| 1796 | # Ignore errors which might be caused |
| 1797 | # because handlers have been closed but |
| 1798 | # references to them are still around at |
| 1799 | # application exit. |
| 1800 | pass |
Vinay Sajip | e12f715 | 2004-07-29 09:19:30 +0000 | [diff] [blame] | 1801 | except: |
Vinay Sajip | 260ce43 | 2006-02-09 08:34:14 +0000 | [diff] [blame] | 1802 | if raiseExceptions: |
| 1803 | raise |
| 1804 | #else, swallow |
Vinay Sajip | ed6bb14 | 2004-02-20 13:18:36 +0000 | [diff] [blame] | 1805 | |
| 1806 | #Let's try and shutdown automatically on application exit... |
Georg Brandl | 01e4d57 | 2010-02-06 22:27:51 +0000 | [diff] [blame] | 1807 | import atexit |
| 1808 | atexit.register(shutdown) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 1809 | |
| 1810 | # Null handler |
| 1811 | |
| 1812 | class NullHandler(Handler): |
| 1813 | """ |
| 1814 | This handler does nothing. It's intended to be used to avoid the |
| 1815 | "No handlers could be found for logger XXX" one-off warning. This is |
| 1816 | important for library code, which may contain code to log events. If a user |
| 1817 | of the library does not configure logging, the one-off warning might be |
| 1818 | produced; to avoid this, the library developer simply needs to instantiate |
| 1819 | a NullHandler and add it to the top-level logger of the library module or |
| 1820 | package. |
| 1821 | """ |
Vinay Sajip | 4fbe4b3 | 2010-09-26 11:04:10 +0000 | [diff] [blame] | 1822 | def handle(self, record): |
| 1823 | pass |
| 1824 | |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 1825 | def emit(self, record): |
| 1826 | pass |
| 1827 | |
Vinay Sajip | 4fbe4b3 | 2010-09-26 11:04:10 +0000 | [diff] [blame] | 1828 | def createLock(self): |
| 1829 | self.lock = None |
| 1830 | |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 1831 | # Warnings integration |
| 1832 | |
| 1833 | _warnings_showwarning = None |
| 1834 | |
| 1835 | def _showwarning(message, category, filename, lineno, file=None, line=None): |
| 1836 | """ |
| 1837 | Implementation of showwarnings which redirects to logging, which will first |
| 1838 | check to see if the file parameter is None. If a file is specified, it will |
| 1839 | delegate to the original warnings implementation of showwarning. Otherwise, |
| 1840 | it will call warnings.formatwarning and will log the resulting string to a |
| 1841 | warnings logger named "py.warnings" with level logging.WARNING. |
| 1842 | """ |
| 1843 | if file is not None: |
| 1844 | if _warnings_showwarning is not None: |
| 1845 | _warnings_showwarning(message, category, filename, lineno, file, line) |
| 1846 | else: |
| 1847 | s = warnings.formatwarning(message, category, filename, lineno, line) |
| 1848 | logger = getLogger("py.warnings") |
| 1849 | if not logger.handlers: |
| 1850 | logger.addHandler(NullHandler()) |
| 1851 | logger.warning("%s", s) |
| 1852 | |
| 1853 | def captureWarnings(capture): |
| 1854 | """ |
| 1855 | If capture is true, redirect all warnings to the logging package. |
| 1856 | If capture is False, ensure that warnings are not redirected to logging |
| 1857 | but to their original destinations. |
| 1858 | """ |
| 1859 | global _warnings_showwarning |
| 1860 | if capture: |
| 1861 | if _warnings_showwarning is None: |
| 1862 | _warnings_showwarning = warnings.showwarning |
| 1863 | warnings.showwarning = _showwarning |
| 1864 | else: |
| 1865 | if _warnings_showwarning is not None: |
| 1866 | warnings.showwarning = _warnings_showwarning |
| 1867 | _warnings_showwarning = None |