Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1 | :mod:`logging` --- Logging facility for Python |
| 2 | ============================================== |
| 3 | |
| 4 | .. module:: logging |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 5 | :synopsis: Flexible event logging system for applications. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 6 | |
| 7 | |
| 8 | .. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com> |
| 9 | .. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com> |
| 10 | |
| 11 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 12 | .. index:: pair: Errors; logging |
| 13 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 14 | .. sidebar:: Important |
| 15 | |
| 16 | This page contains the API reference information. For tutorial |
| 17 | information and discussion of more advanced topics, see |
| 18 | |
| 19 | * :ref:`Basic Tutorial <logging-basic-tutorial>` |
| 20 | * :ref:`Advanced Tutorial <logging-advanced-tutorial>` |
| 21 | * :ref:`Logging Cookbook <logging-cookbook>` |
| 22 | |
Vinay Sajip | 6971f2e | 2013-09-05 22:57:20 +0100 | [diff] [blame] | 23 | **Source code:** :source:`Lib/logging/__init__.py` |
| 24 | |
| 25 | -------------- |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 26 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 27 | .. versionadded:: 2.3 |
| 28 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 29 | This module defines functions and classes which implement a flexible event |
| 30 | logging system for applications and libraries. |
Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 31 | |
| 32 | The key benefit of having the logging API provided by a standard library module |
| 33 | is that all Python modules can participate in logging, so your application log |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 34 | can include your own messages integrated with messages from third-party |
| 35 | modules. |
Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 36 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 37 | The module provides a lot of functionality and flexibility. If you are |
| 38 | unfamiliar with logging, the best way to get to grips with it is to see the |
| 39 | tutorials (see the links on the right). |
Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 40 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 41 | The basic classes defined by the module, together with their functions, are |
| 42 | listed below. |
Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 43 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 44 | * Loggers expose the interface that application code directly uses. |
| 45 | * Handlers send the log records (created by loggers) to the appropriate |
| 46 | destination. |
| 47 | * Filters provide a finer grained facility for determining which log records |
| 48 | to output. |
| 49 | * Formatters specify the layout of log records in the final output. |
Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 50 | |
Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 51 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 52 | .. _logger: |
Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 53 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 54 | Logger Objects |
Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 55 | -------------- |
| 56 | |
Vinay Sajip | 2a1c13b | 2012-04-10 19:52:06 +0100 | [diff] [blame] | 57 | Loggers have the following attributes and methods. Note that Loggers are never |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 58 | instantiated directly, but always through the module-level function |
Vinay Sajip | 2a1c13b | 2012-04-10 19:52:06 +0100 | [diff] [blame] | 59 | ``logging.getLogger(name)``. Multiple calls to :func:`getLogger` with the same |
| 60 | name will always return a reference to the same Logger object. |
| 61 | |
| 62 | The ``name`` is potentially a period-separated hierarchical value, like |
| 63 | ``foo.bar.baz`` (though it could also be just plain ``foo``, for example). |
| 64 | Loggers that are further down in the hierarchical list are children of loggers |
| 65 | higher up in the list. For example, given a logger with a name of ``foo``, |
| 66 | loggers with names of ``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all |
| 67 | descendants of ``foo``. The logger name hierarchy is analogous to the Python |
| 68 | package hierarchy, and identical to it if you organise your loggers on a |
| 69 | per-module basis using the recommended construction |
| 70 | ``logging.getLogger(__name__)``. That's because in a module, ``__name__`` |
| 71 | is the module's name in the Python package namespace. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 72 | |
Vinay Sajip | cb309c5 | 2013-01-21 19:43:51 +0000 | [diff] [blame] | 73 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 74 | .. class:: Logger |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 75 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 76 | .. attribute:: Logger.propagate |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 77 | |
Vinay Sajip | cb309c5 | 2013-01-21 19:43:51 +0000 | [diff] [blame] | 78 | If this evaluates to true, events logged to this logger will be passed to the |
| 79 | handlers of higher level (ancestor) loggers, in addition to any handlers |
| 80 | attached to this logger. Messages are passed directly to the ancestor |
| 81 | loggers' handlers - neither the level nor filters of the ancestor loggers in |
| 82 | question are considered. |
Vinay Sajip | 3639807 | 2011-11-23 08:51:35 +0000 | [diff] [blame] | 83 | |
| 84 | If this evaluates to false, logging messages are not passed to the handlers |
| 85 | of ancestor loggers. |
| 86 | |
Benjamin Peterson | c016f46 | 2011-12-30 13:47:25 -0600 | [diff] [blame] | 87 | The constructor sets this attribute to ``True``. |
Vinay Sajip | 89e1ae2 | 2010-09-17 10:09:04 +0000 | [diff] [blame] | 88 | |
Vinay Sajip | 8a459d9 | 2013-01-21 21:56:35 +0000 | [diff] [blame] | 89 | .. note:: If you attach a handler to a logger *and* one or more of its |
| 90 | ancestors, it may emit the same record multiple times. In general, you |
| 91 | should not need to attach a handler to more than one logger - if you just |
| 92 | attach it to the appropriate logger which is highest in the logger |
| 93 | hierarchy, then it will see all events logged by all descendant loggers, |
| 94 | provided that their propagate setting is left set to ``True``. A common |
| 95 | scenario is to attach handlers only to the root logger, and to let |
| 96 | propagation take care of the rest. |
Vinay Sajip | 89e1ae2 | 2010-09-17 10:09:04 +0000 | [diff] [blame] | 97 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 98 | .. method:: Logger.setLevel(lvl) |
| 99 | |
| 100 | Sets the threshold for this logger to *lvl*. Logging messages which are less |
| 101 | severe than *lvl* will be ignored. When a logger is created, the level is set to |
| 102 | :const:`NOTSET` (which causes all messages to be processed when the logger is |
| 103 | the root logger, or delegation to the parent when the logger is a non-root |
| 104 | logger). Note that the root logger is created with level :const:`WARNING`. |
| 105 | |
| 106 | The term 'delegation to the parent' means that if a logger has a level of |
| 107 | NOTSET, its chain of ancestor loggers is traversed until either an ancestor with |
| 108 | a level other than NOTSET is found, or the root is reached. |
| 109 | |
| 110 | If an ancestor is found with a level other than NOTSET, then that ancestor's |
| 111 | level is treated as the effective level of the logger where the ancestor search |
| 112 | began, and is used to determine how a logging event is handled. |
| 113 | |
| 114 | If the root is reached, and it has a level of NOTSET, then all messages will be |
| 115 | processed. Otherwise, the root's level will be used as the effective level. |
| 116 | |
Vinay Sajip | d46a31f | 2013-12-19 11:42:18 +0000 | [diff] [blame] | 117 | See :ref:`levels` for a list of levels. |
| 118 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 119 | |
| 120 | .. method:: Logger.isEnabledFor(lvl) |
| 121 | |
| 122 | Indicates if a message of severity *lvl* would be processed by this logger. |
| 123 | This method checks first the module-level level set by |
| 124 | ``logging.disable(lvl)`` and then the logger's effective level as determined |
| 125 | by :meth:`getEffectiveLevel`. |
| 126 | |
| 127 | |
| 128 | .. method:: Logger.getEffectiveLevel() |
| 129 | |
| 130 | Indicates the effective level for this logger. If a value other than |
| 131 | :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise, |
| 132 | the hierarchy is traversed towards the root until a value other than |
Vinay Sajip | f40a407 | 2014-09-18 17:46:58 +0100 | [diff] [blame] | 133 | :const:`NOTSET` is found, and that value is returned. The value returned is |
| 134 | an integer, typically one of :const:`logging.DEBUG`, :const:`logging.INFO` |
| 135 | etc. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 136 | |
| 137 | |
| 138 | .. method:: Logger.getChild(suffix) |
| 139 | |
| 140 | Returns a logger which is a descendant to this logger, as determined by the suffix. |
| 141 | Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same |
| 142 | logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a |
| 143 | convenience method, useful when the parent logger is named using e.g. ``__name__`` |
| 144 | rather than a literal string. |
| 145 | |
| 146 | .. versionadded:: 2.7 |
| 147 | |
| 148 | |
| 149 | .. method:: Logger.debug(msg, *args, **kwargs) |
| 150 | |
| 151 | Logs a message with level :const:`DEBUG` on this logger. The *msg* is the |
| 152 | message format string, and the *args* are the arguments which are merged into |
| 153 | *msg* using the string formatting operator. (Note that this means that you can |
| 154 | use keywords in the format string, together with a single dictionary argument.) |
| 155 | |
| 156 | There are two keyword arguments in *kwargs* which are inspected: *exc_info* |
| 157 | which, if it does not evaluate as false, causes exception information to be |
| 158 | added to the logging message. If an exception tuple (in the format returned by |
| 159 | :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info` |
| 160 | is called to get the exception information. |
| 161 | |
| 162 | The second keyword argument is *extra* which can be used to pass a |
| 163 | dictionary which is used to populate the __dict__ of the LogRecord created for |
| 164 | the logging event with user-defined attributes. These custom attributes can then |
| 165 | be used as you like. For example, they could be incorporated into logged |
| 166 | messages. For example:: |
| 167 | |
| 168 | FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s' |
| 169 | logging.basicConfig(format=FORMAT) |
Jason R. Coombs | d6a80ee | 2012-03-07 10:24:04 -0500 | [diff] [blame] | 170 | d = {'clientip': '192.168.0.1', 'user': 'fbloggs'} |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 171 | logger = logging.getLogger('tcpserver') |
| 172 | logger.warning('Protocol problem: %s', 'connection reset', extra=d) |
| 173 | |
| 174 | would print something like :: |
| 175 | |
| 176 | 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset |
| 177 | |
| 178 | The keys in the dictionary passed in *extra* should not clash with the keys used |
| 179 | by the logging system. (See the :class:`Formatter` documentation for more |
| 180 | information on which keys are used by the logging system.) |
| 181 | |
| 182 | If you choose to use these attributes in logged messages, you need to exercise |
| 183 | some care. In the above example, for instance, the :class:`Formatter` has been |
| 184 | set up with a format string which expects 'clientip' and 'user' in the attribute |
| 185 | dictionary of the LogRecord. If these are missing, the message will not be |
| 186 | logged because a string formatting exception will occur. So in this case, you |
| 187 | always need to pass the *extra* dictionary with these keys. |
| 188 | |
| 189 | While this might be annoying, this feature is intended for use in specialized |
| 190 | circumstances, such as multi-threaded servers where the same code executes in |
| 191 | many contexts, and interesting conditions which arise are dependent on this |
| 192 | context (such as remote client IP address and authenticated user name, in the |
| 193 | above example). In such circumstances, it is likely that specialized |
| 194 | :class:`Formatter`\ s would be used with particular :class:`Handler`\ s. |
| 195 | |
| 196 | |
| 197 | .. method:: Logger.info(msg, *args, **kwargs) |
| 198 | |
| 199 | Logs a message with level :const:`INFO` on this logger. The arguments are |
| 200 | interpreted as for :meth:`debug`. |
| 201 | |
| 202 | |
| 203 | .. method:: Logger.warning(msg, *args, **kwargs) |
| 204 | |
| 205 | Logs a message with level :const:`WARNING` on this logger. The arguments are |
| 206 | interpreted as for :meth:`debug`. |
| 207 | |
| 208 | |
| 209 | .. method:: Logger.error(msg, *args, **kwargs) |
| 210 | |
| 211 | Logs a message with level :const:`ERROR` on this logger. The arguments are |
| 212 | interpreted as for :meth:`debug`. |
| 213 | |
| 214 | |
| 215 | .. method:: Logger.critical(msg, *args, **kwargs) |
| 216 | |
| 217 | Logs a message with level :const:`CRITICAL` on this logger. The arguments are |
| 218 | interpreted as for :meth:`debug`. |
| 219 | |
| 220 | |
| 221 | .. method:: Logger.log(lvl, msg, *args, **kwargs) |
| 222 | |
| 223 | Logs a message with integer level *lvl* on this logger. The other arguments are |
| 224 | interpreted as for :meth:`debug`. |
| 225 | |
| 226 | |
Vinay Sajip | 51f80c1 | 2014-04-15 23:11:15 +0100 | [diff] [blame] | 227 | .. method:: Logger.exception(msg, *args, **kwargs) |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 228 | |
| 229 | Logs a message with level :const:`ERROR` on this logger. The arguments are |
| 230 | interpreted as for :meth:`debug`. Exception info is added to the logging |
| 231 | message. This method should only be called from an exception handler. |
| 232 | |
| 233 | |
| 234 | .. method:: Logger.addFilter(filt) |
| 235 | |
| 236 | Adds the specified filter *filt* to this logger. |
| 237 | |
| 238 | |
| 239 | .. method:: Logger.removeFilter(filt) |
| 240 | |
| 241 | Removes the specified filter *filt* from this logger. |
| 242 | |
| 243 | |
| 244 | .. method:: Logger.filter(record) |
| 245 | |
| 246 | Applies this logger's filters to the record and returns a true value if the |
Vinay Sajip | cb309c5 | 2013-01-21 19:43:51 +0000 | [diff] [blame] | 247 | record is to be processed. The filters are consulted in turn, until one of |
| 248 | them returns a false value. If none of them return a false value, the record |
| 249 | will be processed (passed to handlers). If one returns a false value, no |
| 250 | further processing of the record occurs. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 251 | |
| 252 | |
| 253 | .. method:: Logger.addHandler(hdlr) |
| 254 | |
| 255 | Adds the specified handler *hdlr* to this logger. |
| 256 | |
| 257 | |
| 258 | .. method:: Logger.removeHandler(hdlr) |
| 259 | |
| 260 | Removes the specified handler *hdlr* from this logger. |
| 261 | |
| 262 | |
| 263 | .. method:: Logger.findCaller() |
| 264 | |
| 265 | Finds the caller's source filename and line number. Returns the filename, line |
| 266 | number and function name as a 3-element tuple. |
| 267 | |
| 268 | .. versionchanged:: 2.4 |
| 269 | The function name was added. In earlier versions, the filename and line |
| 270 | number were returned as a 2-element tuple. |
| 271 | |
| 272 | .. method:: Logger.handle(record) |
| 273 | |
| 274 | Handles a record by passing it to all handlers associated with this logger and |
| 275 | its ancestors (until a false value of *propagate* is found). This method is used |
| 276 | for unpickled records received from a socket, as well as those created locally. |
| 277 | Logger-level filtering is applied using :meth:`~Logger.filter`. |
| 278 | |
| 279 | |
| 280 | .. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None) |
| 281 | |
| 282 | This is a factory method which can be overridden in subclasses to create |
| 283 | specialized :class:`LogRecord` instances. |
| 284 | |
| 285 | .. versionchanged:: 2.5 |
| 286 | *func* and *extra* were added. |
| 287 | |
Vinay Sajip | d46a31f | 2013-12-19 11:42:18 +0000 | [diff] [blame] | 288 | |
| 289 | .. _levels: |
| 290 | |
| 291 | Logging Levels |
| 292 | -------------- |
| 293 | |
| 294 | The numeric values of logging levels are given in the following table. These are |
| 295 | primarily of interest if you want to define your own levels, and need them to |
| 296 | have specific values relative to the predefined levels. If you define a level |
| 297 | with the same numeric value, it overwrites the predefined value; the predefined |
| 298 | name is lost. |
| 299 | |
| 300 | +--------------+---------------+ |
| 301 | | Level | Numeric value | |
| 302 | +==============+===============+ |
| 303 | | ``CRITICAL`` | 50 | |
| 304 | +--------------+---------------+ |
| 305 | | ``ERROR`` | 40 | |
| 306 | +--------------+---------------+ |
| 307 | | ``WARNING`` | 30 | |
| 308 | +--------------+---------------+ |
| 309 | | ``INFO`` | 20 | |
| 310 | +--------------+---------------+ |
| 311 | | ``DEBUG`` | 10 | |
| 312 | +--------------+---------------+ |
| 313 | | ``NOTSET`` | 0 | |
| 314 | +--------------+---------------+ |
| 315 | |
| 316 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 317 | .. _handler: |
| 318 | |
| 319 | Handler Objects |
Vinay Sajip | b5902e6 | 2009-01-15 22:48:13 +0000 | [diff] [blame] | 320 | --------------- |
| 321 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 322 | Handlers have the following attributes and methods. Note that :class:`Handler` |
| 323 | is never instantiated directly; this class acts as a base for more useful |
| 324 | subclasses. However, the :meth:`__init__` method in subclasses needs to call |
| 325 | :meth:`Handler.__init__`. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 326 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 327 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 328 | .. method:: Handler.__init__(level=NOTSET) |
Vinay Sajip | b1a15e4 | 2009-01-15 23:04:47 +0000 | [diff] [blame] | 329 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 330 | Initializes the :class:`Handler` instance by setting its level, setting the list |
| 331 | of filters to the empty list and creating a lock (using :meth:`createLock`) for |
| 332 | serializing access to an I/O mechanism. |
Vinay Sajip | c2211ad | 2009-01-10 19:22:57 +0000 | [diff] [blame] | 333 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 334 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 335 | .. method:: Handler.createLock() |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 336 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 337 | Initializes a thread lock which can be used to serialize access to underlying |
| 338 | I/O functionality which may not be threadsafe. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 339 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 340 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 341 | .. method:: Handler.acquire() |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 342 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 343 | Acquires the thread lock created with :meth:`createLock`. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 344 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 345 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 346 | .. method:: Handler.release() |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 347 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 348 | Releases the thread lock acquired with :meth:`acquire`. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 349 | |
Vinay Sajip | c2211ad | 2009-01-10 19:22:57 +0000 | [diff] [blame] | 350 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 351 | .. method:: Handler.setLevel(lvl) |
Vinay Sajip | 213faca | 2008-12-03 23:22:58 +0000 | [diff] [blame] | 352 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 353 | Sets the threshold for this handler to *lvl*. Logging messages which are less |
| 354 | severe than *lvl* will be ignored. When a handler is created, the level is set |
| 355 | to :const:`NOTSET` (which causes all messages to be processed). |
Vinay Sajip | 213faca | 2008-12-03 23:22:58 +0000 | [diff] [blame] | 356 | |
Vinay Sajip | d46a31f | 2013-12-19 11:42:18 +0000 | [diff] [blame] | 357 | See :ref:`levels` for a list of levels. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 358 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 359 | .. method:: Handler.setFormatter(form) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 360 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 361 | Sets the :class:`Formatter` for this handler to *form*. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 362 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 363 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 364 | .. method:: Handler.addFilter(filt) |
| 365 | |
| 366 | Adds the specified filter *filt* to this handler. |
| 367 | |
| 368 | |
| 369 | .. method:: Handler.removeFilter(filt) |
| 370 | |
| 371 | Removes the specified filter *filt* from this handler. |
| 372 | |
| 373 | |
| 374 | .. method:: Handler.filter(record) |
| 375 | |
| 376 | Applies this handler's filters to the record and returns a true value if the |
Vinay Sajip | cb309c5 | 2013-01-21 19:43:51 +0000 | [diff] [blame] | 377 | record is to be processed. The filters are consulted in turn, until one of |
| 378 | them returns a false value. If none of them return a false value, the record |
| 379 | will be emitted. If one returns a false value, the handler will not emit the |
| 380 | record. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 381 | |
| 382 | |
| 383 | .. method:: Handler.flush() |
| 384 | |
| 385 | Ensure all logging output has been flushed. This version does nothing and is |
| 386 | intended to be implemented by subclasses. |
| 387 | |
| 388 | |
| 389 | .. method:: Handler.close() |
| 390 | |
| 391 | Tidy up any resources used by the handler. This version does no output but |
| 392 | removes the handler from an internal list of handlers which is closed when |
| 393 | :func:`shutdown` is called. Subclasses should ensure that this gets called |
| 394 | from overridden :meth:`close` methods. |
| 395 | |
| 396 | |
| 397 | .. method:: Handler.handle(record) |
| 398 | |
| 399 | Conditionally emits the specified logging record, depending on filters which may |
| 400 | have been added to the handler. Wraps the actual emission of the record with |
| 401 | acquisition/release of the I/O thread lock. |
| 402 | |
| 403 | |
| 404 | .. method:: Handler.handleError(record) |
| 405 | |
| 406 | This method should be called from handlers when an exception is encountered |
Vinay Sajip | 7d13cd3 | 2012-02-20 18:34:07 +0000 | [diff] [blame] | 407 | during an :meth:`emit` call. If the module-level attribute |
| 408 | ``raiseExceptions`` is ``False``, exceptions get silently ignored. This is |
| 409 | what is mostly wanted for a logging system - most users will not care about |
| 410 | errors in the logging system, they are more interested in application |
| 411 | errors. You could, however, replace this with a custom handler if you wish. |
| 412 | The specified record is the one which was being processed when the exception |
| 413 | occurred. (The default value of ``raiseExceptions`` is ``True``, as that is |
| 414 | more useful during development). |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 415 | |
| 416 | |
| 417 | .. method:: Handler.format(record) |
| 418 | |
| 419 | Do formatting for a record - if a formatter is set, use it. Otherwise, use the |
| 420 | default formatter for the module. |
| 421 | |
| 422 | |
| 423 | .. method:: Handler.emit(record) |
| 424 | |
| 425 | Do whatever it takes to actually log the specified logging record. This version |
| 426 | is intended to be implemented by subclasses and so raises a |
| 427 | :exc:`NotImplementedError`. |
| 428 | |
| 429 | For a list of handlers included as standard, see :mod:`logging.handlers`. |
| 430 | |
| 431 | .. _formatter-objects: |
| 432 | |
| 433 | Formatter Objects |
| 434 | ----------------- |
| 435 | |
| 436 | .. currentmodule:: logging |
| 437 | |
| 438 | :class:`Formatter` objects have the following attributes and methods. They are |
| 439 | responsible for converting a :class:`LogRecord` to (usually) a string which can |
| 440 | be interpreted by either a human or an external system. The base |
| 441 | :class:`Formatter` allows a formatting string to be specified. If none is |
| 442 | supplied, the default value of ``'%(message)s'`` is used. |
| 443 | |
| 444 | A Formatter can be initialized with a format string which makes use of knowledge |
| 445 | of the :class:`LogRecord` attributes - such as the default value mentioned above |
| 446 | making use of the fact that the user's message and arguments are pre-formatted |
| 447 | into a :class:`LogRecord`'s *message* attribute. This format string contains |
| 448 | standard Python %-style mapping keys. See section :ref:`string-formatting` |
| 449 | for more information on string formatting. |
| 450 | |
| 451 | The useful mapping keys in a :class:`LogRecord` are given in the section on |
| 452 | :ref:`logrecord-attributes`. |
| 453 | |
| 454 | |
| 455 | .. class:: Formatter(fmt=None, datefmt=None) |
| 456 | |
| 457 | Returns a new instance of the :class:`Formatter` class. The instance is |
| 458 | initialized with a format string for the message as a whole, as well as a |
| 459 | format string for the date/time portion of a message. If no *fmt* is |
| 460 | specified, ``'%(message)s'`` is used. If no *datefmt* is specified, the |
| 461 | ISO8601 date format is used. |
| 462 | |
| 463 | .. method:: format(record) |
| 464 | |
| 465 | The record's attribute dictionary is used as the operand to a string |
| 466 | formatting operation. Returns the resulting string. Before formatting the |
| 467 | dictionary, a couple of preparatory steps are carried out. The *message* |
| 468 | attribute of the record is computed using *msg* % *args*. If the |
| 469 | formatting string contains ``'(asctime)'``, :meth:`formatTime` is called |
| 470 | to format the event time. If there is exception information, it is |
| 471 | formatted using :meth:`formatException` and appended to the message. Note |
| 472 | that the formatted exception information is cached in attribute |
| 473 | *exc_text*. This is useful because the exception information can be |
| 474 | pickled and sent across the wire, but you should be careful if you have |
| 475 | more than one :class:`Formatter` subclass which customizes the formatting |
| 476 | of exception information. In this case, you will have to clear the cached |
| 477 | value after a formatter has done its formatting, so that the next |
| 478 | formatter to handle the event doesn't use the cached value but |
| 479 | recalculates it afresh. |
| 480 | |
| 481 | |
| 482 | .. method:: formatTime(record, datefmt=None) |
| 483 | |
| 484 | This method should be called from :meth:`format` by a formatter which |
| 485 | wants to make use of a formatted time. This method can be overridden in |
| 486 | formatters to provide for any specific requirement, but the basic behavior |
| 487 | is as follows: if *datefmt* (a string) is specified, it is used with |
| 488 | :func:`time.strftime` to format the creation time of the |
| 489 | record. Otherwise, the ISO8601 format is used. The resulting string is |
| 490 | returned. |
| 491 | |
Vinay Sajip | ad52cb2 | 2011-06-13 14:59:36 +0100 | [diff] [blame] | 492 | This function uses a user-configurable function to convert the creation |
| 493 | time to a tuple. By default, :func:`time.localtime` is used; to change |
| 494 | this for a particular formatter instance, set the ``converter`` attribute |
| 495 | to a function with the same signature as :func:`time.localtime` or |
| 496 | :func:`time.gmtime`. To change it for all formatters, for example if you |
| 497 | want all logging times to be shown in GMT, set the ``converter`` |
| 498 | attribute in the ``Formatter`` class. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 499 | |
| 500 | .. method:: formatException(exc_info) |
| 501 | |
| 502 | Formats the specified exception information (a standard exception tuple as |
| 503 | returned by :func:`sys.exc_info`) as a string. This default implementation |
| 504 | just uses :func:`traceback.print_exception`. The resulting string is |
| 505 | returned. |
| 506 | |
| 507 | .. _filter: |
| 508 | |
| 509 | Filter Objects |
| 510 | -------------- |
| 511 | |
| 512 | ``Filters`` can be used by ``Handlers`` and ``Loggers`` for more sophisticated |
| 513 | filtering than is provided by levels. The base filter class only allows events |
| 514 | which are below a certain point in the logger hierarchy. For example, a filter |
| 515 | initialized with 'A.B' will allow events logged by loggers 'A.B', 'A.B.C', |
| 516 | 'A.B.C.D', 'A.B.D' etc. but not 'A.BB', 'B.A.B' etc. If initialized with the |
| 517 | empty string, all events are passed. |
| 518 | |
| 519 | |
| 520 | .. class:: Filter(name='') |
| 521 | |
| 522 | Returns an instance of the :class:`Filter` class. If *name* is specified, it |
| 523 | names a logger which, together with its children, will have its events allowed |
| 524 | through the filter. If *name* is the empty string, allows every event. |
| 525 | |
| 526 | |
| 527 | .. method:: filter(record) |
| 528 | |
| 529 | Is the specified record to be logged? Returns zero for no, nonzero for |
| 530 | yes. If deemed appropriate, the record may be modified in-place by this |
| 531 | method. |
| 532 | |
Vinay Sajip | cb309c5 | 2013-01-21 19:43:51 +0000 | [diff] [blame] | 533 | Note that filters attached to handlers are consulted before an event is |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 534 | emitted by the handler, whereas filters attached to loggers are consulted |
Vinay Sajip | cb309c5 | 2013-01-21 19:43:51 +0000 | [diff] [blame] | 535 | whenever an event is logged (using :meth:`debug`, :meth:`info`, |
| 536 | etc.), before sending an event to handlers. This means that events which have |
| 537 | been generated by descendant loggers will not be filtered by a logger's filter |
| 538 | setting, unless the filter has also been applied to those descendant loggers. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 539 | |
| 540 | You don't actually need to subclass ``Filter``: you can pass any instance |
| 541 | which has a ``filter`` method with the same semantics. |
| 542 | |
| 543 | Although filters are used primarily to filter records based on more |
| 544 | sophisticated criteria than levels, they get to see every record which is |
| 545 | processed by the handler or logger they're attached to: this can be useful if |
| 546 | you want to do things like counting how many records were processed by a |
| 547 | particular logger or handler, or adding, changing or removing attributes in |
| 548 | the LogRecord being processed. Obviously changing the LogRecord needs to be |
| 549 | done with some care, but it does allow the injection of contextual information |
| 550 | into logs (see :ref:`filters-contextual`). |
| 551 | |
| 552 | .. _log-record: |
| 553 | |
| 554 | LogRecord Objects |
| 555 | ----------------- |
| 556 | |
| 557 | :class:`LogRecord` instances are created automatically by the :class:`Logger` |
| 558 | every time something is logged, and can be created manually via |
| 559 | :func:`makeLogRecord` (for example, from a pickled event received over the |
| 560 | wire). |
| 561 | |
| 562 | |
| 563 | .. class:: LogRecord(name, level, pathname, lineno, msg, args, exc_info, func=None) |
| 564 | |
| 565 | Contains all the information pertinent to the event being logged. |
| 566 | |
| 567 | The primary information is passed in :attr:`msg` and :attr:`args`, which |
| 568 | are combined using ``msg % args`` to create the :attr:`message` field of the |
| 569 | record. |
| 570 | |
| 571 | :param name: The name of the logger used to log the event represented by |
Vinay Sajip | cb309c5 | 2013-01-21 19:43:51 +0000 | [diff] [blame] | 572 | this LogRecord. Note that this name will always have this |
| 573 | value, even though it may be emitted by a handler attached to |
| 574 | a different (ancestor) logger. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 575 | :param level: The numeric level of the logging event (one of DEBUG, INFO etc.) |
Vinay Sajip | ad52cb2 | 2011-06-13 14:59:36 +0100 | [diff] [blame] | 576 | Note that this is converted to *two* attributes of the LogRecord: |
| 577 | ``levelno`` for the numeric value and ``levelname`` for the |
| 578 | corresponding level name. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 579 | :param pathname: The full pathname of the source file where the logging call |
| 580 | was made. |
| 581 | :param lineno: The line number in the source file where the logging call was |
| 582 | made. |
| 583 | :param msg: The event description message, possibly a format string with |
| 584 | placeholders for variable data. |
| 585 | :param args: Variable data to merge into the *msg* argument to obtain the |
| 586 | event description. |
| 587 | :param exc_info: An exception tuple with the current exception information, |
| 588 | or *None* if no exception information is available. |
| 589 | :param func: The name of the function or method from which the logging call |
| 590 | was invoked. |
| 591 | |
| 592 | .. versionchanged:: 2.5 |
| 593 | *func* was added. |
| 594 | |
| 595 | .. method:: getMessage() |
| 596 | |
| 597 | Returns the message for this :class:`LogRecord` instance after merging any |
| 598 | user-supplied arguments with the message. If the user-supplied message |
| 599 | argument to the logging call is not a string, :func:`str` is called on it to |
| 600 | convert it to a string. This allows use of user-defined classes as |
| 601 | messages, whose ``__str__`` method can return the actual format string to |
| 602 | be used. |
| 603 | |
| 604 | |
| 605 | .. _logrecord-attributes: |
| 606 | |
| 607 | LogRecord attributes |
| 608 | -------------------- |
| 609 | |
| 610 | The LogRecord has a number of attributes, most of which are derived from the |
| 611 | parameters to the constructor. (Note that the names do not always correspond |
| 612 | exactly between the LogRecord constructor parameters and the LogRecord |
| 613 | attributes.) These attributes can be used to merge data from the record into |
| 614 | the format string. The following table lists (in alphabetical order) the |
| 615 | attribute names, their meanings and the corresponding placeholder in a %-style |
| 616 | format string. |
| 617 | |
| 618 | +----------------+-------------------------+-----------------------------------------------+ |
| 619 | | Attribute name | Format | Description | |
| 620 | +================+=========================+===============================================+ |
| 621 | | args | You shouldn't need to | The tuple of arguments merged into ``msg`` to | |
| 622 | | | format this yourself. | produce ``message``. | |
| 623 | +----------------+-------------------------+-----------------------------------------------+ |
| 624 | | asctime | ``%(asctime)s`` | Human-readable time when the | |
| 625 | | | | :class:`LogRecord` was created. By default | |
| 626 | | | | this is of the form '2003-07-08 16:49:45,896' | |
| 627 | | | | (the numbers after the comma are millisecond | |
| 628 | | | | portion of the time). | |
| 629 | +----------------+-------------------------+-----------------------------------------------+ |
| 630 | | created | ``%(created)f`` | Time when the :class:`LogRecord` was created | |
| 631 | | | | (as returned by :func:`time.time`). | |
| 632 | +----------------+-------------------------+-----------------------------------------------+ |
| 633 | | exc_info | You shouldn't need to | Exception tuple (à la ``sys.exc_info``) or, | |
| 634 | | | format this yourself. | if no exception has occurred, *None*. | |
| 635 | +----------------+-------------------------+-----------------------------------------------+ |
| 636 | | filename | ``%(filename)s`` | Filename portion of ``pathname``. | |
| 637 | +----------------+-------------------------+-----------------------------------------------+ |
| 638 | | funcName | ``%(funcName)s`` | Name of function containing the logging call. | |
| 639 | +----------------+-------------------------+-----------------------------------------------+ |
| 640 | | levelname | ``%(levelname)s`` | Text logging level for the message | |
| 641 | | | | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, | |
| 642 | | | | ``'ERROR'``, ``'CRITICAL'``). | |
| 643 | +----------------+-------------------------+-----------------------------------------------+ |
| 644 | | levelno | ``%(levelno)s`` | Numeric logging level for the message | |
| 645 | | | | (:const:`DEBUG`, :const:`INFO`, | |
| 646 | | | | :const:`WARNING`, :const:`ERROR`, | |
| 647 | | | | :const:`CRITICAL`). | |
| 648 | +----------------+-------------------------+-----------------------------------------------+ |
| 649 | | lineno | ``%(lineno)d`` | Source line number where the logging call was | |
| 650 | | | | issued (if available). | |
| 651 | +----------------+-------------------------+-----------------------------------------------+ |
| 652 | | module | ``%(module)s`` | Module (name portion of ``filename``). | |
| 653 | +----------------+-------------------------+-----------------------------------------------+ |
| 654 | | msecs | ``%(msecs)d`` | Millisecond portion of the time when the | |
| 655 | | | | :class:`LogRecord` was created. | |
| 656 | +----------------+-------------------------+-----------------------------------------------+ |
| 657 | | message | ``%(message)s`` | The logged message, computed as ``msg % | |
| 658 | | | | args``. This is set when | |
| 659 | | | | :meth:`Formatter.format` is invoked. | |
| 660 | +----------------+-------------------------+-----------------------------------------------+ |
| 661 | | msg | You shouldn't need to | The format string passed in the original | |
| 662 | | | format this yourself. | logging call. Merged with ``args`` to | |
| 663 | | | | produce ``message``, or an arbitrary object | |
| 664 | | | | (see :ref:`arbitrary-object-messages`). | |
| 665 | +----------------+-------------------------+-----------------------------------------------+ |
| 666 | | name | ``%(name)s`` | Name of the logger used to log the call. | |
| 667 | +----------------+-------------------------+-----------------------------------------------+ |
| 668 | | pathname | ``%(pathname)s`` | Full pathname of the source file where the | |
| 669 | | | | logging call was issued (if available). | |
| 670 | +----------------+-------------------------+-----------------------------------------------+ |
| 671 | | process | ``%(process)d`` | Process ID (if available). | |
| 672 | +----------------+-------------------------+-----------------------------------------------+ |
| 673 | | processName | ``%(processName)s`` | Process name (if available). | |
| 674 | +----------------+-------------------------+-----------------------------------------------+ |
| 675 | | relativeCreated| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was | |
| 676 | | | | created, relative to the time the logging | |
| 677 | | | | module was loaded. | |
| 678 | +----------------+-------------------------+-----------------------------------------------+ |
| 679 | | thread | ``%(thread)d`` | Thread ID (if available). | |
| 680 | +----------------+-------------------------+-----------------------------------------------+ |
| 681 | | threadName | ``%(threadName)s`` | Thread name (if available). | |
| 682 | +----------------+-------------------------+-----------------------------------------------+ |
| 683 | |
| 684 | .. versionchanged:: 2.5 |
| 685 | *funcName* was added. |
| 686 | |
Vinay Sajip | bee739b | 2012-07-20 09:48:46 +0100 | [diff] [blame] | 687 | .. versionchanged:: 2.6 |
| 688 | *processName* was added. |
| 689 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 690 | .. _logger-adapter: |
| 691 | |
| 692 | LoggerAdapter Objects |
| 693 | --------------------- |
| 694 | |
| 695 | :class:`LoggerAdapter` instances are used to conveniently pass contextual |
Serhiy Storchaka | 610f84a | 2013-12-23 18:19:34 +0200 | [diff] [blame] | 696 | information into logging calls. For a usage example, see the section on |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 697 | :ref:`adding contextual information to your logging output <context-info>`. |
| 698 | |
| 699 | .. versionadded:: 2.6 |
| 700 | |
| 701 | |
| 702 | .. class:: LoggerAdapter(logger, extra) |
| 703 | |
| 704 | Returns an instance of :class:`LoggerAdapter` initialized with an |
| 705 | underlying :class:`Logger` instance and a dict-like object. |
| 706 | |
| 707 | .. method:: process(msg, kwargs) |
| 708 | |
| 709 | Modifies the message and/or keyword arguments passed to a logging call in |
| 710 | order to insert contextual information. This implementation takes the object |
| 711 | passed as *extra* to the constructor and adds it to *kwargs* using key |
| 712 | 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the |
| 713 | (possibly modified) versions of the arguments passed in. |
| 714 | |
| 715 | In addition to the above, :class:`LoggerAdapter` supports the following |
Vinay Sajip | 41e9b40 | 2013-10-31 01:08:59 +0000 | [diff] [blame] | 716 | methods of :class:`Logger`: :meth:`~Logger.debug`, :meth:`~Logger.info`, |
| 717 | :meth:`~Logger.warning`, :meth:`~Logger.error`, :meth:`~Logger.exception`, |
| 718 | :meth:`~Logger.critical`, :meth:`~Logger.log` and :meth:`~Logger.isEnabledFor`. |
| 719 | These methods have the same signatures as their counterparts in :class:`Logger`, |
| 720 | so you can use the two types of instances interchangeably for these calls. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 721 | |
| 722 | .. versionchanged:: 2.7 |
Vinay Sajip | 41e9b40 | 2013-10-31 01:08:59 +0000 | [diff] [blame] | 723 | The :meth:`~Logger.isEnabledFor` method was added to :class:`LoggerAdapter`. |
| 724 | This method delegates to the underlying logger. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 725 | |
| 726 | |
| 727 | Thread Safety |
| 728 | ------------- |
| 729 | |
| 730 | The logging module is intended to be thread-safe without any special work |
| 731 | needing to be done by its clients. It achieves this though using threading |
| 732 | locks; there is one lock to serialize access to the module's shared data, and |
| 733 | each handler also creates a lock to serialize access to its underlying I/O. |
| 734 | |
| 735 | If you are implementing asynchronous signal handlers using the :mod:`signal` |
| 736 | module, you may not be able to use logging from within such handlers. This is |
| 737 | because lock implementations in the :mod:`threading` module are not always |
| 738 | re-entrant, and so cannot be invoked from such signal handlers. |
| 739 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 740 | |
Vinay Sajip | b5902e6 | 2009-01-15 22:48:13 +0000 | [diff] [blame] | 741 | Module-Level Functions |
| 742 | ---------------------- |
| 743 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 744 | In addition to the classes described above, there are a number of module- level |
| 745 | functions. |
| 746 | |
| 747 | |
| 748 | .. function:: getLogger([name]) |
| 749 | |
| 750 | Return a logger with the specified name or, if no name is specified, return a |
| 751 | logger which is the root logger of the hierarchy. If specified, the name is |
| 752 | typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*. |
| 753 | Choice of these names is entirely up to the developer who is using logging. |
| 754 | |
| 755 | All calls to this function with a given name return the same logger instance. |
| 756 | This means that logger instances never need to be passed between different parts |
| 757 | of an application. |
| 758 | |
| 759 | |
| 760 | .. function:: getLoggerClass() |
| 761 | |
| 762 | Return either the standard :class:`Logger` class, or the last class passed to |
| 763 | :func:`setLoggerClass`. This function may be called from within a new class |
Vinay Sajip | 6afafc7 | 2013-11-15 20:54:15 +0000 | [diff] [blame] | 764 | definition, to ensure that installing a customized :class:`Logger` class will |
| 765 | not undo customizations already applied by other code. For example:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 766 | |
| 767 | class MyLogger(logging.getLoggerClass()): |
| 768 | # ... override behaviour here |
| 769 | |
| 770 | |
| 771 | .. function:: debug(msg[, *args[, **kwargs]]) |
| 772 | |
| 773 | Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the |
| 774 | message format string, and the *args* are the arguments which are merged into |
| 775 | *msg* using the string formatting operator. (Note that this means that you can |
| 776 | use keywords in the format string, together with a single dictionary argument.) |
| 777 | |
| 778 | There are two keyword arguments in *kwargs* which are inspected: *exc_info* |
| 779 | which, if it does not evaluate as false, causes exception information to be |
| 780 | added to the logging message. If an exception tuple (in the format returned by |
| 781 | :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info` |
| 782 | is called to get the exception information. |
| 783 | |
| 784 | The other optional keyword argument is *extra* which can be used to pass a |
| 785 | dictionary which is used to populate the __dict__ of the LogRecord created for |
| 786 | the logging event with user-defined attributes. These custom attributes can then |
| 787 | be used as you like. For example, they could be incorporated into logged |
| 788 | messages. For example:: |
| 789 | |
| 790 | FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s" |
| 791 | logging.basicConfig(format=FORMAT) |
| 792 | d = {'clientip': '192.168.0.1', 'user': 'fbloggs'} |
| 793 | logging.warning("Protocol problem: %s", "connection reset", extra=d) |
| 794 | |
Vinay Sajip | fe08e6f | 2010-09-11 10:25:28 +0000 | [diff] [blame] | 795 | would print something like:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 796 | |
| 797 | 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset |
| 798 | |
| 799 | The keys in the dictionary passed in *extra* should not clash with the keys used |
| 800 | by the logging system. (See the :class:`Formatter` documentation for more |
| 801 | information on which keys are used by the logging system.) |
| 802 | |
| 803 | If you choose to use these attributes in logged messages, you need to exercise |
| 804 | some care. In the above example, for instance, the :class:`Formatter` has been |
| 805 | set up with a format string which expects 'clientip' and 'user' in the attribute |
| 806 | dictionary of the LogRecord. If these are missing, the message will not be |
| 807 | logged because a string formatting exception will occur. So in this case, you |
| 808 | always need to pass the *extra* dictionary with these keys. |
| 809 | |
| 810 | While this might be annoying, this feature is intended for use in specialized |
| 811 | circumstances, such as multi-threaded servers where the same code executes in |
| 812 | many contexts, and interesting conditions which arise are dependent on this |
| 813 | context (such as remote client IP address and authenticated user name, in the |
| 814 | above example). In such circumstances, it is likely that specialized |
| 815 | :class:`Formatter`\ s would be used with particular :class:`Handler`\ s. |
| 816 | |
| 817 | .. versionchanged:: 2.5 |
| 818 | *extra* was added. |
| 819 | |
| 820 | |
| 821 | .. function:: info(msg[, *args[, **kwargs]]) |
| 822 | |
| 823 | Logs a message with level :const:`INFO` on the root logger. The arguments are |
| 824 | interpreted as for :func:`debug`. |
| 825 | |
| 826 | |
| 827 | .. function:: warning(msg[, *args[, **kwargs]]) |
| 828 | |
| 829 | Logs a message with level :const:`WARNING` on the root logger. The arguments are |
| 830 | interpreted as for :func:`debug`. |
| 831 | |
| 832 | |
| 833 | .. function:: error(msg[, *args[, **kwargs]]) |
| 834 | |
| 835 | Logs a message with level :const:`ERROR` on the root logger. The arguments are |
| 836 | interpreted as for :func:`debug`. |
| 837 | |
| 838 | |
| 839 | .. function:: critical(msg[, *args[, **kwargs]]) |
| 840 | |
| 841 | Logs a message with level :const:`CRITICAL` on the root logger. The arguments |
| 842 | are interpreted as for :func:`debug`. |
| 843 | |
| 844 | |
Vinay Sajip | 51f80c1 | 2014-04-15 23:11:15 +0100 | [diff] [blame] | 845 | .. function:: exception(msg[, *args[, **kwargs]]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 846 | |
| 847 | Logs a message with level :const:`ERROR` on the root logger. The arguments are |
| 848 | interpreted as for :func:`debug`. Exception info is added to the logging |
| 849 | message. This function should only be called from an exception handler. |
| 850 | |
| 851 | |
| 852 | .. function:: log(level, msg[, *args[, **kwargs]]) |
| 853 | |
| 854 | Logs a message with level *level* on the root logger. The other arguments are |
| 855 | interpreted as for :func:`debug`. |
| 856 | |
Vinay Sajip | ace08ab | 2014-01-15 13:27:58 +0000 | [diff] [blame] | 857 | .. note:: The above module-level convenience functions, which delegate to the |
| 858 | root logger, call :func:`basicConfig` to ensure that at least one handler |
| 859 | is available. Because of this, they should *not* be used in threads, |
| 860 | in versions of Python earlier than 2.7.1 and 3.2, unless at least one |
| 861 | handler has been added to the root logger *before* the threads are |
| 862 | started. In earlier versions of Python, due to a thread safety shortcoming |
| 863 | in :func:`basicConfig`, this can (under rare circumstances) lead to |
| 864 | handlers being added multiple times to the root logger, which can in turn |
| 865 | lead to multiple messages for the same event. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 866 | |
| 867 | .. function:: disable(lvl) |
| 868 | |
| 869 | Provides an overriding level *lvl* for all loggers which takes precedence over |
| 870 | the logger's own level. When the need arises to temporarily throttle logging |
Vinay Sajip | 2060e42 | 2010-03-17 15:05:57 +0000 | [diff] [blame] | 871 | output down across the whole application, this function can be useful. Its |
| 872 | effect is to disable all logging calls of severity *lvl* and below, so that |
| 873 | if you call it with a value of INFO, then all INFO and DEBUG events would be |
| 874 | discarded, whereas those of severity WARNING and above would be processed |
Vinay Sajip | e9cb5e9 | 2013-11-30 22:43:13 +0000 | [diff] [blame] | 875 | according to the logger's effective level. If |
| 876 | ``logging.disable(logging.NOTSET)`` is called, it effectively removes this |
| 877 | overriding level, so that logging output again depends on the effective |
| 878 | levels of individual loggers. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 879 | |
| 880 | |
| 881 | .. function:: addLevelName(lvl, levelName) |
| 882 | |
| 883 | Associates level *lvl* with text *levelName* in an internal dictionary, which is |
| 884 | used to map numeric levels to a textual representation, for example when a |
| 885 | :class:`Formatter` formats a message. This function can also be used to define |
| 886 | your own levels. The only constraints are that all levels used must be |
| 887 | registered using this function, levels should be positive integers and they |
| 888 | should increase in increasing order of severity. |
| 889 | |
Vinay Sajip | 3a5fc4b | 2013-01-08 11:18:42 +0000 | [diff] [blame] | 890 | .. note:: If you are thinking of defining your own levels, please see the |
| 891 | section on :ref:`custom-levels`. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 892 | |
| 893 | .. function:: getLevelName(lvl) |
| 894 | |
| 895 | Returns the textual representation of logging level *lvl*. If the level is one |
| 896 | of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`, |
| 897 | :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you |
| 898 | have associated levels with names using :func:`addLevelName` then the name you |
| 899 | have associated with *lvl* is returned. If a numeric value corresponding to one |
| 900 | of the defined levels is passed in, the corresponding string representation is |
| 901 | returned. Otherwise, the string "Level %s" % lvl is returned. |
| 902 | |
Vinay Sajip | f40a407 | 2014-09-18 17:46:58 +0100 | [diff] [blame] | 903 | .. note:: Integer levels should be used when e.g. setting levels on instances |
| 904 | of :class:`Logger` and handlers. This function is used to convert between |
| 905 | an integer level and the level name displayed in the formatted log output |
| 906 | by means of the ``%(levelname)s`` format specifier (see |
| 907 | :ref:`logrecord-attributes`). |
| 908 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 909 | |
| 910 | .. function:: makeLogRecord(attrdict) |
| 911 | |
| 912 | Creates and returns a new :class:`LogRecord` instance whose attributes are |
| 913 | defined by *attrdict*. This function is useful for taking a pickled |
| 914 | :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting |
| 915 | it as a :class:`LogRecord` instance at the receiving end. |
| 916 | |
| 917 | |
| 918 | .. function:: basicConfig([**kwargs]) |
| 919 | |
| 920 | Does basic configuration for the logging system by creating a |
| 921 | :class:`StreamHandler` with a default :class:`Formatter` and adding it to the |
Vinay Sajip | 1c77b7f | 2009-10-10 20:32:36 +0000 | [diff] [blame] | 922 | root logger. The functions :func:`debug`, :func:`info`, :func:`warning`, |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 923 | :func:`error` and :func:`critical` will call :func:`basicConfig` automatically |
| 924 | if no handlers are defined for the root logger. |
| 925 | |
Vinay Sajip | 1c77b7f | 2009-10-10 20:32:36 +0000 | [diff] [blame] | 926 | This function does nothing if the root logger already has handlers |
| 927 | configured for it. |
Georg Brandl | dfb5bbd | 2008-05-09 06:18:27 +0000 | [diff] [blame] | 928 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 929 | .. versionchanged:: 2.4 |
| 930 | Formerly, :func:`basicConfig` did not take any keyword arguments. |
| 931 | |
Vinay Sajip | 3a5fc4b | 2013-01-08 11:18:42 +0000 | [diff] [blame] | 932 | .. note:: This function should be called from the main thread before other |
| 933 | threads are started. In versions of Python prior to 2.7.1 and 3.2, if |
| 934 | this function is called from multiple threads, it is possible (in rare |
| 935 | circumstances) that a handler will be added to the root logger more than |
| 936 | once, leading to unexpected results such as messages being duplicated in |
| 937 | the log. |
Vinay Sajip | 89e1ae2 | 2010-09-17 10:09:04 +0000 | [diff] [blame] | 938 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 939 | The following keyword arguments are supported. |
| 940 | |
Georg Brandl | 44ea77b | 2013-03-28 13:28:44 +0100 | [diff] [blame] | 941 | .. tabularcolumns:: |l|L| |
| 942 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 943 | +--------------+---------------------------------------------+ |
| 944 | | Format | Description | |
| 945 | +==============+=============================================+ |
| 946 | | ``filename`` | Specifies that a FileHandler be created, | |
| 947 | | | using the specified filename, rather than a | |
| 948 | | | StreamHandler. | |
| 949 | +--------------+---------------------------------------------+ |
| 950 | | ``filemode`` | Specifies the mode to open the file, if | |
| 951 | | | filename is specified (if filemode is | |
| 952 | | | unspecified, it defaults to 'a'). | |
| 953 | +--------------+---------------------------------------------+ |
| 954 | | ``format`` | Use the specified format string for the | |
| 955 | | | handler. | |
| 956 | +--------------+---------------------------------------------+ |
| 957 | | ``datefmt`` | Use the specified date/time format. | |
| 958 | +--------------+---------------------------------------------+ |
| 959 | | ``level`` | Set the root logger level to the specified | |
| 960 | | | level. | |
| 961 | +--------------+---------------------------------------------+ |
| 962 | | ``stream`` | Use the specified stream to initialize the | |
| 963 | | | StreamHandler. Note that this argument is | |
| 964 | | | incompatible with 'filename' - if both are | |
| 965 | | | present, 'stream' is ignored. | |
| 966 | +--------------+---------------------------------------------+ |
| 967 | |
| 968 | |
| 969 | .. function:: shutdown() |
| 970 | |
| 971 | Informs the logging system to perform an orderly shutdown by flushing and |
Vinay Sajip | 91f0ee4 | 2008-03-16 21:35:58 +0000 | [diff] [blame] | 972 | closing all handlers. This should be called at application exit and no |
| 973 | further use of the logging system should be made after this call. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 974 | |
| 975 | |
| 976 | .. function:: setLoggerClass(klass) |
| 977 | |
| 978 | Tells the logging system to use the class *klass* when instantiating a logger. |
| 979 | The class should define :meth:`__init__` such that only a name argument is |
| 980 | required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This |
| 981 | function is typically called before any loggers are instantiated by applications |
| 982 | which need to use custom logger behavior. |
| 983 | |
| 984 | |
Vinay Sajip | 61afd26 | 2010-02-19 23:53:17 +0000 | [diff] [blame] | 985 | Integration with the warnings module |
| 986 | ------------------------------------ |
| 987 | |
| 988 | The :func:`captureWarnings` function can be used to integrate :mod:`logging` |
| 989 | with the :mod:`warnings` module. |
| 990 | |
| 991 | .. function:: captureWarnings(capture) |
| 992 | |
| 993 | This function is used to turn the capture of warnings by logging on and |
| 994 | off. |
| 995 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 996 | If *capture* is ``True``, warnings issued by the :mod:`warnings` module will |
| 997 | be redirected to the logging system. Specifically, a warning will be |
Vinay Sajip | 61afd26 | 2010-02-19 23:53:17 +0000 | [diff] [blame] | 998 | formatted using :func:`warnings.formatwarning` and the resulting string |
Éric Araujo | a318a3b | 2012-02-26 01:36:31 +0100 | [diff] [blame] | 999 | logged to a logger named ``'py.warnings'`` with a severity of :const:`WARNING`. |
Vinay Sajip | 61afd26 | 2010-02-19 23:53:17 +0000 | [diff] [blame] | 1000 | |
Georg Brandl | f6d36745 | 2010-03-12 10:02:03 +0000 | [diff] [blame] | 1001 | If *capture* is ``False``, the redirection of warnings to the logging system |
Vinay Sajip | 61afd26 | 2010-02-19 23:53:17 +0000 | [diff] [blame] | 1002 | will stop, and warnings will be redirected to their original destinations |
Éric Araujo | a318a3b | 2012-02-26 01:36:31 +0100 | [diff] [blame] | 1003 | (i.e. those in effect before ``captureWarnings(True)`` was called). |
Vinay Sajip | 61afd26 | 2010-02-19 23:53:17 +0000 | [diff] [blame] | 1004 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1005 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 1006 | .. seealso:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1007 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 1008 | Module :mod:`logging.config` |
| 1009 | Configuration API for the logging module. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1010 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 1011 | Module :mod:`logging.handlers` |
| 1012 | Useful handlers included with the logging module. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1013 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 1014 | :pep:`282` - A Logging System |
| 1015 | The proposal which described this feature for inclusion in the Python standard |
| 1016 | library. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1017 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 1018 | `Original Python logging package <http://www.red-dove.com/python_logging.html>`_ |
| 1019 | This is the original source for the :mod:`logging` package. The version of the |
| 1020 | package available from this site is suitable for use with Python 1.5.2, 2.1.x |
| 1021 | and 2.2.x, which do not include the :mod:`logging` package in the standard |
| 1022 | library. |
Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 1023 | |