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