| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1 | :mod:`logging` --- Logging facility for Python | 
|  | 2 | ============================================== | 
|  | 3 |  | 
|  | 4 | .. module:: logging | 
|  | 5 | :synopsis: Flexible error logging system for applications. | 
|  | 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 |  | 
|  | 14 | .. versionadded:: 2.3 | 
|  | 15 |  | 
|  | 16 | This module defines functions and classes which implement a flexible error | 
|  | 17 | logging system for applications. | 
|  | 18 |  | 
|  | 19 | Logging is performed by calling methods on instances of the :class:`Logger` | 
|  | 20 | class (hereafter called :dfn:`loggers`). Each instance has a name, and they are | 
| Georg Brandl | a739503 | 2007-10-21 12:15:05 +0000 | [diff] [blame] | 21 | conceptually arranged in a namespace hierarchy using dots (periods) as | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 22 | separators. For example, a logger named "scan" is the parent of loggers | 
|  | 23 | "scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want, | 
|  | 24 | and indicate the area of an application in which a logged message originates. | 
|  | 25 |  | 
|  | 26 | Logged messages also have levels of importance associated with them. The default | 
|  | 27 | levels provided are :const:`DEBUG`, :const:`INFO`, :const:`WARNING`, | 
|  | 28 | :const:`ERROR` and :const:`CRITICAL`. As a convenience, you indicate the | 
|  | 29 | importance of a logged message by calling an appropriate method of | 
|  | 30 | :class:`Logger`. The methods are :meth:`debug`, :meth:`info`, :meth:`warning`, | 
|  | 31 | :meth:`error` and :meth:`critical`, which mirror the default levels. You are not | 
|  | 32 | constrained to use these levels: you can specify your own and use a more general | 
|  | 33 | :class:`Logger` method, :meth:`log`, which takes an explicit level argument. | 
|  | 34 |  | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 35 |  | 
|  | 36 | Logging tutorial | 
|  | 37 | ---------------- | 
|  | 38 |  | 
|  | 39 | The key benefit of having the logging API provided by a standard library module | 
|  | 40 | is that all Python modules can participate in logging, so your application log | 
|  | 41 | can include messages from third-party modules. | 
|  | 42 |  | 
|  | 43 | It is, of course, possible to log messages with different verbosity levels or to | 
|  | 44 | different destinations.  Support for writing log messages to files, HTTP | 
|  | 45 | GET/POST locations, email via SMTP, generic sockets, or OS-specific logging | 
| Georg Brandl | 907a720 | 2008-02-22 12:31:45 +0000 | [diff] [blame] | 46 | mechanisms are all supported by the standard module.  You can also create your | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 47 | own log destination class if you have special requirements not met by any of the | 
|  | 48 | built-in classes. | 
|  | 49 |  | 
|  | 50 | Simple examples | 
|  | 51 | ^^^^^^^^^^^^^^^ | 
|  | 52 |  | 
|  | 53 | .. sectionauthor:: Doug Hellmann | 
|  | 54 | .. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>) | 
|  | 55 |  | 
|  | 56 | Most applications are probably going to want to log to a file, so let's start | 
|  | 57 | with that case. Using the :func:`basicConfig` function, we can set up the | 
| Vinay Sajip | 9a26aab | 2010-06-03 22:34:42 +0000 | [diff] [blame] | 58 | default handler so that debug messages are written to a file (in the example, | 
|  | 59 | we assume that you have the appropriate permissions to create a file called | 
| Vinay Sajip | 998cc24 | 2010-06-04 13:41:02 +0000 | [diff] [blame] | 60 | *example.log* in the current directory):: | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 61 |  | 
|  | 62 | import logging | 
| Vinay Sajip | 9a26aab | 2010-06-03 22:34:42 +0000 | [diff] [blame] | 63 | LOG_FILENAME = 'example.log' | 
| Vinay Sajip | f778bec | 2009-09-22 17:23:41 +0000 | [diff] [blame] | 64 | logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG) | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 65 |  | 
|  | 66 | logging.debug('This message should go to the log file') | 
|  | 67 |  | 
|  | 68 | And now if we open the file and look at what we have, we should find the log | 
|  | 69 | message:: | 
|  | 70 |  | 
|  | 71 | DEBUG:root:This message should go to the log file | 
|  | 72 |  | 
|  | 73 | If you run the script repeatedly, the additional log messages are appended to | 
| Eric Smith | e7dbebb | 2009-06-04 17:58:15 +0000 | [diff] [blame] | 74 | the file.  To create a new file each time, you can pass a *filemode* argument to | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 75 | :func:`basicConfig` with a value of ``'w'``.  Rather than managing the file size | 
|  | 76 | yourself, though, it is simpler to use a :class:`RotatingFileHandler`:: | 
|  | 77 |  | 
|  | 78 | import glob | 
|  | 79 | import logging | 
|  | 80 | import logging.handlers | 
|  | 81 |  | 
| Vinay Sajip | 998cc24 | 2010-06-04 13:41:02 +0000 | [diff] [blame] | 82 | LOG_FILENAME = 'logging_rotatingfile_example.out' | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 83 |  | 
|  | 84 | # Set up a specific logger with our desired output level | 
|  | 85 | my_logger = logging.getLogger('MyLogger') | 
|  | 86 | my_logger.setLevel(logging.DEBUG) | 
|  | 87 |  | 
|  | 88 | # Add the log message handler to the logger | 
|  | 89 | handler = logging.handlers.RotatingFileHandler( | 
|  | 90 | LOG_FILENAME, maxBytes=20, backupCount=5) | 
|  | 91 |  | 
|  | 92 | my_logger.addHandler(handler) | 
|  | 93 |  | 
|  | 94 | # Log some messages | 
|  | 95 | for i in range(20): | 
|  | 96 | my_logger.debug('i = %d' % i) | 
|  | 97 |  | 
|  | 98 | # See what files are created | 
|  | 99 | logfiles = glob.glob('%s*' % LOG_FILENAME) | 
|  | 100 |  | 
|  | 101 | for filename in logfiles: | 
|  | 102 | print filename | 
|  | 103 |  | 
|  | 104 | The result should be 6 separate files, each with part of the log history for the | 
|  | 105 | application:: | 
|  | 106 |  | 
| Vinay Sajip | 998cc24 | 2010-06-04 13:41:02 +0000 | [diff] [blame] | 107 | logging_rotatingfile_example.out | 
|  | 108 | logging_rotatingfile_example.out.1 | 
|  | 109 | logging_rotatingfile_example.out.2 | 
|  | 110 | logging_rotatingfile_example.out.3 | 
|  | 111 | logging_rotatingfile_example.out.4 | 
|  | 112 | logging_rotatingfile_example.out.5 | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 113 |  | 
| Vinay Sajip | 998cc24 | 2010-06-04 13:41:02 +0000 | [diff] [blame] | 114 | The most current file is always :file:`logging_rotatingfile_example.out`, | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 115 | and each time it reaches the size limit it is renamed with the suffix | 
|  | 116 | ``.1``. Each of the existing backup files is renamed to increment the suffix | 
| Eric Smith | e7dbebb | 2009-06-04 17:58:15 +0000 | [diff] [blame] | 117 | (``.1`` becomes ``.2``, etc.)  and the ``.6`` file is erased. | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 118 |  | 
|  | 119 | Obviously this example sets the log length much much too small as an extreme | 
|  | 120 | example.  You would want to set *maxBytes* to an appropriate value. | 
|  | 121 |  | 
|  | 122 | Another useful feature of the logging API is the ability to produce different | 
|  | 123 | messages at different log levels.  This allows you to instrument your code with | 
|  | 124 | debug messages, for example, but turning the log level down so that those debug | 
|  | 125 | messages are not written for your production system.  The default levels are | 
| Vinay Sajip | a7d4400 | 2009-10-28 23:28:16 +0000 | [diff] [blame] | 126 | ``NOTSET``, ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and ``CRITICAL``. | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 127 |  | 
|  | 128 | The logger, handler, and log message call each specify a level.  The log message | 
|  | 129 | is only emitted if the handler and logger are configured to emit messages of | 
|  | 130 | that level or lower.  For example, if a message is ``CRITICAL``, and the logger | 
|  | 131 | is set to ``ERROR``, the message is emitted.  If a message is a ``WARNING``, and | 
|  | 132 | the logger is set to produce only ``ERROR``\s, the message is not emitted:: | 
|  | 133 |  | 
|  | 134 | import logging | 
|  | 135 | import sys | 
|  | 136 |  | 
|  | 137 | LEVELS = {'debug': logging.DEBUG, | 
|  | 138 | 'info': logging.INFO, | 
|  | 139 | 'warning': logging.WARNING, | 
|  | 140 | 'error': logging.ERROR, | 
|  | 141 | 'critical': logging.CRITICAL} | 
|  | 142 |  | 
|  | 143 | if len(sys.argv) > 1: | 
|  | 144 | level_name = sys.argv[1] | 
|  | 145 | level = LEVELS.get(level_name, logging.NOTSET) | 
|  | 146 | logging.basicConfig(level=level) | 
|  | 147 |  | 
|  | 148 | logging.debug('This is a debug message') | 
|  | 149 | logging.info('This is an info message') | 
|  | 150 | logging.warning('This is a warning message') | 
|  | 151 | logging.error('This is an error message') | 
|  | 152 | logging.critical('This is a critical error message') | 
|  | 153 |  | 
|  | 154 | Run the script with an argument like 'debug' or 'warning' to see which messages | 
|  | 155 | show up at different levels:: | 
|  | 156 |  | 
|  | 157 | $ python logging_level_example.py debug | 
|  | 158 | DEBUG:root:This is a debug message | 
|  | 159 | INFO:root:This is an info message | 
|  | 160 | WARNING:root:This is a warning message | 
|  | 161 | ERROR:root:This is an error message | 
|  | 162 | CRITICAL:root:This is a critical error message | 
|  | 163 |  | 
|  | 164 | $ python logging_level_example.py info | 
|  | 165 | INFO:root:This is an info message | 
|  | 166 | WARNING:root:This is a warning message | 
|  | 167 | ERROR:root:This is an error message | 
|  | 168 | CRITICAL:root:This is a critical error message | 
|  | 169 |  | 
|  | 170 | You will notice that these log messages all have ``root`` embedded in them.  The | 
|  | 171 | logging module supports a hierarchy of loggers with different names.  An easy | 
|  | 172 | way to tell where a specific log message comes from is to use a separate logger | 
|  | 173 | object for each of your modules.  Each new logger "inherits" the configuration | 
|  | 174 | of its parent, and log messages sent to a logger include the name of that | 
|  | 175 | logger.  Optionally, each logger can be configured differently, so that messages | 
|  | 176 | from different modules are handled in different ways.  Let's look at a simple | 
|  | 177 | example of how to log from different modules so it is easy to trace the source | 
|  | 178 | of the message:: | 
|  | 179 |  | 
|  | 180 | import logging | 
|  | 181 |  | 
|  | 182 | logging.basicConfig(level=logging.WARNING) | 
|  | 183 |  | 
|  | 184 | logger1 = logging.getLogger('package1.module1') | 
|  | 185 | logger2 = logging.getLogger('package2.module2') | 
|  | 186 |  | 
|  | 187 | logger1.warning('This message comes from one module') | 
|  | 188 | logger2.warning('And this message comes from another module') | 
|  | 189 |  | 
|  | 190 | And the output:: | 
|  | 191 |  | 
|  | 192 | $ python logging_modules_example.py | 
|  | 193 | WARNING:package1.module1:This message comes from one module | 
|  | 194 | WARNING:package2.module2:And this message comes from another module | 
|  | 195 |  | 
|  | 196 | There are many more options for configuring logging, including different log | 
|  | 197 | message formatting options, having messages delivered to multiple destinations, | 
|  | 198 | and changing the configuration of a long-running application on the fly using a | 
|  | 199 | socket interface.  All of these options are covered in depth in the library | 
|  | 200 | module documentation. | 
|  | 201 |  | 
|  | 202 | Loggers | 
|  | 203 | ^^^^^^^ | 
|  | 204 |  | 
|  | 205 | The logging library takes a modular approach and offers the several categories | 
|  | 206 | of components: loggers, handlers, filters, and formatters.  Loggers expose the | 
|  | 207 | interface that application code directly uses.  Handlers send the log records to | 
|  | 208 | the appropriate destination. Filters provide a finer grained facility for | 
|  | 209 | determining which log records to send on to a handler.  Formatters specify the | 
|  | 210 | layout of the resultant log record. | 
|  | 211 |  | 
|  | 212 | :class:`Logger` objects have a threefold job.  First, they expose several | 
|  | 213 | methods to application code so that applications can log messages at runtime. | 
|  | 214 | Second, logger objects determine which log messages to act upon based upon | 
|  | 215 | severity (the default filtering facility) or filter objects.  Third, logger | 
|  | 216 | objects pass along relevant log messages to all interested log handlers. | 
|  | 217 |  | 
|  | 218 | The most widely used methods on logger objects fall into two categories: | 
|  | 219 | configuration and message sending. | 
|  | 220 |  | 
|  | 221 | * :meth:`Logger.setLevel` specifies the lowest-severity log message a logger | 
|  | 222 | will handle, where debug is the lowest built-in severity level and critical is | 
|  | 223 | the highest built-in severity.  For example, if the severity level is info, | 
|  | 224 | the logger will handle only info, warning, error, and critical messages and | 
|  | 225 | will ignore debug messages. | 
|  | 226 |  | 
|  | 227 | * :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter | 
|  | 228 | objects from the logger object.  This tutorial does not address filters. | 
|  | 229 |  | 
|  | 230 | With the logger object configured, the following methods create log messages: | 
|  | 231 |  | 
|  | 232 | * :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`, | 
|  | 233 | :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with | 
|  | 234 | a message and a level that corresponds to their respective method names. The | 
|  | 235 | message is actually a format string, which may contain the standard string | 
|  | 236 | substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on.  The | 
|  | 237 | rest of their arguments is a list of objects that correspond with the | 
|  | 238 | substitution fields in the message.  With regard to :const:`**kwargs`, the | 
|  | 239 | logging methods care only about a keyword of :const:`exc_info` and use it to | 
|  | 240 | determine whether to log exception information. | 
|  | 241 |  | 
|  | 242 | * :meth:`Logger.exception` creates a log message similar to | 
|  | 243 | :meth:`Logger.error`.  The difference is that :meth:`Logger.exception` dumps a | 
|  | 244 | stack trace along with it.  Call this method only from an exception handler. | 
|  | 245 |  | 
|  | 246 | * :meth:`Logger.log` takes a log level as an explicit argument.  This is a | 
|  | 247 | little more verbose for logging messages than using the log level convenience | 
|  | 248 | methods listed above, but this is how to log at custom log levels. | 
|  | 249 |  | 
| Brett Cannon | 499969a | 2008-02-25 05:33:07 +0000 | [diff] [blame] | 250 | :func:`getLogger` returns a reference to a logger instance with the specified | 
| Vinay Sajip | 80eed3e | 2010-07-06 15:08:55 +0000 | [diff] [blame] | 251 | name if it is provided, or ``root`` if not.  The names are period-separated | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 252 | hierarchical structures.  Multiple calls to :func:`getLogger` with the same name | 
|  | 253 | will return a reference to the same logger object.  Loggers that are further | 
|  | 254 | down in the hierarchical list are children of loggers higher up in the list. | 
|  | 255 | For example, given a logger with a name of ``foo``, loggers with names of | 
| Vinay Sajip | ccd8bc8 | 2010-04-06 22:32:37 +0000 | [diff] [blame] | 256 | ``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``. | 
|  | 257 | Child loggers propagate messages up to the handlers associated with their | 
|  | 258 | ancestor loggers.  Because of this, it is unnecessary to define and configure | 
|  | 259 | handlers for all the loggers an application uses. It is sufficient to | 
|  | 260 | configure handlers for a top-level logger and create child loggers as needed. | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 261 |  | 
|  | 262 |  | 
|  | 263 | Handlers | 
|  | 264 | ^^^^^^^^ | 
|  | 265 |  | 
|  | 266 | :class:`Handler` objects are responsible for dispatching the appropriate log | 
|  | 267 | messages (based on the log messages' severity) to the handler's specified | 
|  | 268 | destination.  Logger objects can add zero or more handler objects to themselves | 
|  | 269 | with an :func:`addHandler` method.  As an example scenario, an application may | 
|  | 270 | want to send all log messages to a log file, all log messages of error or higher | 
|  | 271 | to stdout, and all messages of critical to an email address.  This scenario | 
| Georg Brandl | 907a720 | 2008-02-22 12:31:45 +0000 | [diff] [blame] | 272 | requires three individual handlers where each handler is responsible for sending | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 273 | messages of a specific severity to a specific location. | 
|  | 274 |  | 
|  | 275 | The standard library includes quite a few handler types; this tutorial uses only | 
|  | 276 | :class:`StreamHandler` and :class:`FileHandler` in its examples. | 
|  | 277 |  | 
|  | 278 | There are very few methods in a handler for application developers to concern | 
|  | 279 | themselves with.  The only handler methods that seem relevant for application | 
|  | 280 | developers who are using the built-in handler objects (that is, not creating | 
|  | 281 | custom handlers) are the following configuration methods: | 
|  | 282 |  | 
|  | 283 | * The :meth:`Handler.setLevel` method, just as in logger objects, specifies the | 
|  | 284 | lowest severity that will be dispatched to the appropriate destination.  Why | 
|  | 285 | are there two :func:`setLevel` methods?  The level set in the logger | 
|  | 286 | determines which severity of messages it will pass to its handlers.  The level | 
|  | 287 | set in each handler determines which messages that handler will send on. | 
| Vinay Sajip | ccd8bc8 | 2010-04-06 22:32:37 +0000 | [diff] [blame] | 288 |  | 
|  | 289 | * :func:`setFormatter` selects a Formatter object for this handler to use. | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 290 |  | 
|  | 291 | * :func:`addFilter` and :func:`removeFilter` respectively configure and | 
|  | 292 | deconfigure filter objects on handlers. | 
|  | 293 |  | 
| Vinay Sajip | ccd8bc8 | 2010-04-06 22:32:37 +0000 | [diff] [blame] | 294 | Application code should not directly instantiate and use instances of | 
|  | 295 | :class:`Handler`.  Instead, the :class:`Handler` class is a base class that | 
| Vinay Sajip | 497256b | 2010-04-07 09:40:52 +0000 | [diff] [blame] | 296 | defines the interface that all handlers should have and establishes some | 
| Vinay Sajip | ccd8bc8 | 2010-04-06 22:32:37 +0000 | [diff] [blame] | 297 | default behavior that child classes can use (or override). | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 298 |  | 
|  | 299 |  | 
|  | 300 | Formatters | 
|  | 301 | ^^^^^^^^^^ | 
|  | 302 |  | 
|  | 303 | Formatter objects configure the final order, structure, and contents of the log | 
| Brett Cannon | 499969a | 2008-02-25 05:33:07 +0000 | [diff] [blame] | 304 | message.  Unlike the base :class:`logging.Handler` class, application code may | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 305 | instantiate formatter classes, although you could likely subclass the formatter | 
|  | 306 | if your application needs special behavior.  The constructor takes two optional | 
|  | 307 | arguments: a message format string and a date format string.  If there is no | 
|  | 308 | message format string, the default is to use the raw message.  If there is no | 
|  | 309 | date format string, the default date format is:: | 
|  | 310 |  | 
|  | 311 | %Y-%m-%d %H:%M:%S | 
|  | 312 |  | 
|  | 313 | with the milliseconds tacked on at the end. | 
|  | 314 |  | 
|  | 315 | The message format string uses ``%(<dictionary key>)s`` styled string | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 316 | substitution; the possible keys are documented in :ref:`formatter`. | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 317 |  | 
|  | 318 | The following message format string will log the time in a human-readable | 
|  | 319 | format, the severity of the message, and the contents of the message, in that | 
|  | 320 | order:: | 
|  | 321 |  | 
|  | 322 | "%(asctime)s - %(levelname)s - %(message)s" | 
|  | 323 |  | 
| Vinay Sajip | 8d8e615 | 2010-08-30 18:10:03 +0000 | [diff] [blame] | 324 | Formatters use a user-configurable function to convert the creation time of a | 
|  | 325 | record to a tuple. By default, :func:`time.localtime` is used; to change this | 
|  | 326 | for a particular formatter instance, set the ``converter`` attribute of the | 
|  | 327 | instance to a function with the same signature as :func:`time.localtime` or | 
|  | 328 | :func:`time.gmtime`. To change it for all formatters, for example if you want | 
|  | 329 | all logging times to be shown in GMT, set the ``converter`` attribute in the | 
|  | 330 | Formatter class (to ``time.gmtime`` for GMT display). | 
|  | 331 |  | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 332 |  | 
|  | 333 | Configuring Logging | 
|  | 334 | ^^^^^^^^^^^^^^^^^^^ | 
|  | 335 |  | 
| Andrew M. Kuchling | f09bc66 | 2010-05-12 18:56:48 +0000 | [diff] [blame] | 336 | Programmers can configure logging in three ways: | 
|  | 337 |  | 
|  | 338 | 1. Creating loggers, handlers, and formatters explicitly using Python | 
|  | 339 | code that calls the configuration methods listed above. | 
|  | 340 | 2. Creating a logging config file and reading it using the :func:`fileConfig` | 
|  | 341 | function. | 
|  | 342 | 3. Creating a dictionary of configuration information and passing it | 
|  | 343 | to the :func:`dictConfig` function. | 
|  | 344 |  | 
|  | 345 | The following example configures a very simple logger, a console | 
| Vinay Sajip | a38cd52 | 2010-05-18 08:16:27 +0000 | [diff] [blame] | 346 | handler, and a simple formatter using Python code:: | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 347 |  | 
|  | 348 | import logging | 
|  | 349 |  | 
|  | 350 | # create logger | 
|  | 351 | logger = logging.getLogger("simple_example") | 
|  | 352 | logger.setLevel(logging.DEBUG) | 
| Andrew M. Kuchling | f09bc66 | 2010-05-12 18:56:48 +0000 | [diff] [blame] | 353 |  | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 354 | # create console handler and set level to debug | 
|  | 355 | ch = logging.StreamHandler() | 
|  | 356 | ch.setLevel(logging.DEBUG) | 
| Andrew M. Kuchling | f09bc66 | 2010-05-12 18:56:48 +0000 | [diff] [blame] | 357 |  | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 358 | # create formatter | 
|  | 359 | formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") | 
| Andrew M. Kuchling | f09bc66 | 2010-05-12 18:56:48 +0000 | [diff] [blame] | 360 |  | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 361 | # add formatter to ch | 
|  | 362 | ch.setFormatter(formatter) | 
| Andrew M. Kuchling | f09bc66 | 2010-05-12 18:56:48 +0000 | [diff] [blame] | 363 |  | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 364 | # add ch to logger | 
|  | 365 | logger.addHandler(ch) | 
|  | 366 |  | 
|  | 367 | # "application" code | 
|  | 368 | logger.debug("debug message") | 
|  | 369 | logger.info("info message") | 
|  | 370 | logger.warn("warn message") | 
|  | 371 | logger.error("error message") | 
|  | 372 | logger.critical("critical message") | 
|  | 373 |  | 
|  | 374 | Running this module from the command line produces the following output:: | 
|  | 375 |  | 
|  | 376 | $ python simple_logging_module.py | 
|  | 377 | 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message | 
|  | 378 | 2005-03-19 15:10:26,620 - simple_example - INFO - info message | 
|  | 379 | 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message | 
|  | 380 | 2005-03-19 15:10:26,697 - simple_example - ERROR - error message | 
|  | 381 | 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message | 
|  | 382 |  | 
|  | 383 | The following Python module creates a logger, handler, and formatter nearly | 
|  | 384 | identical to those in the example listed above, with the only difference being | 
|  | 385 | the names of the objects:: | 
|  | 386 |  | 
|  | 387 | import logging | 
|  | 388 | import logging.config | 
|  | 389 |  | 
|  | 390 | logging.config.fileConfig("logging.conf") | 
|  | 391 |  | 
|  | 392 | # create logger | 
|  | 393 | logger = logging.getLogger("simpleExample") | 
|  | 394 |  | 
|  | 395 | # "application" code | 
|  | 396 | logger.debug("debug message") | 
|  | 397 | logger.info("info message") | 
|  | 398 | logger.warn("warn message") | 
|  | 399 | logger.error("error message") | 
|  | 400 | logger.critical("critical message") | 
|  | 401 |  | 
|  | 402 | Here is the logging.conf file:: | 
|  | 403 |  | 
|  | 404 | [loggers] | 
|  | 405 | keys=root,simpleExample | 
|  | 406 |  | 
|  | 407 | [handlers] | 
|  | 408 | keys=consoleHandler | 
|  | 409 |  | 
|  | 410 | [formatters] | 
|  | 411 | keys=simpleFormatter | 
|  | 412 |  | 
|  | 413 | [logger_root] | 
|  | 414 | level=DEBUG | 
|  | 415 | handlers=consoleHandler | 
|  | 416 |  | 
|  | 417 | [logger_simpleExample] | 
|  | 418 | level=DEBUG | 
|  | 419 | handlers=consoleHandler | 
|  | 420 | qualname=simpleExample | 
|  | 421 | propagate=0 | 
|  | 422 |  | 
|  | 423 | [handler_consoleHandler] | 
|  | 424 | class=StreamHandler | 
|  | 425 | level=DEBUG | 
|  | 426 | formatter=simpleFormatter | 
|  | 427 | args=(sys.stdout,) | 
|  | 428 |  | 
|  | 429 | [formatter_simpleFormatter] | 
|  | 430 | format=%(asctime)s - %(name)s - %(levelname)s - %(message)s | 
|  | 431 | datefmt= | 
|  | 432 |  | 
|  | 433 | The output is nearly identical to that of the non-config-file-based example:: | 
|  | 434 |  | 
|  | 435 | $ python simple_logging_config.py | 
|  | 436 | 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message | 
|  | 437 | 2005-03-19 15:38:55,979 - simpleExample - INFO - info message | 
|  | 438 | 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message | 
|  | 439 | 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message | 
|  | 440 | 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message | 
|  | 441 |  | 
|  | 442 | You can see that the config file approach has a few advantages over the Python | 
|  | 443 | code approach, mainly separation of configuration and code and the ability of | 
|  | 444 | noncoders to easily modify the logging properties. | 
|  | 445 |  | 
| Vinay Sajip | 0e6e97d | 2010-02-04 20:23:45 +0000 | [diff] [blame] | 446 | Note that the class names referenced in config files need to be either relative | 
|  | 447 | to the logging module, or absolute values which can be resolved using normal | 
| Georg Brandl | f6d36745 | 2010-03-12 10:02:03 +0000 | [diff] [blame] | 448 | import mechanisms. Thus, you could use either :class:`handlers.WatchedFileHandler` | 
|  | 449 | (relative to the logging module) or :class:`mypackage.mymodule.MyHandler` (for a | 
|  | 450 | class defined in package :mod:`mypackage` and module :mod:`mymodule`, where | 
|  | 451 | :mod:`mypackage` is available on the Python import path). | 
| Vinay Sajip | 0e6e97d | 2010-02-04 20:23:45 +0000 | [diff] [blame] | 452 |  | 
| Vinay Sajip | c76defc | 2010-05-21 17:41:34 +0000 | [diff] [blame] | 453 | .. versionchanged:: 2.7 | 
|  | 454 |  | 
|  | 455 | In Python 2.7, a new means of configuring logging has been introduced, using | 
|  | 456 | dictionaries to hold configuration information. This provides a superset of the | 
|  | 457 | functionality of the config-file-based approach outlined above, and is the | 
|  | 458 | recommended configuration method for new applications and deployments. Because | 
|  | 459 | a Python dictionary is used to hold configuration information, and since you | 
|  | 460 | can populate that dictionary using different means, you have more options for | 
|  | 461 | configuration. For example, you can use a configuration file in JSON format, | 
|  | 462 | or, if you have access to YAML processing functionality, a file in YAML | 
|  | 463 | format, to populate the configuration dictionary. Or, of course, you can | 
|  | 464 | construct the dictionary in Python code, receive it in pickled form over a | 
|  | 465 | socket, or use whatever approach makes sense for your application. | 
|  | 466 |  | 
|  | 467 | Here's an example of the same configuration as above, in YAML format for | 
|  | 468 | the new dictionary-based approach:: | 
|  | 469 |  | 
|  | 470 | version: 1 | 
|  | 471 | formatters: | 
|  | 472 | simple: | 
|  | 473 | format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s | 
|  | 474 | handlers: | 
|  | 475 | console: | 
|  | 476 | class: logging.StreamHandler | 
|  | 477 | level: DEBUG | 
|  | 478 | formatter: simple | 
|  | 479 | stream: ext://sys.stdout | 
|  | 480 | loggers: | 
|  | 481 | simpleExample: | 
|  | 482 | level: DEBUG | 
|  | 483 | handlers: [console] | 
|  | 484 | propagate: no | 
|  | 485 | root: | 
|  | 486 | level: DEBUG | 
|  | 487 | handlers: [console] | 
|  | 488 |  | 
|  | 489 | For more information about logging using a dictionary, see | 
|  | 490 | :ref:`logging-config-api`. | 
|  | 491 |  | 
| Vinay Sajip | 99505c8 | 2009-01-10 13:38:04 +0000 | [diff] [blame] | 492 | .. _library-config: | 
|  | 493 |  | 
| Vinay Sajip | 34bfda5 | 2008-09-01 15:08:07 +0000 | [diff] [blame] | 494 | Configuring Logging for a Library | 
|  | 495 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | 
|  | 496 |  | 
|  | 497 | When developing a library which uses logging, some consideration needs to be | 
|  | 498 | given to its configuration. If the using application does not use logging, and | 
|  | 499 | library code makes logging calls, then a one-off message "No handlers could be | 
|  | 500 | found for logger X.Y.Z" is printed to the console. This message is intended | 
|  | 501 | to catch mistakes in logging configuration, but will confuse an application | 
|  | 502 | developer who is not aware of logging by the library. | 
|  | 503 |  | 
|  | 504 | In addition to documenting how a library uses logging, a good way to configure | 
|  | 505 | library logging so that it does not cause a spurious message is to add a | 
|  | 506 | handler which does nothing. This avoids the message being printed, since a | 
|  | 507 | handler will be found: it just doesn't produce any output. If the library user | 
|  | 508 | configures logging for application use, presumably that configuration will add | 
|  | 509 | some handlers, and if levels are suitably configured then logging calls made | 
|  | 510 | in library code will send output to those handlers, as normal. | 
|  | 511 |  | 
|  | 512 | A do-nothing handler can be simply defined as follows:: | 
|  | 513 |  | 
|  | 514 | import logging | 
|  | 515 |  | 
|  | 516 | class NullHandler(logging.Handler): | 
|  | 517 | def emit(self, record): | 
|  | 518 | pass | 
|  | 519 |  | 
|  | 520 | An instance of this handler should be added to the top-level logger of the | 
|  | 521 | logging namespace used by the library. If all logging by a library *foo* is | 
|  | 522 | done using loggers with names matching "foo.x.y", then the code:: | 
|  | 523 |  | 
|  | 524 | import logging | 
|  | 525 |  | 
|  | 526 | h = NullHandler() | 
|  | 527 | logging.getLogger("foo").addHandler(h) | 
|  | 528 |  | 
|  | 529 | should have the desired effect. If an organisation produces a number of | 
|  | 530 | libraries, then the logger name specified can be "orgname.foo" rather than | 
|  | 531 | just "foo". | 
|  | 532 |  | 
| Vinay Sajip | 47ca122 | 2010-09-27 13:53:47 +0000 | [diff] [blame] | 533 | **PLEASE NOTE:** It is strongly advised that you *do not add any handlers other | 
|  | 534 | than* :class:`NullHandler` *to your library's loggers*. This is because the | 
|  | 535 | configuration of handlers is the prerogative of the application developer who | 
|  | 536 | uses your library. The application developer knows their target audience and | 
|  | 537 | what handlers are most appropriate for their application: if you add handlers | 
|  | 538 | "under the hood", you might well interfere with their ability to carry out | 
|  | 539 | unit tests and deliver logs which suit their requirements. | 
|  | 540 |  | 
| Vinay Sajip | 213faca | 2008-12-03 23:22:58 +0000 | [diff] [blame] | 541 | .. versionadded:: 2.7 | 
|  | 542 |  | 
|  | 543 | The :class:`NullHandler` class was not present in previous versions, but is now | 
|  | 544 | included, so that it need not be defined in library code. | 
|  | 545 |  | 
|  | 546 |  | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 547 |  | 
|  | 548 | Logging Levels | 
|  | 549 | -------------- | 
|  | 550 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 551 | The numeric values of logging levels are given in the following table. These are | 
|  | 552 | primarily of interest if you want to define your own levels, and need them to | 
|  | 553 | have specific values relative to the predefined levels. If you define a level | 
|  | 554 | with the same numeric value, it overwrites the predefined value; the predefined | 
|  | 555 | name is lost. | 
|  | 556 |  | 
|  | 557 | +--------------+---------------+ | 
|  | 558 | | Level        | Numeric value | | 
|  | 559 | +==============+===============+ | 
|  | 560 | | ``CRITICAL`` | 50            | | 
|  | 561 | +--------------+---------------+ | 
|  | 562 | | ``ERROR``    | 40            | | 
|  | 563 | +--------------+---------------+ | 
|  | 564 | | ``WARNING``  | 30            | | 
|  | 565 | +--------------+---------------+ | 
|  | 566 | | ``INFO``     | 20            | | 
|  | 567 | +--------------+---------------+ | 
|  | 568 | | ``DEBUG``    | 10            | | 
|  | 569 | +--------------+---------------+ | 
|  | 570 | | ``NOTSET``   | 0             | | 
|  | 571 | +--------------+---------------+ | 
|  | 572 |  | 
|  | 573 | Levels can also be associated with loggers, being set either by the developer or | 
|  | 574 | through loading a saved logging configuration. When a logging method is called | 
|  | 575 | on a logger, the logger compares its own level with the level associated with | 
|  | 576 | the method call. If the logger's level is higher than the method call's, no | 
|  | 577 | logging message is actually generated. This is the basic mechanism controlling | 
|  | 578 | the verbosity of logging output. | 
|  | 579 |  | 
|  | 580 | Logging messages are encoded as instances of the :class:`LogRecord` class. When | 
|  | 581 | a logger decides to actually log an event, a :class:`LogRecord` instance is | 
|  | 582 | created from the logging message. | 
|  | 583 |  | 
|  | 584 | Logging messages are subjected to a dispatch mechanism through the use of | 
|  | 585 | :dfn:`handlers`, which are instances of subclasses of the :class:`Handler` | 
|  | 586 | class. Handlers are responsible for ensuring that a logged message (in the form | 
|  | 587 | of a :class:`LogRecord`) ends up in a particular location (or set of locations) | 
|  | 588 | which is useful for the target audience for that message (such as end users, | 
|  | 589 | support desk staff, system administrators, developers). Handlers are passed | 
|  | 590 | :class:`LogRecord` instances intended for particular destinations. Each logger | 
|  | 591 | can have zero, one or more handlers associated with it (via the | 
|  | 592 | :meth:`addHandler` method of :class:`Logger`). In addition to any handlers | 
|  | 593 | directly associated with a logger, *all handlers associated with all ancestors | 
| Vinay Sajip | ccd8bc8 | 2010-04-06 22:32:37 +0000 | [diff] [blame] | 594 | of the logger* are called to dispatch the message (unless the *propagate* flag | 
|  | 595 | for a logger is set to a false value, at which point the passing to ancestor | 
|  | 596 | handlers stops). | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 597 |  | 
|  | 598 | Just as for loggers, handlers can have levels associated with them. A handler's | 
|  | 599 | level acts as a filter in the same way as a logger's level does. If a handler | 
|  | 600 | decides to actually dispatch an event, the :meth:`emit` method is used to send | 
|  | 601 | the message to its destination. Most user-defined subclasses of :class:`Handler` | 
|  | 602 | will need to override this :meth:`emit`. | 
|  | 603 |  | 
| Vinay Sajip | 89e1ae2 | 2010-09-17 10:09:04 +0000 | [diff] [blame] | 604 | .. _custom-levels: | 
|  | 605 |  | 
|  | 606 | Custom Levels | 
|  | 607 | ^^^^^^^^^^^^^ | 
|  | 608 |  | 
|  | 609 | Defining your own levels is possible, but should not be necessary, as the | 
|  | 610 | existing levels have been chosen on the basis of practical experience. | 
|  | 611 | However, if you are convinced that you need custom levels, great care should | 
|  | 612 | be exercised when doing this, and it is possibly *a very bad idea to define | 
|  | 613 | custom levels if you are developing a library*. That's because if multiple | 
|  | 614 | library authors all define their own custom levels, there is a chance that | 
|  | 615 | the logging output from such multiple libraries used together will be | 
|  | 616 | difficult for the using developer to control and/or interpret, because a | 
|  | 617 | given numeric value might mean different things for different libraries. | 
|  | 618 |  | 
|  | 619 |  | 
| Vinay Sajip | b5902e6 | 2009-01-15 22:48:13 +0000 | [diff] [blame] | 620 | Useful Handlers | 
|  | 621 | --------------- | 
|  | 622 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 623 | In addition to the base :class:`Handler` class, many useful subclasses are | 
|  | 624 | provided: | 
|  | 625 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 626 | #. :ref:`stream-handler` instances send error messages to streams (file-like | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 627 | objects). | 
|  | 628 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 629 | #. :ref:`file-handler` instances send error messages to disk files. | 
| Vinay Sajip | b1a15e4 | 2009-01-15 23:04:47 +0000 | [diff] [blame] | 630 |  | 
| Vinay Sajip | b5902e6 | 2009-01-15 22:48:13 +0000 | [diff] [blame] | 631 | #. :class:`BaseRotatingHandler` is the base class for handlers that | 
| Vinay Sajip | 99234c5 | 2009-01-12 20:36:18 +0000 | [diff] [blame] | 632 | rotate log files at a certain point. It is not meant to be  instantiated | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 633 | directly. Instead, use :ref:`rotating-file-handler` or | 
|  | 634 | :ref:`timed-rotating-file-handler`. | 
| Vinay Sajip | c2211ad | 2009-01-10 19:22:57 +0000 | [diff] [blame] | 635 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 636 | #. :ref:`rotating-file-handler` instances send error messages to disk | 
| Vinay Sajip | b5902e6 | 2009-01-15 22:48:13 +0000 | [diff] [blame] | 637 | files, with support for maximum log file sizes and log file rotation. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 638 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 639 | #. :ref:`timed-rotating-file-handler` instances send error messages to | 
| Vinay Sajip | b5902e6 | 2009-01-15 22:48:13 +0000 | [diff] [blame] | 640 | disk files, rotating the log file at certain timed intervals. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 641 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 642 | #. :ref:`socket-handler` instances send error messages to TCP/IP | 
| Vinay Sajip | b5902e6 | 2009-01-15 22:48:13 +0000 | [diff] [blame] | 643 | sockets. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 644 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 645 | #. :ref:`datagram-handler` instances send error messages to UDP | 
| Vinay Sajip | b5902e6 | 2009-01-15 22:48:13 +0000 | [diff] [blame] | 646 | sockets. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 647 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 648 | #. :ref:`smtp-handler` instances send error messages to a designated | 
| Vinay Sajip | b5902e6 | 2009-01-15 22:48:13 +0000 | [diff] [blame] | 649 | email address. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 650 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 651 | #. :ref:`syslog-handler` instances send error messages to a Unix | 
| Vinay Sajip | b5902e6 | 2009-01-15 22:48:13 +0000 | [diff] [blame] | 652 | syslog daemon, possibly on a remote machine. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 653 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 654 | #. :ref:`nt-eventlog-handler` instances send error messages to a | 
| Vinay Sajip | b5902e6 | 2009-01-15 22:48:13 +0000 | [diff] [blame] | 655 | Windows NT/2000/XP event log. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 656 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 657 | #. :ref:`memory-handler` instances send error messages to a buffer | 
| Vinay Sajip | b5902e6 | 2009-01-15 22:48:13 +0000 | [diff] [blame] | 658 | in memory, which is flushed whenever specific criteria are met. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 659 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 660 | #. :ref:`http-handler` instances send error messages to an HTTP | 
| Vinay Sajip | b5902e6 | 2009-01-15 22:48:13 +0000 | [diff] [blame] | 661 | server using either ``GET`` or ``POST`` semantics. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 662 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 663 | #. :ref:`watched-file-handler` instances watch the file they are | 
| Vinay Sajip | b5902e6 | 2009-01-15 22:48:13 +0000 | [diff] [blame] | 664 | logging to. If the file changes, it is closed and reopened using the file | 
|  | 665 | name. This handler is only useful on Unix-like systems; Windows does not | 
|  | 666 | support the underlying mechanism used. | 
| Vinay Sajip | c2211ad | 2009-01-10 19:22:57 +0000 | [diff] [blame] | 667 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 668 | #. :ref:`null-handler` instances do nothing with error messages. They are used | 
| Vinay Sajip | 213faca | 2008-12-03 23:22:58 +0000 | [diff] [blame] | 669 | by library developers who want to use logging, but want to avoid the "No | 
|  | 670 | handlers could be found for logger XXX" message which can be displayed if | 
| Vinay Sajip | 99505c8 | 2009-01-10 13:38:04 +0000 | [diff] [blame] | 671 | the library user has not configured logging. See :ref:`library-config` for | 
|  | 672 | more information. | 
| Vinay Sajip | 213faca | 2008-12-03 23:22:58 +0000 | [diff] [blame] | 673 |  | 
|  | 674 | .. versionadded:: 2.7 | 
|  | 675 |  | 
|  | 676 | The :class:`NullHandler` class was not present in previous versions. | 
|  | 677 |  | 
| Vinay Sajip | 7cc9755 | 2008-12-30 07:01:25 +0000 | [diff] [blame] | 678 | The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler` | 
|  | 679 | classes are defined in the core logging package. The other handlers are | 
|  | 680 | defined in a sub- module, :mod:`logging.handlers`. (There is also another | 
|  | 681 | sub-module, :mod:`logging.config`, for configuration functionality.) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 682 |  | 
|  | 683 | Logged messages are formatted for presentation through instances of the | 
|  | 684 | :class:`Formatter` class. They are initialized with a format string suitable for | 
|  | 685 | use with the % operator and a dictionary. | 
|  | 686 |  | 
|  | 687 | For formatting multiple messages in a batch, instances of | 
|  | 688 | :class:`BufferingFormatter` can be used. In addition to the format string (which | 
|  | 689 | is applied to each message in the batch), there is provision for header and | 
|  | 690 | trailer format strings. | 
|  | 691 |  | 
|  | 692 | When filtering based on logger level and/or handler level is not enough, | 
|  | 693 | instances of :class:`Filter` can be added to both :class:`Logger` and | 
|  | 694 | :class:`Handler` instances (through their :meth:`addFilter` method). Before | 
|  | 695 | deciding to process a message further, both loggers and handlers consult all | 
|  | 696 | their filters for permission. If any filter returns a false value, the message | 
|  | 697 | is not processed further. | 
|  | 698 |  | 
|  | 699 | The basic :class:`Filter` functionality allows filtering by specific logger | 
|  | 700 | name. If this feature is used, messages sent to the named logger and its | 
|  | 701 | children are allowed through the filter, and all others dropped. | 
|  | 702 |  | 
| Vinay Sajip | b5902e6 | 2009-01-15 22:48:13 +0000 | [diff] [blame] | 703 | Module-Level Functions | 
|  | 704 | ---------------------- | 
|  | 705 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 706 | In addition to the classes described above, there are a number of module- level | 
|  | 707 | functions. | 
|  | 708 |  | 
|  | 709 |  | 
|  | 710 | .. function:: getLogger([name]) | 
|  | 711 |  | 
|  | 712 | Return a logger with the specified name or, if no name is specified, return a | 
|  | 713 | logger which is the root logger of the hierarchy. If specified, the name is | 
|  | 714 | typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*. | 
|  | 715 | Choice of these names is entirely up to the developer who is using logging. | 
|  | 716 |  | 
|  | 717 | All calls to this function with a given name return the same logger instance. | 
|  | 718 | This means that logger instances never need to be passed between different parts | 
|  | 719 | of an application. | 
|  | 720 |  | 
|  | 721 |  | 
|  | 722 | .. function:: getLoggerClass() | 
|  | 723 |  | 
|  | 724 | Return either the standard :class:`Logger` class, or the last class passed to | 
|  | 725 | :func:`setLoggerClass`. This function may be called from within a new class | 
|  | 726 | definition, to ensure that installing a customised :class:`Logger` class will | 
|  | 727 | not undo customisations already applied by other code. For example:: | 
|  | 728 |  | 
|  | 729 | class MyLogger(logging.getLoggerClass()): | 
|  | 730 | # ... override behaviour here | 
|  | 731 |  | 
|  | 732 |  | 
|  | 733 | .. function:: debug(msg[, *args[, **kwargs]]) | 
|  | 734 |  | 
|  | 735 | Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the | 
|  | 736 | message format string, and the *args* are the arguments which are merged into | 
|  | 737 | *msg* using the string formatting operator. (Note that this means that you can | 
|  | 738 | use keywords in the format string, together with a single dictionary argument.) | 
|  | 739 |  | 
|  | 740 | There are two keyword arguments in *kwargs* which are inspected: *exc_info* | 
|  | 741 | which, if it does not evaluate as false, causes exception information to be | 
|  | 742 | added to the logging message. If an exception tuple (in the format returned by | 
|  | 743 | :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info` | 
|  | 744 | is called to get the exception information. | 
|  | 745 |  | 
|  | 746 | The other optional keyword argument is *extra* which can be used to pass a | 
|  | 747 | dictionary which is used to populate the __dict__ of the LogRecord created for | 
|  | 748 | the logging event with user-defined attributes. These custom attributes can then | 
|  | 749 | be used as you like. For example, they could be incorporated into logged | 
|  | 750 | messages. For example:: | 
|  | 751 |  | 
|  | 752 | FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s" | 
|  | 753 | logging.basicConfig(format=FORMAT) | 
|  | 754 | d = {'clientip': '192.168.0.1', 'user': 'fbloggs'} | 
|  | 755 | logging.warning("Protocol problem: %s", "connection reset", extra=d) | 
|  | 756 |  | 
| Vinay Sajip | fe08e6f | 2010-09-11 10:25:28 +0000 | [diff] [blame] | 757 | would print something like:: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 758 |  | 
|  | 759 | 2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset | 
|  | 760 |  | 
|  | 761 | The keys in the dictionary passed in *extra* should not clash with the keys used | 
|  | 762 | by the logging system. (See the :class:`Formatter` documentation for more | 
|  | 763 | information on which keys are used by the logging system.) | 
|  | 764 |  | 
|  | 765 | If you choose to use these attributes in logged messages, you need to exercise | 
|  | 766 | some care. In the above example, for instance, the :class:`Formatter` has been | 
|  | 767 | set up with a format string which expects 'clientip' and 'user' in the attribute | 
|  | 768 | dictionary of the LogRecord. If these are missing, the message will not be | 
|  | 769 | logged because a string formatting exception will occur. So in this case, you | 
|  | 770 | always need to pass the *extra* dictionary with these keys. | 
|  | 771 |  | 
|  | 772 | While this might be annoying, this feature is intended for use in specialized | 
|  | 773 | circumstances, such as multi-threaded servers where the same code executes in | 
|  | 774 | many contexts, and interesting conditions which arise are dependent on this | 
|  | 775 | context (such as remote client IP address and authenticated user name, in the | 
|  | 776 | above example). In such circumstances, it is likely that specialized | 
|  | 777 | :class:`Formatter`\ s would be used with particular :class:`Handler`\ s. | 
|  | 778 |  | 
|  | 779 | .. versionchanged:: 2.5 | 
|  | 780 | *extra* was added. | 
|  | 781 |  | 
|  | 782 |  | 
|  | 783 | .. function:: info(msg[, *args[, **kwargs]]) | 
|  | 784 |  | 
|  | 785 | Logs a message with level :const:`INFO` on the root logger. The arguments are | 
|  | 786 | interpreted as for :func:`debug`. | 
|  | 787 |  | 
|  | 788 |  | 
|  | 789 | .. function:: warning(msg[, *args[, **kwargs]]) | 
|  | 790 |  | 
|  | 791 | Logs a message with level :const:`WARNING` on the root logger. The arguments are | 
|  | 792 | interpreted as for :func:`debug`. | 
|  | 793 |  | 
|  | 794 |  | 
|  | 795 | .. function:: error(msg[, *args[, **kwargs]]) | 
|  | 796 |  | 
|  | 797 | Logs a message with level :const:`ERROR` on the root logger. The arguments are | 
|  | 798 | interpreted as for :func:`debug`. | 
|  | 799 |  | 
|  | 800 |  | 
|  | 801 | .. function:: critical(msg[, *args[, **kwargs]]) | 
|  | 802 |  | 
|  | 803 | Logs a message with level :const:`CRITICAL` on the root logger. The arguments | 
|  | 804 | are interpreted as for :func:`debug`. | 
|  | 805 |  | 
|  | 806 |  | 
|  | 807 | .. function:: exception(msg[, *args]) | 
|  | 808 |  | 
|  | 809 | Logs a message with level :const:`ERROR` on the root logger. The arguments are | 
|  | 810 | interpreted as for :func:`debug`. Exception info is added to the logging | 
|  | 811 | message. This function should only be called from an exception handler. | 
|  | 812 |  | 
|  | 813 |  | 
|  | 814 | .. function:: log(level, msg[, *args[, **kwargs]]) | 
|  | 815 |  | 
|  | 816 | Logs a message with level *level* on the root logger. The other arguments are | 
|  | 817 | interpreted as for :func:`debug`. | 
|  | 818 |  | 
| Vinay Sajip | 89e1ae2 | 2010-09-17 10:09:04 +0000 | [diff] [blame] | 819 | PLEASE NOTE: The above module-level functions which delegate to the root | 
|  | 820 | logger should *not* be used in threads, in versions of Python earlier than | 
|  | 821 | 2.7.1 and 3.2, unless at least one handler has been added to the root | 
|  | 822 | logger *before* the threads are started. These convenience functions call | 
|  | 823 | :func:`basicConfig` to ensure that at least one handler is available; in | 
|  | 824 | earlier versions of Python, this can (under rare circumstances) lead to | 
|  | 825 | handlers being added multiple times to the root logger, which can in turn | 
|  | 826 | lead to multiple messages for the same event. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 827 |  | 
|  | 828 | .. function:: disable(lvl) | 
|  | 829 |  | 
|  | 830 | Provides an overriding level *lvl* for all loggers which takes precedence over | 
|  | 831 | 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] | 832 | output down across the whole application, this function can be useful. Its | 
|  | 833 | effect is to disable all logging calls of severity *lvl* and below, so that | 
|  | 834 | if you call it with a value of INFO, then all INFO and DEBUG events would be | 
|  | 835 | discarded, whereas those of severity WARNING and above would be processed | 
|  | 836 | according to the logger's effective level. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 837 |  | 
|  | 838 |  | 
|  | 839 | .. function:: addLevelName(lvl, levelName) | 
|  | 840 |  | 
|  | 841 | Associates level *lvl* with text *levelName* in an internal dictionary, which is | 
|  | 842 | used to map numeric levels to a textual representation, for example when a | 
|  | 843 | :class:`Formatter` formats a message. This function can also be used to define | 
|  | 844 | your own levels. The only constraints are that all levels used must be | 
|  | 845 | registered using this function, levels should be positive integers and they | 
|  | 846 | should increase in increasing order of severity. | 
|  | 847 |  | 
| Vinay Sajip | 89e1ae2 | 2010-09-17 10:09:04 +0000 | [diff] [blame] | 848 | NOTE: If you are thinking of defining your own levels, please see the section | 
|  | 849 | on :ref:`custom-levels`. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 850 |  | 
|  | 851 | .. function:: getLevelName(lvl) | 
|  | 852 |  | 
|  | 853 | Returns the textual representation of logging level *lvl*. If the level is one | 
|  | 854 | of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`, | 
|  | 855 | :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you | 
|  | 856 | have associated levels with names using :func:`addLevelName` then the name you | 
|  | 857 | have associated with *lvl* is returned. If a numeric value corresponding to one | 
|  | 858 | of the defined levels is passed in, the corresponding string representation is | 
|  | 859 | returned. Otherwise, the string "Level %s" % lvl is returned. | 
|  | 860 |  | 
|  | 861 |  | 
|  | 862 | .. function:: makeLogRecord(attrdict) | 
|  | 863 |  | 
|  | 864 | Creates and returns a new :class:`LogRecord` instance whose attributes are | 
|  | 865 | defined by *attrdict*. This function is useful for taking a pickled | 
|  | 866 | :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting | 
|  | 867 | it as a :class:`LogRecord` instance at the receiving end. | 
|  | 868 |  | 
|  | 869 |  | 
|  | 870 | .. function:: basicConfig([**kwargs]) | 
|  | 871 |  | 
|  | 872 | Does basic configuration for the logging system by creating a | 
|  | 873 | :class:`StreamHandler` with a default :class:`Formatter` and adding it to the | 
| Vinay Sajip | 1c77b7f | 2009-10-10 20:32:36 +0000 | [diff] [blame] | 874 | root logger. The functions :func:`debug`, :func:`info`, :func:`warning`, | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 875 | :func:`error` and :func:`critical` will call :func:`basicConfig` automatically | 
|  | 876 | if no handlers are defined for the root logger. | 
|  | 877 |  | 
| Vinay Sajip | 1c77b7f | 2009-10-10 20:32:36 +0000 | [diff] [blame] | 878 | This function does nothing if the root logger already has handlers | 
|  | 879 | configured for it. | 
| Georg Brandl | dfb5bbd | 2008-05-09 06:18:27 +0000 | [diff] [blame] | 880 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 881 | .. versionchanged:: 2.4 | 
|  | 882 | Formerly, :func:`basicConfig` did not take any keyword arguments. | 
|  | 883 |  | 
| Vinay Sajip | 89e1ae2 | 2010-09-17 10:09:04 +0000 | [diff] [blame] | 884 | PLEASE NOTE: This function should be called from the main thread | 
|  | 885 | before other threads are started. In versions of Python prior to | 
|  | 886 | 2.7.1 and 3.2, if this function is called from multiple threads, | 
|  | 887 | it is possible (in rare circumstances) that a handler will be added | 
|  | 888 | to the root logger more than once, leading to unexpected results | 
|  | 889 | such as messages being duplicated in the log. | 
|  | 890 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 891 | The following keyword arguments are supported. | 
|  | 892 |  | 
|  | 893 | +--------------+---------------------------------------------+ | 
|  | 894 | | Format       | Description                                 | | 
|  | 895 | +==============+=============================================+ | 
|  | 896 | | ``filename`` | Specifies that a FileHandler be created,    | | 
|  | 897 | |              | using the specified filename, rather than a | | 
|  | 898 | |              | StreamHandler.                              | | 
|  | 899 | +--------------+---------------------------------------------+ | 
|  | 900 | | ``filemode`` | Specifies the mode to open the file, if     | | 
|  | 901 | |              | filename is specified (if filemode is       | | 
|  | 902 | |              | unspecified, it defaults to 'a').           | | 
|  | 903 | +--------------+---------------------------------------------+ | 
|  | 904 | | ``format``   | Use the specified format string for the     | | 
|  | 905 | |              | handler.                                    | | 
|  | 906 | +--------------+---------------------------------------------+ | 
|  | 907 | | ``datefmt``  | Use the specified date/time format.         | | 
|  | 908 | +--------------+---------------------------------------------+ | 
|  | 909 | | ``level``    | Set the root logger level to the specified  | | 
|  | 910 | |              | level.                                      | | 
|  | 911 | +--------------+---------------------------------------------+ | 
|  | 912 | | ``stream``   | Use the specified stream to initialize the  | | 
|  | 913 | |              | StreamHandler. Note that this argument is   | | 
|  | 914 | |              | incompatible with 'filename' - if both are  | | 
|  | 915 | |              | present, 'stream' is ignored.               | | 
|  | 916 | +--------------+---------------------------------------------+ | 
|  | 917 |  | 
|  | 918 |  | 
|  | 919 | .. function:: shutdown() | 
|  | 920 |  | 
|  | 921 | Informs the logging system to perform an orderly shutdown by flushing and | 
| Vinay Sajip | 91f0ee4 | 2008-03-16 21:35:58 +0000 | [diff] [blame] | 922 | closing all handlers. This should be called at application exit and no | 
|  | 923 | further use of the logging system should be made after this call. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 924 |  | 
|  | 925 |  | 
|  | 926 | .. function:: setLoggerClass(klass) | 
|  | 927 |  | 
|  | 928 | Tells the logging system to use the class *klass* when instantiating a logger. | 
|  | 929 | The class should define :meth:`__init__` such that only a name argument is | 
|  | 930 | required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This | 
|  | 931 | function is typically called before any loggers are instantiated by applications | 
|  | 932 | which need to use custom logger behavior. | 
|  | 933 |  | 
|  | 934 |  | 
|  | 935 | .. seealso:: | 
|  | 936 |  | 
|  | 937 | :pep:`282` - A Logging System | 
|  | 938 | The proposal which described this feature for inclusion in the Python standard | 
|  | 939 | library. | 
|  | 940 |  | 
| Georg Brandl | 2b92f6b | 2007-12-06 01:52:24 +0000 | [diff] [blame] | 941 | `Original Python logging package <http://www.red-dove.com/python_logging.html>`_ | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 942 | This is the original source for the :mod:`logging` package.  The version of the | 
|  | 943 | package available from this site is suitable for use with Python 1.5.2, 2.1.x | 
|  | 944 | and 2.2.x, which do not include the :mod:`logging` package in the standard | 
|  | 945 | library. | 
|  | 946 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 947 | .. _logger: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 948 |  | 
|  | 949 | Logger Objects | 
|  | 950 | -------------- | 
|  | 951 |  | 
|  | 952 | Loggers have the following attributes and methods. Note that Loggers are never | 
|  | 953 | instantiated directly, but always through the module-level function | 
|  | 954 | ``logging.getLogger(name)``. | 
|  | 955 |  | 
|  | 956 |  | 
|  | 957 | .. attribute:: Logger.propagate | 
|  | 958 |  | 
|  | 959 | If this evaluates to false, logging messages are not passed by this logger or by | 
| Vinay Sajip | ccd8bc8 | 2010-04-06 22:32:37 +0000 | [diff] [blame] | 960 | its child loggers to the handlers of higher level (ancestor) loggers. The | 
|  | 961 | constructor sets this attribute to 1. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 962 |  | 
|  | 963 |  | 
|  | 964 | .. method:: Logger.setLevel(lvl) | 
|  | 965 |  | 
|  | 966 | Sets the threshold for this logger to *lvl*. Logging messages which are less | 
|  | 967 | severe than *lvl* will be ignored. When a logger is created, the level is set to | 
|  | 968 | :const:`NOTSET` (which causes all messages to be processed when the logger is | 
|  | 969 | the root logger, or delegation to the parent when the logger is a non-root | 
|  | 970 | logger). Note that the root logger is created with level :const:`WARNING`. | 
|  | 971 |  | 
|  | 972 | The term "delegation to the parent" means that if a logger has a level of | 
|  | 973 | NOTSET, its chain of ancestor loggers is traversed until either an ancestor with | 
|  | 974 | a level other than NOTSET is found, or the root is reached. | 
|  | 975 |  | 
|  | 976 | If an ancestor is found with a level other than NOTSET, then that ancestor's | 
|  | 977 | level is treated as the effective level of the logger where the ancestor search | 
|  | 978 | began, and is used to determine how a logging event is handled. | 
|  | 979 |  | 
|  | 980 | If the root is reached, and it has a level of NOTSET, then all messages will be | 
|  | 981 | processed. Otherwise, the root's level will be used as the effective level. | 
|  | 982 |  | 
|  | 983 |  | 
|  | 984 | .. method:: Logger.isEnabledFor(lvl) | 
|  | 985 |  | 
|  | 986 | Indicates if a message of severity *lvl* would be processed by this logger. | 
|  | 987 | This method checks first the module-level level set by | 
|  | 988 | ``logging.disable(lvl)`` and then the logger's effective level as determined | 
|  | 989 | by :meth:`getEffectiveLevel`. | 
|  | 990 |  | 
|  | 991 |  | 
|  | 992 | .. method:: Logger.getEffectiveLevel() | 
|  | 993 |  | 
|  | 994 | Indicates the effective level for this logger. If a value other than | 
|  | 995 | :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise, | 
|  | 996 | the hierarchy is traversed towards the root until a value other than | 
|  | 997 | :const:`NOTSET` is found, and that value is returned. | 
|  | 998 |  | 
|  | 999 |  | 
| Vinay Sajip | 804899b | 2010-03-22 15:29:01 +0000 | [diff] [blame] | 1000 | .. method:: Logger.getChild(suffix) | 
|  | 1001 |  | 
|  | 1002 | Returns a logger which is a descendant to this logger, as determined by the suffix. | 
|  | 1003 | Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same | 
|  | 1004 | logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a | 
|  | 1005 | convenience method, useful when the parent logger is named using e.g. ``__name__`` | 
|  | 1006 | rather than a literal string. | 
|  | 1007 |  | 
|  | 1008 | .. versionadded:: 2.7 | 
|  | 1009 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1010 | .. method:: Logger.debug(msg[, *args[, **kwargs]]) | 
|  | 1011 |  | 
|  | 1012 | Logs a message with level :const:`DEBUG` on this logger. The *msg* is the | 
|  | 1013 | message format string, and the *args* are the arguments which are merged into | 
|  | 1014 | *msg* using the string formatting operator. (Note that this means that you can | 
|  | 1015 | use keywords in the format string, together with a single dictionary argument.) | 
|  | 1016 |  | 
|  | 1017 | There are two keyword arguments in *kwargs* which are inspected: *exc_info* | 
|  | 1018 | which, if it does not evaluate as false, causes exception information to be | 
|  | 1019 | added to the logging message. If an exception tuple (in the format returned by | 
|  | 1020 | :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info` | 
|  | 1021 | is called to get the exception information. | 
|  | 1022 |  | 
|  | 1023 | The other optional keyword argument is *extra* which can be used to pass a | 
|  | 1024 | dictionary which is used to populate the __dict__ of the LogRecord created for | 
|  | 1025 | the logging event with user-defined attributes. These custom attributes can then | 
|  | 1026 | be used as you like. For example, they could be incorporated into logged | 
|  | 1027 | messages. For example:: | 
|  | 1028 |  | 
|  | 1029 | FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s" | 
|  | 1030 | logging.basicConfig(format=FORMAT) | 
| Neal Norwitz | 5300428 | 2007-10-23 05:44:27 +0000 | [diff] [blame] | 1031 | d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' } | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1032 | logger = logging.getLogger("tcpserver") | 
|  | 1033 | logger.warning("Protocol problem: %s", "connection reset", extra=d) | 
|  | 1034 |  | 
|  | 1035 | would print something like  :: | 
|  | 1036 |  | 
|  | 1037 | 2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset | 
|  | 1038 |  | 
|  | 1039 | The keys in the dictionary passed in *extra* should not clash with the keys used | 
|  | 1040 | by the logging system. (See the :class:`Formatter` documentation for more | 
|  | 1041 | information on which keys are used by the logging system.) | 
|  | 1042 |  | 
|  | 1043 | If you choose to use these attributes in logged messages, you need to exercise | 
|  | 1044 | some care. In the above example, for instance, the :class:`Formatter` has been | 
|  | 1045 | set up with a format string which expects 'clientip' and 'user' in the attribute | 
|  | 1046 | dictionary of the LogRecord. If these are missing, the message will not be | 
|  | 1047 | logged because a string formatting exception will occur. So in this case, you | 
|  | 1048 | always need to pass the *extra* dictionary with these keys. | 
|  | 1049 |  | 
|  | 1050 | While this might be annoying, this feature is intended for use in specialized | 
|  | 1051 | circumstances, such as multi-threaded servers where the same code executes in | 
|  | 1052 | many contexts, and interesting conditions which arise are dependent on this | 
|  | 1053 | context (such as remote client IP address and authenticated user name, in the | 
|  | 1054 | above example). In such circumstances, it is likely that specialized | 
|  | 1055 | :class:`Formatter`\ s would be used with particular :class:`Handler`\ s. | 
|  | 1056 |  | 
|  | 1057 | .. versionchanged:: 2.5 | 
|  | 1058 | *extra* was added. | 
|  | 1059 |  | 
|  | 1060 |  | 
|  | 1061 | .. method:: Logger.info(msg[, *args[, **kwargs]]) | 
|  | 1062 |  | 
|  | 1063 | Logs a message with level :const:`INFO` on this logger. The arguments are | 
|  | 1064 | interpreted as for :meth:`debug`. | 
|  | 1065 |  | 
|  | 1066 |  | 
|  | 1067 | .. method:: Logger.warning(msg[, *args[, **kwargs]]) | 
|  | 1068 |  | 
|  | 1069 | Logs a message with level :const:`WARNING` on this logger. The arguments are | 
|  | 1070 | interpreted as for :meth:`debug`. | 
|  | 1071 |  | 
|  | 1072 |  | 
|  | 1073 | .. method:: Logger.error(msg[, *args[, **kwargs]]) | 
|  | 1074 |  | 
|  | 1075 | Logs a message with level :const:`ERROR` on this logger. The arguments are | 
|  | 1076 | interpreted as for :meth:`debug`. | 
|  | 1077 |  | 
|  | 1078 |  | 
|  | 1079 | .. method:: Logger.critical(msg[, *args[, **kwargs]]) | 
|  | 1080 |  | 
|  | 1081 | Logs a message with level :const:`CRITICAL` on this logger. The arguments are | 
|  | 1082 | interpreted as for :meth:`debug`. | 
|  | 1083 |  | 
|  | 1084 |  | 
|  | 1085 | .. method:: Logger.log(lvl, msg[, *args[, **kwargs]]) | 
|  | 1086 |  | 
|  | 1087 | Logs a message with integer level *lvl* on this logger. The other arguments are | 
|  | 1088 | interpreted as for :meth:`debug`. | 
|  | 1089 |  | 
|  | 1090 |  | 
|  | 1091 | .. method:: Logger.exception(msg[, *args]) | 
|  | 1092 |  | 
|  | 1093 | Logs a message with level :const:`ERROR` on this logger. The arguments are | 
|  | 1094 | interpreted as for :meth:`debug`. Exception info is added to the logging | 
|  | 1095 | message. This method should only be called from an exception handler. | 
|  | 1096 |  | 
|  | 1097 |  | 
|  | 1098 | .. method:: Logger.addFilter(filt) | 
|  | 1099 |  | 
|  | 1100 | Adds the specified filter *filt* to this logger. | 
|  | 1101 |  | 
|  | 1102 |  | 
|  | 1103 | .. method:: Logger.removeFilter(filt) | 
|  | 1104 |  | 
|  | 1105 | Removes the specified filter *filt* from this logger. | 
|  | 1106 |  | 
|  | 1107 |  | 
|  | 1108 | .. method:: Logger.filter(record) | 
|  | 1109 |  | 
|  | 1110 | Applies this logger's filters to the record and returns a true value if the | 
|  | 1111 | record is to be processed. | 
|  | 1112 |  | 
|  | 1113 |  | 
|  | 1114 | .. method:: Logger.addHandler(hdlr) | 
|  | 1115 |  | 
|  | 1116 | Adds the specified handler *hdlr* to this logger. | 
|  | 1117 |  | 
|  | 1118 |  | 
|  | 1119 | .. method:: Logger.removeHandler(hdlr) | 
|  | 1120 |  | 
|  | 1121 | Removes the specified handler *hdlr* from this logger. | 
|  | 1122 |  | 
|  | 1123 |  | 
|  | 1124 | .. method:: Logger.findCaller() | 
|  | 1125 |  | 
|  | 1126 | Finds the caller's source filename and line number. Returns the filename, line | 
|  | 1127 | number and function name as a 3-element tuple. | 
|  | 1128 |  | 
| Matthias Klose | f0e2918 | 2007-08-16 12:03:44 +0000 | [diff] [blame] | 1129 | .. versionchanged:: 2.4 | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1130 | The function name was added. In earlier versions, the filename and line number | 
|  | 1131 | were returned as a 2-element tuple.. | 
|  | 1132 |  | 
|  | 1133 |  | 
|  | 1134 | .. method:: Logger.handle(record) | 
|  | 1135 |  | 
|  | 1136 | Handles a record by passing it to all handlers associated with this logger and | 
|  | 1137 | its ancestors (until a false value of *propagate* is found). This method is used | 
|  | 1138 | for unpickled records received from a socket, as well as those created locally. | 
| Georg Brandl | 9fa61bb | 2009-07-26 14:19:57 +0000 | [diff] [blame] | 1139 | Logger-level filtering is applied using :meth:`~Logger.filter`. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1140 |  | 
|  | 1141 |  | 
|  | 1142 | .. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info [, func, extra]) | 
|  | 1143 |  | 
|  | 1144 | This is a factory method which can be overridden in subclasses to create | 
|  | 1145 | specialized :class:`LogRecord` instances. | 
|  | 1146 |  | 
|  | 1147 | .. versionchanged:: 2.5 | 
|  | 1148 | *func* and *extra* were added. | 
|  | 1149 |  | 
|  | 1150 |  | 
|  | 1151 | .. _minimal-example: | 
|  | 1152 |  | 
|  | 1153 | Basic example | 
|  | 1154 | ------------- | 
|  | 1155 |  | 
|  | 1156 | .. versionchanged:: 2.4 | 
|  | 1157 | formerly :func:`basicConfig` did not take any keyword arguments. | 
|  | 1158 |  | 
|  | 1159 | The :mod:`logging` package provides a lot of flexibility, and its configuration | 
|  | 1160 | can appear daunting.  This section demonstrates that simple use of the logging | 
|  | 1161 | package is possible. | 
|  | 1162 |  | 
|  | 1163 | The simplest example shows logging to the console:: | 
|  | 1164 |  | 
|  | 1165 | import logging | 
|  | 1166 |  | 
|  | 1167 | logging.debug('A debug message') | 
|  | 1168 | logging.info('Some information') | 
|  | 1169 | logging.warning('A shot across the bows') | 
|  | 1170 |  | 
|  | 1171 | If you run the above script, you'll see this:: | 
|  | 1172 |  | 
|  | 1173 | WARNING:root:A shot across the bows | 
|  | 1174 |  | 
|  | 1175 | Because no particular logger was specified, the system used the root logger. The | 
|  | 1176 | debug and info messages didn't appear because by default, the root logger is | 
|  | 1177 | configured to only handle messages with a severity of WARNING or above. The | 
|  | 1178 | message format is also a configuration default, as is the output destination of | 
|  | 1179 | the messages - ``sys.stderr``. The severity level, the message format and | 
|  | 1180 | destination can be easily changed, as shown in the example below:: | 
|  | 1181 |  | 
|  | 1182 | import logging | 
|  | 1183 |  | 
|  | 1184 | logging.basicConfig(level=logging.DEBUG, | 
|  | 1185 | format='%(asctime)s %(levelname)s %(message)s', | 
| Vinay Sajip | 998cc24 | 2010-06-04 13:41:02 +0000 | [diff] [blame] | 1186 | filename='myapp.log', | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1187 | filemode='w') | 
|  | 1188 | logging.debug('A debug message') | 
|  | 1189 | logging.info('Some information') | 
|  | 1190 | logging.warning('A shot across the bows') | 
|  | 1191 |  | 
|  | 1192 | The :meth:`basicConfig` method is used to change the configuration defaults, | 
| Vinay Sajip | 998cc24 | 2010-06-04 13:41:02 +0000 | [diff] [blame] | 1193 | which results in output (written to ``myapp.log``) which should look | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1194 | something like the following:: | 
|  | 1195 |  | 
|  | 1196 | 2004-07-02 13:00:08,743 DEBUG A debug message | 
|  | 1197 | 2004-07-02 13:00:08,743 INFO Some information | 
|  | 1198 | 2004-07-02 13:00:08,743 WARNING A shot across the bows | 
|  | 1199 |  | 
|  | 1200 | This time, all messages with a severity of DEBUG or above were handled, and the | 
|  | 1201 | format of the messages was also changed, and output went to the specified file | 
|  | 1202 | rather than the console. | 
|  | 1203 |  | 
|  | 1204 | Formatting uses standard Python string formatting - see section | 
|  | 1205 | :ref:`string-formatting`. The format string takes the following common | 
|  | 1206 | specifiers. For a complete list of specifiers, consult the :class:`Formatter` | 
|  | 1207 | documentation. | 
|  | 1208 |  | 
|  | 1209 | +-------------------+-----------------------------------------------+ | 
|  | 1210 | | Format            | Description                                   | | 
|  | 1211 | +===================+===============================================+ | 
|  | 1212 | | ``%(name)s``      | Name of the logger (logging channel).         | | 
|  | 1213 | +-------------------+-----------------------------------------------+ | 
|  | 1214 | | ``%(levelname)s`` | Text logging level for the message            | | 
|  | 1215 | |                   | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``,      | | 
|  | 1216 | |                   | ``'ERROR'``, ``'CRITICAL'``).                 | | 
|  | 1217 | +-------------------+-----------------------------------------------+ | 
|  | 1218 | | ``%(asctime)s``   | Human-readable time when the                  | | 
|  | 1219 | |                   | :class:`LogRecord` was created.  By default   | | 
|  | 1220 | |                   | this is of the form "2003-07-08 16:49:45,896" | | 
|  | 1221 | |                   | (the numbers after the comma are millisecond  | | 
|  | 1222 | |                   | portion of the time).                         | | 
|  | 1223 | +-------------------+-----------------------------------------------+ | 
|  | 1224 | | ``%(message)s``   | The logged message.                           | | 
|  | 1225 | +-------------------+-----------------------------------------------+ | 
|  | 1226 |  | 
|  | 1227 | To change the date/time format, you can pass an additional keyword parameter, | 
|  | 1228 | *datefmt*, as in the following:: | 
|  | 1229 |  | 
|  | 1230 | import logging | 
|  | 1231 |  | 
|  | 1232 | logging.basicConfig(level=logging.DEBUG, | 
|  | 1233 | format='%(asctime)s %(levelname)-8s %(message)s', | 
|  | 1234 | datefmt='%a, %d %b %Y %H:%M:%S', | 
|  | 1235 | filename='/temp/myapp.log', | 
|  | 1236 | filemode='w') | 
|  | 1237 | logging.debug('A debug message') | 
|  | 1238 | logging.info('Some information') | 
|  | 1239 | logging.warning('A shot across the bows') | 
|  | 1240 |  | 
|  | 1241 | which would result in output like :: | 
|  | 1242 |  | 
|  | 1243 | Fri, 02 Jul 2004 13:06:18 DEBUG    A debug message | 
|  | 1244 | Fri, 02 Jul 2004 13:06:18 INFO     Some information | 
|  | 1245 | Fri, 02 Jul 2004 13:06:18 WARNING  A shot across the bows | 
|  | 1246 |  | 
|  | 1247 | The date format string follows the requirements of :func:`strftime` - see the | 
|  | 1248 | documentation for the :mod:`time` module. | 
|  | 1249 |  | 
|  | 1250 | If, instead of sending logging output to the console or a file, you'd rather use | 
|  | 1251 | a file-like object which you have created separately, you can pass it to | 
|  | 1252 | :func:`basicConfig` using the *stream* keyword argument. Note that if both | 
|  | 1253 | *stream* and *filename* keyword arguments are passed, the *stream* argument is | 
|  | 1254 | ignored. | 
|  | 1255 |  | 
|  | 1256 | Of course, you can put variable information in your output. To do this, simply | 
|  | 1257 | have the message be a format string and pass in additional arguments containing | 
|  | 1258 | the variable information, as in the following example:: | 
|  | 1259 |  | 
|  | 1260 | import logging | 
|  | 1261 |  | 
|  | 1262 | logging.basicConfig(level=logging.DEBUG, | 
|  | 1263 | format='%(asctime)s %(levelname)-8s %(message)s', | 
|  | 1264 | datefmt='%a, %d %b %Y %H:%M:%S', | 
|  | 1265 | filename='/temp/myapp.log', | 
|  | 1266 | filemode='w') | 
|  | 1267 | logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs') | 
|  | 1268 |  | 
|  | 1269 | which would result in :: | 
|  | 1270 |  | 
|  | 1271 | Wed, 21 Jul 2004 15:35:16 ERROR    Pack my box with 5 dozen liquor jugs | 
|  | 1272 |  | 
|  | 1273 |  | 
|  | 1274 | .. _multiple-destinations: | 
|  | 1275 |  | 
|  | 1276 | Logging to multiple destinations | 
|  | 1277 | -------------------------------- | 
|  | 1278 |  | 
|  | 1279 | Let's say you want to log to console and file with different message formats and | 
|  | 1280 | in differing circumstances. Say you want to log messages with levels of DEBUG | 
|  | 1281 | and higher to file, and those messages at level INFO and higher to the console. | 
|  | 1282 | Let's also assume that the file should contain timestamps, but the console | 
|  | 1283 | messages should not. Here's how you can achieve this:: | 
|  | 1284 |  | 
|  | 1285 | import logging | 
|  | 1286 |  | 
|  | 1287 | # set up logging to file - see previous section for more details | 
|  | 1288 | logging.basicConfig(level=logging.DEBUG, | 
|  | 1289 | format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', | 
|  | 1290 | datefmt='%m-%d %H:%M', | 
|  | 1291 | filename='/temp/myapp.log', | 
|  | 1292 | filemode='w') | 
|  | 1293 | # define a Handler which writes INFO messages or higher to the sys.stderr | 
|  | 1294 | console = logging.StreamHandler() | 
|  | 1295 | console.setLevel(logging.INFO) | 
|  | 1296 | # set a format which is simpler for console use | 
|  | 1297 | formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') | 
|  | 1298 | # tell the handler to use this format | 
|  | 1299 | console.setFormatter(formatter) | 
|  | 1300 | # add the handler to the root logger | 
|  | 1301 | logging.getLogger('').addHandler(console) | 
|  | 1302 |  | 
|  | 1303 | # Now, we can log to the root logger, or any other logger. First the root... | 
|  | 1304 | logging.info('Jackdaws love my big sphinx of quartz.') | 
|  | 1305 |  | 
|  | 1306 | # Now, define a couple of other loggers which might represent areas in your | 
|  | 1307 | # application: | 
|  | 1308 |  | 
|  | 1309 | logger1 = logging.getLogger('myapp.area1') | 
|  | 1310 | logger2 = logging.getLogger('myapp.area2') | 
|  | 1311 |  | 
|  | 1312 | logger1.debug('Quick zephyrs blow, vexing daft Jim.') | 
|  | 1313 | logger1.info('How quickly daft jumping zebras vex.') | 
|  | 1314 | logger2.warning('Jail zesty vixen who grabbed pay from quack.') | 
|  | 1315 | logger2.error('The five boxing wizards jump quickly.') | 
|  | 1316 |  | 
|  | 1317 | When you run this, on the console you will see :: | 
|  | 1318 |  | 
|  | 1319 | root        : INFO     Jackdaws love my big sphinx of quartz. | 
|  | 1320 | myapp.area1 : INFO     How quickly daft jumping zebras vex. | 
|  | 1321 | myapp.area2 : WARNING  Jail zesty vixen who grabbed pay from quack. | 
|  | 1322 | myapp.area2 : ERROR    The five boxing wizards jump quickly. | 
|  | 1323 |  | 
|  | 1324 | and in the file you will see something like :: | 
|  | 1325 |  | 
|  | 1326 | 10-22 22:19 root         INFO     Jackdaws love my big sphinx of quartz. | 
|  | 1327 | 10-22 22:19 myapp.area1  DEBUG    Quick zephyrs blow, vexing daft Jim. | 
|  | 1328 | 10-22 22:19 myapp.area1  INFO     How quickly daft jumping zebras vex. | 
|  | 1329 | 10-22 22:19 myapp.area2  WARNING  Jail zesty vixen who grabbed pay from quack. | 
|  | 1330 | 10-22 22:19 myapp.area2  ERROR    The five boxing wizards jump quickly. | 
|  | 1331 |  | 
|  | 1332 | As you can see, the DEBUG message only shows up in the file. The other messages | 
|  | 1333 | are sent to both destinations. | 
|  | 1334 |  | 
|  | 1335 | This example uses console and file handlers, but you can use any number and | 
|  | 1336 | combination of handlers you choose. | 
|  | 1337 |  | 
| Vinay Sajip | 333c6e7 | 2009-08-20 22:04:32 +0000 | [diff] [blame] | 1338 | .. _logging-exceptions: | 
|  | 1339 |  | 
|  | 1340 | Exceptions raised during logging | 
|  | 1341 | -------------------------------- | 
|  | 1342 |  | 
|  | 1343 | The logging package is designed to swallow exceptions which occur while logging | 
|  | 1344 | in production. This is so that errors which occur while handling logging events | 
|  | 1345 | - such as logging misconfiguration, network or other similar errors - do not | 
|  | 1346 | cause the application using logging to terminate prematurely. | 
|  | 1347 |  | 
|  | 1348 | :class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never | 
|  | 1349 | swallowed. Other exceptions which occur during the :meth:`emit` method of a | 
|  | 1350 | :class:`Handler` subclass are passed to its :meth:`handleError` method. | 
|  | 1351 |  | 
|  | 1352 | The default implementation of :meth:`handleError` in :class:`Handler` checks | 
| Georg Brandl | f6d36745 | 2010-03-12 10:02:03 +0000 | [diff] [blame] | 1353 | to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a | 
|  | 1354 | traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed. | 
| Vinay Sajip | 333c6e7 | 2009-08-20 22:04:32 +0000 | [diff] [blame] | 1355 |  | 
| Georg Brandl | f6d36745 | 2010-03-12 10:02:03 +0000 | [diff] [blame] | 1356 | **Note:** The default value of :data:`raiseExceptions` is ``True``. This is because | 
| Vinay Sajip | 333c6e7 | 2009-08-20 22:04:32 +0000 | [diff] [blame] | 1357 | during development, you typically want to be notified of any exceptions that | 
| Georg Brandl | f6d36745 | 2010-03-12 10:02:03 +0000 | [diff] [blame] | 1358 | occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production | 
| Vinay Sajip | 333c6e7 | 2009-08-20 22:04:32 +0000 | [diff] [blame] | 1359 | usage. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1360 |  | 
| Vinay Sajip | aa0665b | 2008-01-07 19:40:10 +0000 | [diff] [blame] | 1361 | .. _context-info: | 
|  | 1362 |  | 
|  | 1363 | Adding contextual information to your logging output | 
|  | 1364 | ---------------------------------------------------- | 
|  | 1365 |  | 
|  | 1366 | Sometimes you want logging output to contain contextual information in | 
|  | 1367 | addition to the parameters passed to the logging call. For example, in a | 
|  | 1368 | networked application, it may be desirable to log client-specific information | 
|  | 1369 | in the log (e.g. remote client's username, or IP address). Although you could | 
|  | 1370 | use the *extra* parameter to achieve this, it's not always convenient to pass | 
|  | 1371 | the information in this way. While it might be tempting to create | 
|  | 1372 | :class:`Logger` instances on a per-connection basis, this is not a good idea | 
|  | 1373 | because these instances are not garbage collected. While this is not a problem | 
|  | 1374 | in practice, when the number of :class:`Logger` instances is dependent on the | 
|  | 1375 | level of granularity you want to use in logging an application, it could | 
|  | 1376 | be hard to manage if the number of :class:`Logger` instances becomes | 
|  | 1377 | effectively unbounded. | 
|  | 1378 |  | 
| Vinay Sajip | 957a47c | 2010-09-06 22:18:20 +0000 | [diff] [blame] | 1379 |  | 
|  | 1380 | Using LoggerAdapters to impart contextual information | 
|  | 1381 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | 
|  | 1382 |  | 
| Vinay Sajip | c740335 | 2008-01-18 15:54:14 +0000 | [diff] [blame] | 1383 | An easy way in which you can pass contextual information to be output along | 
|  | 1384 | with logging event information is to use the :class:`LoggerAdapter` class. | 
|  | 1385 | This class is designed to look like a :class:`Logger`, so that you can call | 
|  | 1386 | :meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`, | 
|  | 1387 | :meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the | 
|  | 1388 | same signatures as their counterparts in :class:`Logger`, so you can use the | 
|  | 1389 | two types of instances interchangeably. | 
| Vinay Sajip | aa0665b | 2008-01-07 19:40:10 +0000 | [diff] [blame] | 1390 |  | 
| Vinay Sajip | c740335 | 2008-01-18 15:54:14 +0000 | [diff] [blame] | 1391 | When you create an instance of :class:`LoggerAdapter`, you pass it a | 
|  | 1392 | :class:`Logger` instance and a dict-like object which contains your contextual | 
|  | 1393 | information. When you call one of the logging methods on an instance of | 
|  | 1394 | :class:`LoggerAdapter`, it delegates the call to the underlying instance of | 
|  | 1395 | :class:`Logger` passed to its constructor, and arranges to pass the contextual | 
|  | 1396 | information in the delegated call. Here's a snippet from the code of | 
|  | 1397 | :class:`LoggerAdapter`:: | 
| Vinay Sajip | aa0665b | 2008-01-07 19:40:10 +0000 | [diff] [blame] | 1398 |  | 
| Vinay Sajip | c740335 | 2008-01-18 15:54:14 +0000 | [diff] [blame] | 1399 | def debug(self, msg, *args, **kwargs): | 
|  | 1400 | """ | 
|  | 1401 | Delegate a debug call to the underlying logger, after adding | 
|  | 1402 | contextual information from this adapter instance. | 
|  | 1403 | """ | 
|  | 1404 | msg, kwargs = self.process(msg, kwargs) | 
|  | 1405 | self.logger.debug(msg, *args, **kwargs) | 
| Vinay Sajip | aa0665b | 2008-01-07 19:40:10 +0000 | [diff] [blame] | 1406 |  | 
| Vinay Sajip | c740335 | 2008-01-18 15:54:14 +0000 | [diff] [blame] | 1407 | The :meth:`process` method of :class:`LoggerAdapter` is where the contextual | 
|  | 1408 | information is added to the logging output. It's passed the message and | 
|  | 1409 | keyword arguments of the logging call, and it passes back (potentially) | 
|  | 1410 | modified versions of these to use in the call to the underlying logger. The | 
|  | 1411 | default implementation of this method leaves the message alone, but inserts | 
|  | 1412 | an "extra" key in the keyword argument whose value is the dict-like object | 
|  | 1413 | passed to the constructor. Of course, if you had passed an "extra" keyword | 
|  | 1414 | argument in the call to the adapter, it will be silently overwritten. | 
| Vinay Sajip | aa0665b | 2008-01-07 19:40:10 +0000 | [diff] [blame] | 1415 |  | 
| Vinay Sajip | c740335 | 2008-01-18 15:54:14 +0000 | [diff] [blame] | 1416 | The advantage of using "extra" is that the values in the dict-like object are | 
|  | 1417 | merged into the :class:`LogRecord` instance's __dict__, allowing you to use | 
|  | 1418 | customized strings with your :class:`Formatter` instances which know about | 
|  | 1419 | the keys of the dict-like object. If you need a different method, e.g. if you | 
|  | 1420 | want to prepend or append the contextual information to the message string, | 
|  | 1421 | you just need to subclass :class:`LoggerAdapter` and override :meth:`process` | 
|  | 1422 | to do what you need. Here's an example script which uses this class, which | 
|  | 1423 | also illustrates what dict-like behaviour is needed from an arbitrary | 
|  | 1424 | "dict-like" object for use in the constructor:: | 
|  | 1425 |  | 
| Georg Brandl | f8e6afb | 2008-01-19 10:11:27 +0000 | [diff] [blame] | 1426 | import logging | 
| Vinay Sajip | 733024a | 2008-01-21 17:39:22 +0000 | [diff] [blame] | 1427 |  | 
| Georg Brandl | f8e6afb | 2008-01-19 10:11:27 +0000 | [diff] [blame] | 1428 | class ConnInfo: | 
|  | 1429 | """ | 
|  | 1430 | An example class which shows how an arbitrary class can be used as | 
|  | 1431 | the 'extra' context information repository passed to a LoggerAdapter. | 
|  | 1432 | """ | 
| Vinay Sajip | 733024a | 2008-01-21 17:39:22 +0000 | [diff] [blame] | 1433 |  | 
| Georg Brandl | f8e6afb | 2008-01-19 10:11:27 +0000 | [diff] [blame] | 1434 | def __getitem__(self, name): | 
|  | 1435 | """ | 
|  | 1436 | To allow this instance to look like a dict. | 
|  | 1437 | """ | 
|  | 1438 | from random import choice | 
|  | 1439 | if name == "ip": | 
|  | 1440 | result = choice(["127.0.0.1", "192.168.0.1"]) | 
|  | 1441 | elif name == "user": | 
|  | 1442 | result = choice(["jim", "fred", "sheila"]) | 
|  | 1443 | else: | 
|  | 1444 | result = self.__dict__.get(name, "?") | 
|  | 1445 | return result | 
| Vinay Sajip | 733024a | 2008-01-21 17:39:22 +0000 | [diff] [blame] | 1446 |  | 
| Georg Brandl | f8e6afb | 2008-01-19 10:11:27 +0000 | [diff] [blame] | 1447 | def __iter__(self): | 
|  | 1448 | """ | 
|  | 1449 | To allow iteration over keys, which will be merged into | 
|  | 1450 | the LogRecord dict before formatting and output. | 
|  | 1451 | """ | 
|  | 1452 | keys = ["ip", "user"] | 
|  | 1453 | keys.extend(self.__dict__.keys()) | 
|  | 1454 | return keys.__iter__() | 
| Vinay Sajip | 733024a | 2008-01-21 17:39:22 +0000 | [diff] [blame] | 1455 |  | 
| Georg Brandl | f8e6afb | 2008-01-19 10:11:27 +0000 | [diff] [blame] | 1456 | if __name__ == "__main__": | 
|  | 1457 | from random import choice | 
|  | 1458 | levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL) | 
|  | 1459 | a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"), | 
|  | 1460 | { "ip" : "123.231.231.123", "user" : "sheila" }) | 
|  | 1461 | logging.basicConfig(level=logging.DEBUG, | 
|  | 1462 | format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s") | 
|  | 1463 | a1.debug("A debug message") | 
|  | 1464 | a1.info("An info message with %s", "some parameters") | 
|  | 1465 | a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo()) | 
|  | 1466 | for x in range(10): | 
|  | 1467 | lvl = choice(levels) | 
|  | 1468 | lvlname = logging.getLevelName(lvl) | 
|  | 1469 | a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters") | 
| Vinay Sajip | c740335 | 2008-01-18 15:54:14 +0000 | [diff] [blame] | 1470 |  | 
|  | 1471 | When this script is run, the output should look something like this:: | 
|  | 1472 |  | 
| Georg Brandl | f8e6afb | 2008-01-19 10:11:27 +0000 | [diff] [blame] | 1473 | 2008-01-18 14:49:54,023 a.b.c DEBUG    IP: 123.231.231.123 User: sheila   A debug message | 
|  | 1474 | 2008-01-18 14:49:54,023 a.b.c INFO     IP: 123.231.231.123 User: sheila   An info message with some parameters | 
|  | 1475 | 2008-01-18 14:49:54,023 d.e.f CRITICAL IP: 192.168.0.1     User: jim      A message at CRITICAL level with 2 parameters | 
|  | 1476 | 2008-01-18 14:49:54,033 d.e.f INFO     IP: 192.168.0.1     User: jim      A message at INFO level with 2 parameters | 
|  | 1477 | 2008-01-18 14:49:54,033 d.e.f WARNING  IP: 192.168.0.1     User: sheila   A message at WARNING level with 2 parameters | 
|  | 1478 | 2008-01-18 14:49:54,033 d.e.f ERROR    IP: 127.0.0.1       User: fred     A message at ERROR level with 2 parameters | 
|  | 1479 | 2008-01-18 14:49:54,033 d.e.f ERROR    IP: 127.0.0.1       User: sheila   A message at ERROR level with 2 parameters | 
|  | 1480 | 2008-01-18 14:49:54,033 d.e.f WARNING  IP: 192.168.0.1     User: sheila   A message at WARNING level with 2 parameters | 
|  | 1481 | 2008-01-18 14:49:54,033 d.e.f WARNING  IP: 192.168.0.1     User: jim      A message at WARNING level with 2 parameters | 
|  | 1482 | 2008-01-18 14:49:54,033 d.e.f INFO     IP: 192.168.0.1     User: fred     A message at INFO level with 2 parameters | 
|  | 1483 | 2008-01-18 14:49:54,033 d.e.f WARNING  IP: 192.168.0.1     User: sheila   A message at WARNING level with 2 parameters | 
|  | 1484 | 2008-01-18 14:49:54,033 d.e.f WARNING  IP: 127.0.0.1       User: jim      A message at WARNING level with 2 parameters | 
| Vinay Sajip | c740335 | 2008-01-18 15:54:14 +0000 | [diff] [blame] | 1485 |  | 
|  | 1486 | .. versionadded:: 2.6 | 
|  | 1487 |  | 
|  | 1488 | The :class:`LoggerAdapter` class was not present in previous versions. | 
|  | 1489 |  | 
| Vinay Sajip | fb7b505 | 2010-09-17 12:45:26 +0000 | [diff] [blame] | 1490 | .. _filters-contextual: | 
|  | 1491 |  | 
| Vinay Sajip | 957a47c | 2010-09-06 22:18:20 +0000 | [diff] [blame] | 1492 | Using Filters to impart contextual information | 
|  | 1493 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | 
|  | 1494 |  | 
|  | 1495 | You can also add contextual information to log output using a user-defined | 
|  | 1496 | :class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords`` | 
|  | 1497 | passed to them, including adding additional attributes which can then be output | 
|  | 1498 | using a suitable format string, or if needed a custom :class:`Formatter`. | 
|  | 1499 |  | 
|  | 1500 | For example in a web application, the request being processed (or at least, | 
|  | 1501 | the interesting parts of it) can be stored in a threadlocal | 
|  | 1502 | (:class:`threading.local`) variable, and then accessed from a ``Filter`` to | 
|  | 1503 | add, say, information from the request - say, the remote IP address and remote | 
|  | 1504 | user's username - to the ``LogRecord``, using the attribute names 'ip' and | 
|  | 1505 | 'user' as in the ``LoggerAdapter`` example above. In that case, the same format | 
|  | 1506 | string can be used to get similar output to that shown above. Here's an example | 
|  | 1507 | script:: | 
|  | 1508 |  | 
|  | 1509 | import logging | 
|  | 1510 | from random import choice | 
|  | 1511 |  | 
|  | 1512 | class ContextFilter(logging.Filter): | 
|  | 1513 | """ | 
|  | 1514 | This is a filter which injects contextual information into the log. | 
|  | 1515 |  | 
|  | 1516 | Rather than use actual contextual information, we just use random | 
|  | 1517 | data in this demo. | 
|  | 1518 | """ | 
|  | 1519 |  | 
|  | 1520 | USERS = ['jim', 'fred', 'sheila'] | 
|  | 1521 | IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1'] | 
|  | 1522 |  | 
|  | 1523 | def filter(self, record): | 
|  | 1524 |  | 
|  | 1525 | record.ip = choice(ContextFilter.IPS) | 
|  | 1526 | record.user = choice(ContextFilter.USERS) | 
|  | 1527 | return True | 
|  | 1528 |  | 
|  | 1529 | if __name__ == "__main__": | 
|  | 1530 | levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL) | 
|  | 1531 | a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"), | 
|  | 1532 | { "ip" : "123.231.231.123", "user" : "sheila" }) | 
|  | 1533 | logging.basicConfig(level=logging.DEBUG, | 
|  | 1534 | format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s") | 
|  | 1535 | a1 = logging.getLogger("a.b.c") | 
|  | 1536 | a2 = logging.getLogger("d.e.f") | 
|  | 1537 |  | 
|  | 1538 | f = ContextFilter() | 
|  | 1539 | a1.addFilter(f) | 
|  | 1540 | a2.addFilter(f) | 
|  | 1541 | a1.debug("A debug message") | 
|  | 1542 | a1.info("An info message with %s", "some parameters") | 
|  | 1543 | for x in range(10): | 
|  | 1544 | lvl = choice(levels) | 
|  | 1545 | lvlname = logging.getLevelName(lvl) | 
|  | 1546 | a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters") | 
|  | 1547 |  | 
|  | 1548 | which, when run, produces something like:: | 
|  | 1549 |  | 
|  | 1550 | 2010-09-06 22:38:15,292 a.b.c DEBUG    IP: 123.231.231.123 User: fred     A debug message | 
|  | 1551 | 2010-09-06 22:38:15,300 a.b.c INFO     IP: 192.168.0.1     User: sheila   An info message with some parameters | 
|  | 1552 | 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters | 
|  | 1553 | 2010-09-06 22:38:15,300 d.e.f ERROR    IP: 127.0.0.1       User: jim      A message at ERROR level with 2 parameters | 
|  | 1554 | 2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 127.0.0.1       User: sheila   A message at DEBUG level with 2 parameters | 
|  | 1555 | 2010-09-06 22:38:15,300 d.e.f ERROR    IP: 123.231.231.123 User: fred     A message at ERROR level with 2 parameters | 
|  | 1556 | 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1     User: jim      A message at CRITICAL level with 2 parameters | 
|  | 1557 | 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters | 
|  | 1558 | 2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 192.168.0.1     User: jim      A message at DEBUG level with 2 parameters | 
|  | 1559 | 2010-09-06 22:38:15,301 d.e.f ERROR    IP: 127.0.0.1       User: sheila   A message at ERROR level with 2 parameters | 
|  | 1560 | 2010-09-06 22:38:15,301 d.e.f DEBUG    IP: 123.231.231.123 User: fred     A message at DEBUG level with 2 parameters | 
|  | 1561 | 2010-09-06 22:38:15,301 d.e.f INFO     IP: 123.231.231.123 User: fred     A message at INFO level with 2 parameters | 
|  | 1562 |  | 
|  | 1563 |  | 
| Vinay Sajip | 3a0dc30 | 2009-08-15 23:23:12 +0000 | [diff] [blame] | 1564 | .. _multiple-processes: | 
|  | 1565 |  | 
|  | 1566 | Logging to a single file from multiple processes | 
|  | 1567 | ------------------------------------------------ | 
|  | 1568 |  | 
|  | 1569 | Although logging is thread-safe, and logging to a single file from multiple | 
|  | 1570 | threads in a single process *is* supported, logging to a single file from | 
|  | 1571 | *multiple processes* is *not* supported, because there is no standard way to | 
|  | 1572 | serialize access to a single file across multiple processes in Python. If you | 
|  | 1573 | need to log to a single file from multiple processes, the best way of doing | 
|  | 1574 | this is to have all the processes log to a :class:`SocketHandler`, and have a | 
|  | 1575 | separate process which implements a socket server which reads from the socket | 
|  | 1576 | and logs to file. (If you prefer, you can dedicate one thread in one of the | 
|  | 1577 | existing processes to perform this function.) The following section documents | 
|  | 1578 | this approach in more detail and includes a working socket receiver which can | 
|  | 1579 | be used as a starting point for you to adapt in your own applications. | 
| Vinay Sajip | aa0665b | 2008-01-07 19:40:10 +0000 | [diff] [blame] | 1580 |  | 
| Vinay Sajip | 1c0b24f | 2009-08-15 23:34:47 +0000 | [diff] [blame] | 1581 | If you are using a recent version of Python which includes the | 
|  | 1582 | :mod:`multiprocessing` module, you can write your own handler which uses the | 
|  | 1583 | :class:`Lock` class from this module to serialize access to the file from | 
|  | 1584 | your processes. The existing :class:`FileHandler` and subclasses do not make | 
|  | 1585 | use of :mod:`multiprocessing` at present, though they may do so in the future. | 
| Vinay Sajip | 5e7f645 | 2009-08-17 13:14:37 +0000 | [diff] [blame] | 1586 | Note that at present, the :mod:`multiprocessing` module does not provide | 
|  | 1587 | working lock functionality on all platforms (see | 
|  | 1588 | http://bugs.python.org/issue3770). | 
| Vinay Sajip | 1c0b24f | 2009-08-15 23:34:47 +0000 | [diff] [blame] | 1589 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1590 | .. _network-logging: | 
|  | 1591 |  | 
|  | 1592 | Sending and receiving logging events across a network | 
|  | 1593 | ----------------------------------------------------- | 
|  | 1594 |  | 
|  | 1595 | Let's say you want to send logging events across a network, and handle them at | 
|  | 1596 | the receiving end. A simple way of doing this is attaching a | 
|  | 1597 | :class:`SocketHandler` instance to the root logger at the sending end:: | 
|  | 1598 |  | 
| Benjamin Peterson | a7b55a3 | 2009-02-20 03:31:23 +0000 | [diff] [blame] | 1599 | import logging, logging.handlers | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1600 |  | 
|  | 1601 | rootLogger = logging.getLogger('') | 
|  | 1602 | rootLogger.setLevel(logging.DEBUG) | 
|  | 1603 | socketHandler = logging.handlers.SocketHandler('localhost', | 
|  | 1604 | logging.handlers.DEFAULT_TCP_LOGGING_PORT) | 
|  | 1605 | # don't bother with a formatter, since a socket handler sends the event as | 
|  | 1606 | # an unformatted pickle | 
|  | 1607 | rootLogger.addHandler(socketHandler) | 
|  | 1608 |  | 
|  | 1609 | # Now, we can log to the root logger, or any other logger. First the root... | 
|  | 1610 | logging.info('Jackdaws love my big sphinx of quartz.') | 
|  | 1611 |  | 
|  | 1612 | # Now, define a couple of other loggers which might represent areas in your | 
|  | 1613 | # application: | 
|  | 1614 |  | 
|  | 1615 | logger1 = logging.getLogger('myapp.area1') | 
|  | 1616 | logger2 = logging.getLogger('myapp.area2') | 
|  | 1617 |  | 
|  | 1618 | logger1.debug('Quick zephyrs blow, vexing daft Jim.') | 
|  | 1619 | logger1.info('How quickly daft jumping zebras vex.') | 
|  | 1620 | logger2.warning('Jail zesty vixen who grabbed pay from quack.') | 
|  | 1621 | logger2.error('The five boxing wizards jump quickly.') | 
|  | 1622 |  | 
| Georg Brandl | e152a77 | 2008-05-24 18:31:28 +0000 | [diff] [blame] | 1623 | At the receiving end, you can set up a receiver using the :mod:`SocketServer` | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1624 | module. Here is a basic working example:: | 
|  | 1625 |  | 
|  | 1626 | import cPickle | 
|  | 1627 | import logging | 
|  | 1628 | import logging.handlers | 
| Georg Brandl | e152a77 | 2008-05-24 18:31:28 +0000 | [diff] [blame] | 1629 | import SocketServer | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1630 | import struct | 
|  | 1631 |  | 
|  | 1632 |  | 
| Georg Brandl | e152a77 | 2008-05-24 18:31:28 +0000 | [diff] [blame] | 1633 | class LogRecordStreamHandler(SocketServer.StreamRequestHandler): | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1634 | """Handler for a streaming logging request. | 
|  | 1635 |  | 
|  | 1636 | This basically logs the record using whatever logging policy is | 
|  | 1637 | configured locally. | 
|  | 1638 | """ | 
|  | 1639 |  | 
|  | 1640 | def handle(self): | 
|  | 1641 | """ | 
|  | 1642 | Handle multiple requests - each expected to be a 4-byte length, | 
|  | 1643 | followed by the LogRecord in pickle format. Logs the record | 
|  | 1644 | according to whatever policy is configured locally. | 
|  | 1645 | """ | 
|  | 1646 | while 1: | 
|  | 1647 | chunk = self.connection.recv(4) | 
|  | 1648 | if len(chunk) < 4: | 
|  | 1649 | break | 
|  | 1650 | slen = struct.unpack(">L", chunk)[0] | 
|  | 1651 | chunk = self.connection.recv(slen) | 
|  | 1652 | while len(chunk) < slen: | 
|  | 1653 | chunk = chunk + self.connection.recv(slen - len(chunk)) | 
|  | 1654 | obj = self.unPickle(chunk) | 
|  | 1655 | record = logging.makeLogRecord(obj) | 
|  | 1656 | self.handleLogRecord(record) | 
|  | 1657 |  | 
|  | 1658 | def unPickle(self, data): | 
|  | 1659 | return cPickle.loads(data) | 
|  | 1660 |  | 
|  | 1661 | def handleLogRecord(self, record): | 
|  | 1662 | # if a name is specified, we use the named logger rather than the one | 
|  | 1663 | # implied by the record. | 
|  | 1664 | if self.server.logname is not None: | 
|  | 1665 | name = self.server.logname | 
|  | 1666 | else: | 
|  | 1667 | name = record.name | 
|  | 1668 | logger = logging.getLogger(name) | 
|  | 1669 | # N.B. EVERY record gets logged. This is because Logger.handle | 
|  | 1670 | # is normally called AFTER logger-level filtering. If you want | 
|  | 1671 | # to do filtering, do it at the client end to save wasting | 
|  | 1672 | # cycles and network bandwidth! | 
|  | 1673 | logger.handle(record) | 
|  | 1674 |  | 
| Georg Brandl | e152a77 | 2008-05-24 18:31:28 +0000 | [diff] [blame] | 1675 | class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer): | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1676 | """simple TCP socket-based logging receiver suitable for testing. | 
|  | 1677 | """ | 
|  | 1678 |  | 
|  | 1679 | allow_reuse_address = 1 | 
|  | 1680 |  | 
|  | 1681 | def __init__(self, host='localhost', | 
|  | 1682 | port=logging.handlers.DEFAULT_TCP_LOGGING_PORT, | 
|  | 1683 | handler=LogRecordStreamHandler): | 
| Georg Brandl | e152a77 | 2008-05-24 18:31:28 +0000 | [diff] [blame] | 1684 | SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1685 | self.abort = 0 | 
|  | 1686 | self.timeout = 1 | 
|  | 1687 | self.logname = None | 
|  | 1688 |  | 
|  | 1689 | def serve_until_stopped(self): | 
|  | 1690 | import select | 
|  | 1691 | abort = 0 | 
|  | 1692 | while not abort: | 
|  | 1693 | rd, wr, ex = select.select([self.socket.fileno()], | 
|  | 1694 | [], [], | 
|  | 1695 | self.timeout) | 
|  | 1696 | if rd: | 
|  | 1697 | self.handle_request() | 
|  | 1698 | abort = self.abort | 
|  | 1699 |  | 
|  | 1700 | def main(): | 
|  | 1701 | logging.basicConfig( | 
|  | 1702 | format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s") | 
|  | 1703 | tcpserver = LogRecordSocketReceiver() | 
|  | 1704 | print "About to start TCP server..." | 
|  | 1705 | tcpserver.serve_until_stopped() | 
|  | 1706 |  | 
|  | 1707 | if __name__ == "__main__": | 
|  | 1708 | main() | 
|  | 1709 |  | 
|  | 1710 | First run the server, and then the client. On the client side, nothing is | 
|  | 1711 | printed on the console; on the server side, you should see something like:: | 
|  | 1712 |  | 
|  | 1713 | About to start TCP server... | 
|  | 1714 | 59 root            INFO     Jackdaws love my big sphinx of quartz. | 
|  | 1715 | 59 myapp.area1     DEBUG    Quick zephyrs blow, vexing daft Jim. | 
|  | 1716 | 69 myapp.area1     INFO     How quickly daft jumping zebras vex. | 
|  | 1717 | 69 myapp.area2     WARNING  Jail zesty vixen who grabbed pay from quack. | 
|  | 1718 | 69 myapp.area2     ERROR    The five boxing wizards jump quickly. | 
|  | 1719 |  | 
| Vinay Sajip | 80eed3e | 2010-07-06 15:08:55 +0000 | [diff] [blame] | 1720 | Note that there are some security issues with pickle in some scenarios. If | 
|  | 1721 | these affect you, you can use an alternative serialization scheme by overriding | 
|  | 1722 | the :meth:`makePickle` method and implementing your alternative there, as | 
|  | 1723 | well as adapting the above script to use your alternative serialization. | 
|  | 1724 |  | 
| Vinay Sajip | fe08e6f | 2010-09-11 10:25:28 +0000 | [diff] [blame] | 1725 | .. _arbitrary-object-messages: | 
|  | 1726 |  | 
| Vinay Sajip | f778bec | 2009-09-22 17:23:41 +0000 | [diff] [blame] | 1727 | Using arbitrary objects as messages | 
|  | 1728 | ----------------------------------- | 
|  | 1729 |  | 
|  | 1730 | In the preceding sections and examples, it has been assumed that the message | 
|  | 1731 | passed when logging the event is a string. However, this is not the only | 
|  | 1732 | possibility. You can pass an arbitrary object as a message, and its | 
|  | 1733 | :meth:`__str__` method will be called when the logging system needs to convert | 
|  | 1734 | it to a string representation. In fact, if you want to, you can avoid | 
|  | 1735 | computing a string representation altogether - for example, the | 
|  | 1736 | :class:`SocketHandler` emits an event by pickling it and sending it over the | 
|  | 1737 | wire. | 
|  | 1738 |  | 
|  | 1739 | Optimization | 
|  | 1740 | ------------ | 
|  | 1741 |  | 
|  | 1742 | Formatting of message arguments is deferred until it cannot be avoided. | 
|  | 1743 | However, computing the arguments passed to the logging method can also be | 
|  | 1744 | expensive, and you may want to avoid doing it if the logger will just throw | 
|  | 1745 | away your event. To decide what to do, you can call the :meth:`isEnabledFor` | 
|  | 1746 | method which takes a level argument and returns true if the event would be | 
|  | 1747 | created by the Logger for that level of call. You can write code like this:: | 
|  | 1748 |  | 
|  | 1749 | if logger.isEnabledFor(logging.DEBUG): | 
|  | 1750 | logger.debug("Message with %s, %s", expensive_func1(), | 
|  | 1751 | expensive_func2()) | 
|  | 1752 |  | 
|  | 1753 | so that if the logger's threshold is set above ``DEBUG``, the calls to | 
|  | 1754 | :func:`expensive_func1` and :func:`expensive_func2` are never made. | 
|  | 1755 |  | 
|  | 1756 | There are other optimizations which can be made for specific applications which | 
|  | 1757 | need more precise control over what logging information is collected. Here's a | 
|  | 1758 | list of things you can do to avoid processing during logging which you don't | 
|  | 1759 | need: | 
|  | 1760 |  | 
|  | 1761 | +-----------------------------------------------+----------------------------------------+ | 
|  | 1762 | | What you don't want to collect                | How to avoid collecting it             | | 
|  | 1763 | +===============================================+========================================+ | 
|  | 1764 | | Information about where calls were made from. | Set ``logging._srcfile`` to ``None``.  | | 
|  | 1765 | +-----------------------------------------------+----------------------------------------+ | 
|  | 1766 | | Threading information.                        | Set ``logging.logThreads`` to ``0``.   | | 
|  | 1767 | +-----------------------------------------------+----------------------------------------+ | 
|  | 1768 | | Process information.                          | Set ``logging.logProcesses`` to ``0``. | | 
|  | 1769 | +-----------------------------------------------+----------------------------------------+ | 
|  | 1770 |  | 
|  | 1771 | Also note that the core logging module only includes the basic handlers. If | 
|  | 1772 | you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't | 
|  | 1773 | take up any memory. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1774 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 1775 | .. _handler: | 
|  | 1776 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1777 | Handler Objects | 
|  | 1778 | --------------- | 
|  | 1779 |  | 
|  | 1780 | Handlers have the following attributes and methods. Note that :class:`Handler` | 
|  | 1781 | is never instantiated directly; this class acts as a base for more useful | 
|  | 1782 | subclasses. However, the :meth:`__init__` method in subclasses needs to call | 
|  | 1783 | :meth:`Handler.__init__`. | 
|  | 1784 |  | 
|  | 1785 |  | 
|  | 1786 | .. method:: Handler.__init__(level=NOTSET) | 
|  | 1787 |  | 
|  | 1788 | Initializes the :class:`Handler` instance by setting its level, setting the list | 
|  | 1789 | of filters to the empty list and creating a lock (using :meth:`createLock`) for | 
|  | 1790 | serializing access to an I/O mechanism. | 
|  | 1791 |  | 
|  | 1792 |  | 
|  | 1793 | .. method:: Handler.createLock() | 
|  | 1794 |  | 
|  | 1795 | Initializes a thread lock which can be used to serialize access to underlying | 
|  | 1796 | I/O functionality which may not be threadsafe. | 
|  | 1797 |  | 
|  | 1798 |  | 
|  | 1799 | .. method:: Handler.acquire() | 
|  | 1800 |  | 
|  | 1801 | Acquires the thread lock created with :meth:`createLock`. | 
|  | 1802 |  | 
|  | 1803 |  | 
|  | 1804 | .. method:: Handler.release() | 
|  | 1805 |  | 
|  | 1806 | Releases the thread lock acquired with :meth:`acquire`. | 
|  | 1807 |  | 
|  | 1808 |  | 
|  | 1809 | .. method:: Handler.setLevel(lvl) | 
|  | 1810 |  | 
|  | 1811 | Sets the threshold for this handler to *lvl*. Logging messages which are less | 
|  | 1812 | severe than *lvl* will be ignored. When a handler is created, the level is set | 
|  | 1813 | to :const:`NOTSET` (which causes all messages to be processed). | 
|  | 1814 |  | 
|  | 1815 |  | 
|  | 1816 | .. method:: Handler.setFormatter(form) | 
|  | 1817 |  | 
|  | 1818 | Sets the :class:`Formatter` for this handler to *form*. | 
|  | 1819 |  | 
|  | 1820 |  | 
|  | 1821 | .. method:: Handler.addFilter(filt) | 
|  | 1822 |  | 
|  | 1823 | Adds the specified filter *filt* to this handler. | 
|  | 1824 |  | 
|  | 1825 |  | 
|  | 1826 | .. method:: Handler.removeFilter(filt) | 
|  | 1827 |  | 
|  | 1828 | Removes the specified filter *filt* from this handler. | 
|  | 1829 |  | 
|  | 1830 |  | 
|  | 1831 | .. method:: Handler.filter(record) | 
|  | 1832 |  | 
|  | 1833 | Applies this handler's filters to the record and returns a true value if the | 
|  | 1834 | record is to be processed. | 
|  | 1835 |  | 
|  | 1836 |  | 
|  | 1837 | .. method:: Handler.flush() | 
|  | 1838 |  | 
|  | 1839 | Ensure all logging output has been flushed. This version does nothing and is | 
|  | 1840 | intended to be implemented by subclasses. | 
|  | 1841 |  | 
|  | 1842 |  | 
|  | 1843 | .. method:: Handler.close() | 
|  | 1844 |  | 
| Vinay Sajip | aa5f873 | 2008-09-01 17:44:14 +0000 | [diff] [blame] | 1845 | Tidy up any resources used by the handler. This version does no output but | 
|  | 1846 | removes the handler from an internal list of handlers which is closed when | 
|  | 1847 | :func:`shutdown` is called. Subclasses should ensure that this gets called | 
|  | 1848 | from overridden :meth:`close` methods. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1849 |  | 
|  | 1850 |  | 
|  | 1851 | .. method:: Handler.handle(record) | 
|  | 1852 |  | 
|  | 1853 | Conditionally emits the specified logging record, depending on filters which may | 
|  | 1854 | have been added to the handler. Wraps the actual emission of the record with | 
|  | 1855 | acquisition/release of the I/O thread lock. | 
|  | 1856 |  | 
|  | 1857 |  | 
|  | 1858 | .. method:: Handler.handleError(record) | 
|  | 1859 |  | 
|  | 1860 | This method should be called from handlers when an exception is encountered | 
|  | 1861 | during an :meth:`emit` call. By default it does nothing, which means that | 
|  | 1862 | exceptions get silently ignored. This is what is mostly wanted for a logging | 
|  | 1863 | system - most users will not care about errors in the logging system, they are | 
|  | 1864 | more interested in application errors. You could, however, replace this with a | 
|  | 1865 | custom handler if you wish. The specified record is the one which was being | 
|  | 1866 | processed when the exception occurred. | 
|  | 1867 |  | 
|  | 1868 |  | 
|  | 1869 | .. method:: Handler.format(record) | 
|  | 1870 |  | 
|  | 1871 | Do formatting for a record - if a formatter is set, use it. Otherwise, use the | 
|  | 1872 | default formatter for the module. | 
|  | 1873 |  | 
|  | 1874 |  | 
|  | 1875 | .. method:: Handler.emit(record) | 
|  | 1876 |  | 
|  | 1877 | Do whatever it takes to actually log the specified logging record. This version | 
|  | 1878 | is intended to be implemented by subclasses and so raises a | 
|  | 1879 | :exc:`NotImplementedError`. | 
|  | 1880 |  | 
|  | 1881 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 1882 | .. _stream-handler: | 
|  | 1883 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1884 | StreamHandler | 
|  | 1885 | ^^^^^^^^^^^^^ | 
|  | 1886 |  | 
|  | 1887 | The :class:`StreamHandler` class, located in the core :mod:`logging` package, | 
|  | 1888 | sends logging output to streams such as *sys.stdout*, *sys.stderr* or any | 
|  | 1889 | file-like object (or, more precisely, any object which supports :meth:`write` | 
|  | 1890 | and :meth:`flush` methods). | 
|  | 1891 |  | 
|  | 1892 |  | 
| Vinay Sajip | 0c6a0e3 | 2009-12-17 14:52:00 +0000 | [diff] [blame] | 1893 | .. currentmodule:: logging | 
|  | 1894 |  | 
| Vinay Sajip | 4780c9a | 2009-09-26 14:53:32 +0000 | [diff] [blame] | 1895 | .. class:: StreamHandler([stream]) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1896 |  | 
| Vinay Sajip | 4780c9a | 2009-09-26 14:53:32 +0000 | [diff] [blame] | 1897 | Returns a new instance of the :class:`StreamHandler` class. If *stream* is | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1898 | specified, the instance will use it for logging output; otherwise, *sys.stderr* | 
|  | 1899 | will be used. | 
|  | 1900 |  | 
|  | 1901 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 1902 | .. method:: emit(record) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1903 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 1904 | If a formatter is specified, it is used to format the record. The record | 
|  | 1905 | is then written to the stream with a trailing newline. If exception | 
|  | 1906 | information is present, it is formatted using | 
|  | 1907 | :func:`traceback.print_exception` and appended to the stream. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1908 |  | 
|  | 1909 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 1910 | .. method:: flush() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1911 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 1912 | Flushes the stream by calling its :meth:`flush` method. Note that the | 
|  | 1913 | :meth:`close` method is inherited from :class:`Handler` and so does | 
| Vinay Sajip | aa5f873 | 2008-09-01 17:44:14 +0000 | [diff] [blame] | 1914 | no output, so an explicit :meth:`flush` call may be needed at times. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1915 |  | 
|  | 1916 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 1917 | .. _file-handler: | 
|  | 1918 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1919 | FileHandler | 
|  | 1920 | ^^^^^^^^^^^ | 
|  | 1921 |  | 
|  | 1922 | The :class:`FileHandler` class, located in the core :mod:`logging` package, | 
|  | 1923 | sends logging output to a disk file.  It inherits the output functionality from | 
|  | 1924 | :class:`StreamHandler`. | 
|  | 1925 |  | 
|  | 1926 |  | 
| Vinay Sajip | f38ba78 | 2008-01-24 12:38:30 +0000 | [diff] [blame] | 1927 | .. class:: FileHandler(filename[, mode[, encoding[, delay]]]) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1928 |  | 
|  | 1929 | Returns a new instance of the :class:`FileHandler` class. The specified file is | 
|  | 1930 | opened and used as the stream for logging. If *mode* is not specified, | 
|  | 1931 | :const:`'a'` is used.  If *encoding* is not *None*, it is used to open the file | 
| Vinay Sajip | f38ba78 | 2008-01-24 12:38:30 +0000 | [diff] [blame] | 1932 | with that encoding.  If *delay* is true, then file opening is deferred until the | 
|  | 1933 | first call to :meth:`emit`. By default, the file grows indefinitely. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1934 |  | 
| Vinay Sajip | 59584c4 | 2009-08-14 11:33:54 +0000 | [diff] [blame] | 1935 | .. versionchanged:: 2.6 | 
|  | 1936 | *delay* was added. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1937 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 1938 | .. method:: close() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1939 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 1940 | Closes the file. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1941 |  | 
|  | 1942 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 1943 | .. method:: emit(record) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1944 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 1945 | Outputs the record to the file. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1946 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 1947 | .. _null-handler: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1948 |  | 
| Vinay Sajip | 5110486 | 2009-01-02 18:53:04 +0000 | [diff] [blame] | 1949 | NullHandler | 
|  | 1950 | ^^^^^^^^^^^ | 
|  | 1951 |  | 
|  | 1952 | .. versionadded:: 2.7 | 
|  | 1953 |  | 
|  | 1954 | The :class:`NullHandler` class, located in the core :mod:`logging` package, | 
|  | 1955 | does not do any formatting or output. It is essentially a "no-op" handler | 
|  | 1956 | for use by library developers. | 
|  | 1957 |  | 
|  | 1958 |  | 
|  | 1959 | .. class:: NullHandler() | 
|  | 1960 |  | 
|  | 1961 | Returns a new instance of the :class:`NullHandler` class. | 
|  | 1962 |  | 
|  | 1963 |  | 
|  | 1964 | .. method:: emit(record) | 
|  | 1965 |  | 
|  | 1966 | This method does nothing. | 
|  | 1967 |  | 
| Vinay Sajip | 47ca122 | 2010-09-27 13:53:47 +0000 | [diff] [blame] | 1968 | .. method:: handle(record) | 
|  | 1969 |  | 
|  | 1970 | This method does nothing. | 
|  | 1971 |  | 
|  | 1972 | .. method:: createLock() | 
|  | 1973 |  | 
|  | 1974 | This method returns `None` for the lock, since there is no | 
|  | 1975 | underlying I/O to which access needs to be serialized. | 
|  | 1976 |  | 
|  | 1977 |  | 
| Vinay Sajip | 99505c8 | 2009-01-10 13:38:04 +0000 | [diff] [blame] | 1978 | See :ref:`library-config` for more information on how to use | 
|  | 1979 | :class:`NullHandler`. | 
|  | 1980 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 1981 | .. _watched-file-handler: | 
|  | 1982 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1983 | WatchedFileHandler | 
|  | 1984 | ^^^^^^^^^^^^^^^^^^ | 
|  | 1985 |  | 
|  | 1986 | .. versionadded:: 2.6 | 
|  | 1987 |  | 
| Vinay Sajip | b1a15e4 | 2009-01-15 23:04:47 +0000 | [diff] [blame] | 1988 | .. currentmodule:: logging.handlers | 
| Vinay Sajip | 5110486 | 2009-01-02 18:53:04 +0000 | [diff] [blame] | 1989 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1990 | The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers` | 
|  | 1991 | module, is a :class:`FileHandler` which watches the file it is logging to. If | 
|  | 1992 | the file changes, it is closed and reopened using the file name. | 
|  | 1993 |  | 
|  | 1994 | A file change can happen because of usage of programs such as *newsyslog* and | 
|  | 1995 | *logrotate* which perform log file rotation. This handler, intended for use | 
|  | 1996 | under Unix/Linux, watches the file to see if it has changed since the last emit. | 
|  | 1997 | (A file is deemed to have changed if its device or inode have changed.) If the | 
|  | 1998 | file has changed, the old file stream is closed, and the file opened to get a | 
|  | 1999 | new stream. | 
|  | 2000 |  | 
|  | 2001 | This handler is not appropriate for use under Windows, because under Windows | 
|  | 2002 | open log files cannot be moved or renamed - logging opens the files with | 
|  | 2003 | exclusive locks - and so there is no need for such a handler. Furthermore, | 
|  | 2004 | *ST_INO* is not supported under Windows; :func:`stat` always returns zero for | 
|  | 2005 | this value. | 
|  | 2006 |  | 
|  | 2007 |  | 
| Vinay Sajip | f38ba78 | 2008-01-24 12:38:30 +0000 | [diff] [blame] | 2008 | .. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]]) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2009 |  | 
|  | 2010 | Returns a new instance of the :class:`WatchedFileHandler` class. The specified | 
|  | 2011 | file is opened and used as the stream for logging. If *mode* is not specified, | 
|  | 2012 | :const:`'a'` is used.  If *encoding* is not *None*, it is used to open the file | 
| Vinay Sajip | f38ba78 | 2008-01-24 12:38:30 +0000 | [diff] [blame] | 2013 | with that encoding.  If *delay* is true, then file opening is deferred until the | 
|  | 2014 | first call to :meth:`emit`.  By default, the file grows indefinitely. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2015 |  | 
| Vinay Sajip | 59584c4 | 2009-08-14 11:33:54 +0000 | [diff] [blame] | 2016 | .. versionchanged:: 2.6 | 
|  | 2017 | *delay* was added. | 
|  | 2018 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2019 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2020 | .. method:: emit(record) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2021 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2022 | Outputs the record to the file, but first checks to see if the file has | 
|  | 2023 | changed.  If it has, the existing stream is flushed and closed and the | 
|  | 2024 | file opened again, before outputting the record to the file. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2025 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 2026 | .. _rotating-file-handler: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2027 |  | 
|  | 2028 | RotatingFileHandler | 
|  | 2029 | ^^^^^^^^^^^^^^^^^^^ | 
|  | 2030 |  | 
|  | 2031 | The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers` | 
|  | 2032 | module, supports rotation of disk log files. | 
|  | 2033 |  | 
|  | 2034 |  | 
| Vinay Sajip | f38ba78 | 2008-01-24 12:38:30 +0000 | [diff] [blame] | 2035 | .. class:: RotatingFileHandler(filename[, mode[, maxBytes[, backupCount[, encoding[, delay]]]]]) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2036 |  | 
|  | 2037 | Returns a new instance of the :class:`RotatingFileHandler` class. The specified | 
|  | 2038 | file is opened and used as the stream for logging. If *mode* is not specified, | 
| Vinay Sajip | f38ba78 | 2008-01-24 12:38:30 +0000 | [diff] [blame] | 2039 | ``'a'`` is used.  If *encoding* is not *None*, it is used to open the file | 
|  | 2040 | with that encoding.  If *delay* is true, then file opening is deferred until the | 
|  | 2041 | first call to :meth:`emit`.  By default, the file grows indefinitely. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2042 |  | 
|  | 2043 | You can use the *maxBytes* and *backupCount* values to allow the file to | 
|  | 2044 | :dfn:`rollover` at a predetermined size. When the size is about to be exceeded, | 
|  | 2045 | the file is closed and a new file is silently opened for output. Rollover occurs | 
|  | 2046 | whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is | 
|  | 2047 | zero, rollover never occurs.  If *backupCount* is non-zero, the system will save | 
|  | 2048 | old log files by appending the extensions ".1", ".2" etc., to the filename. For | 
|  | 2049 | example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you | 
|  | 2050 | would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to | 
|  | 2051 | :file:`app.log.5`. The file being written to is always :file:`app.log`.  When | 
|  | 2052 | this file is filled, it is closed and renamed to :file:`app.log.1`, and if files | 
|  | 2053 | :file:`app.log.1`, :file:`app.log.2`, etc.  exist, then they are renamed to | 
|  | 2054 | :file:`app.log.2`, :file:`app.log.3` etc.  respectively. | 
|  | 2055 |  | 
| Vinay Sajip | 59584c4 | 2009-08-14 11:33:54 +0000 | [diff] [blame] | 2056 | .. versionchanged:: 2.6 | 
|  | 2057 | *delay* was added. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2058 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2059 | .. method:: doRollover() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2060 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2061 | Does a rollover, as described above. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2062 |  | 
|  | 2063 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2064 | .. method:: emit(record) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2065 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2066 | Outputs the record to the file, catering for rollover as described | 
|  | 2067 | previously. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2068 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 2069 | .. _timed-rotating-file-handler: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2070 |  | 
|  | 2071 | TimedRotatingFileHandler | 
|  | 2072 | ^^^^^^^^^^^^^^^^^^^^^^^^ | 
|  | 2073 |  | 
|  | 2074 | The :class:`TimedRotatingFileHandler` class, located in the | 
|  | 2075 | :mod:`logging.handlers` module, supports rotation of disk log files at certain | 
|  | 2076 | timed intervals. | 
|  | 2077 |  | 
|  | 2078 |  | 
| Andrew M. Kuchling | 6dd8cca | 2008-06-05 23:33:54 +0000 | [diff] [blame] | 2079 | .. class:: TimedRotatingFileHandler(filename [,when [,interval [,backupCount[, encoding[, delay[, utc]]]]]]) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2080 |  | 
|  | 2081 | Returns a new instance of the :class:`TimedRotatingFileHandler` class. The | 
|  | 2082 | specified file is opened and used as the stream for logging. On rotating it also | 
|  | 2083 | sets the filename suffix. Rotating happens based on the product of *when* and | 
|  | 2084 | *interval*. | 
|  | 2085 |  | 
|  | 2086 | You can use the *when* to specify the type of *interval*. The list of possible | 
| Georg Brandl | d77554f | 2008-06-06 07:34:50 +0000 | [diff] [blame] | 2087 | values is below.  Note that they are not case sensitive. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2088 |  | 
| Georg Brandl | 72780a4 | 2008-03-02 13:41:39 +0000 | [diff] [blame] | 2089 | +----------------+-----------------------+ | 
|  | 2090 | | Value          | Type of interval      | | 
|  | 2091 | +================+=======================+ | 
|  | 2092 | | ``'S'``        | Seconds               | | 
|  | 2093 | +----------------+-----------------------+ | 
|  | 2094 | | ``'M'``        | Minutes               | | 
|  | 2095 | +----------------+-----------------------+ | 
|  | 2096 | | ``'H'``        | Hours                 | | 
|  | 2097 | +----------------+-----------------------+ | 
|  | 2098 | | ``'D'``        | Days                  | | 
|  | 2099 | +----------------+-----------------------+ | 
|  | 2100 | | ``'W'``        | Week day (0=Monday)   | | 
|  | 2101 | +----------------+-----------------------+ | 
|  | 2102 | | ``'midnight'`` | Roll over at midnight | | 
|  | 2103 | +----------------+-----------------------+ | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2104 |  | 
| Georg Brandl | e6dab2a | 2008-03-02 14:15:04 +0000 | [diff] [blame] | 2105 | The system will save old log files by appending extensions to the filename. | 
|  | 2106 | The extensions are date-and-time based, using the strftime format | 
| Vinay Sajip | 89a01cd | 2008-04-02 21:17:25 +0000 | [diff] [blame] | 2107 | ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the | 
| Vinay Sajip | 2a649f9 | 2008-07-18 09:00:35 +0000 | [diff] [blame] | 2108 | rollover interval. | 
| Vinay Sajip | ecfa08f | 2010-03-12 09:16:10 +0000 | [diff] [blame] | 2109 |  | 
|  | 2110 | When computing the next rollover time for the first time (when the handler | 
|  | 2111 | is created), the last modification time of an existing log file, or else | 
|  | 2112 | the current time, is used to compute when the next rotation will occur. | 
|  | 2113 |  | 
| Georg Brandl | d77554f | 2008-06-06 07:34:50 +0000 | [diff] [blame] | 2114 | If the *utc* argument is true, times in UTC will be used; otherwise | 
| Andrew M. Kuchling | 6dd8cca | 2008-06-05 23:33:54 +0000 | [diff] [blame] | 2115 | local time is used. | 
|  | 2116 |  | 
|  | 2117 | If *backupCount* is nonzero, at most *backupCount* files | 
| Vinay Sajip | 89a01cd | 2008-04-02 21:17:25 +0000 | [diff] [blame] | 2118 | will be kept, and if more would be created when rollover occurs, the oldest | 
|  | 2119 | one is deleted. The deletion logic uses the interval to determine which | 
|  | 2120 | files to delete, so changing the interval may leave old files lying around. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2121 |  | 
| Vinay Sajip | 59584c4 | 2009-08-14 11:33:54 +0000 | [diff] [blame] | 2122 | If *delay* is true, then file opening is deferred until the first call to | 
|  | 2123 | :meth:`emit`. | 
|  | 2124 |  | 
|  | 2125 | .. versionchanged:: 2.6 | 
|  | 2126 | *delay* was added. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2127 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2128 | .. method:: doRollover() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2129 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2130 | Does a rollover, as described above. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2131 |  | 
|  | 2132 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2133 | .. method:: emit(record) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2134 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2135 | Outputs the record to the file, catering for rollover as described above. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2136 |  | 
|  | 2137 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 2138 | .. _socket-handler: | 
|  | 2139 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2140 | SocketHandler | 
|  | 2141 | ^^^^^^^^^^^^^ | 
|  | 2142 |  | 
|  | 2143 | The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module, | 
|  | 2144 | sends logging output to a network socket. The base class uses a TCP socket. | 
|  | 2145 |  | 
|  | 2146 |  | 
|  | 2147 | .. class:: SocketHandler(host, port) | 
|  | 2148 |  | 
|  | 2149 | Returns a new instance of the :class:`SocketHandler` class intended to | 
|  | 2150 | communicate with a remote machine whose address is given by *host* and *port*. | 
|  | 2151 |  | 
|  | 2152 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2153 | .. method:: close() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2154 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2155 | Closes the socket. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2156 |  | 
|  | 2157 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2158 | .. method:: emit() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2159 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2160 | Pickles the record's attribute dictionary and writes it to the socket in | 
|  | 2161 | binary format. If there is an error with the socket, silently drops the | 
|  | 2162 | packet. If the connection was previously lost, re-establishes the | 
|  | 2163 | connection. To unpickle the record at the receiving end into a | 
|  | 2164 | :class:`LogRecord`, use the :func:`makeLogRecord` function. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2165 |  | 
|  | 2166 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2167 | .. method:: handleError() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2168 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2169 | Handles an error which has occurred during :meth:`emit`. The most likely | 
|  | 2170 | cause is a lost connection. Closes the socket so that we can retry on the | 
|  | 2171 | next event. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2172 |  | 
|  | 2173 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2174 | .. method:: makeSocket() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2175 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2176 | This is a factory method which allows subclasses to define the precise | 
|  | 2177 | type of socket they want. The default implementation creates a TCP socket | 
|  | 2178 | (:const:`socket.SOCK_STREAM`). | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2179 |  | 
|  | 2180 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2181 | .. method:: makePickle(record) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2182 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2183 | Pickles the record's attribute dictionary in binary format with a length | 
|  | 2184 | prefix, and returns it ready for transmission across the socket. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2185 |  | 
| Vinay Sajip | 86aa905 | 2010-06-29 15:13:14 +0000 | [diff] [blame] | 2186 | Note that pickles aren't completely secure. If you are concerned about | 
|  | 2187 | security, you may want to override this method to implement a more secure | 
|  | 2188 | mechanism. For example, you can sign pickles using HMAC and then verify | 
|  | 2189 | them on the receiving end, or alternatively you can disable unpickling of | 
|  | 2190 | global objects on the receiving end. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2191 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2192 | .. method:: send(packet) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2193 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2194 | Send a pickled string *packet* to the socket. This function allows for | 
|  | 2195 | partial sends which can happen when the network is busy. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2196 |  | 
|  | 2197 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 2198 | .. _datagram-handler: | 
|  | 2199 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2200 | DatagramHandler | 
|  | 2201 | ^^^^^^^^^^^^^^^ | 
|  | 2202 |  | 
|  | 2203 | The :class:`DatagramHandler` class, located in the :mod:`logging.handlers` | 
|  | 2204 | module, inherits from :class:`SocketHandler` to support sending logging messages | 
|  | 2205 | over UDP sockets. | 
|  | 2206 |  | 
|  | 2207 |  | 
|  | 2208 | .. class:: DatagramHandler(host, port) | 
|  | 2209 |  | 
|  | 2210 | Returns a new instance of the :class:`DatagramHandler` class intended to | 
|  | 2211 | communicate with a remote machine whose address is given by *host* and *port*. | 
|  | 2212 |  | 
|  | 2213 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2214 | .. method:: emit() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2215 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2216 | Pickles the record's attribute dictionary and writes it to the socket in | 
|  | 2217 | binary format. If there is an error with the socket, silently drops the | 
|  | 2218 | packet. To unpickle the record at the receiving end into a | 
|  | 2219 | :class:`LogRecord`, use the :func:`makeLogRecord` function. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2220 |  | 
|  | 2221 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2222 | .. method:: makeSocket() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2223 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2224 | The factory method of :class:`SocketHandler` is here overridden to create | 
|  | 2225 | a UDP socket (:const:`socket.SOCK_DGRAM`). | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2226 |  | 
|  | 2227 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2228 | .. method:: send(s) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2229 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2230 | Send a pickled string to a socket. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2231 |  | 
|  | 2232 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 2233 | .. _syslog-handler: | 
|  | 2234 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2235 | SysLogHandler | 
|  | 2236 | ^^^^^^^^^^^^^ | 
|  | 2237 |  | 
|  | 2238 | The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module, | 
|  | 2239 | supports sending logging messages to a remote or local Unix syslog. | 
|  | 2240 |  | 
|  | 2241 |  | 
| Vinay Sajip | 1c77b7f | 2009-10-10 20:32:36 +0000 | [diff] [blame] | 2242 | .. class:: SysLogHandler([address[, facility[, socktype]]]) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2243 |  | 
|  | 2244 | Returns a new instance of the :class:`SysLogHandler` class intended to | 
|  | 2245 | communicate with a remote Unix machine whose address is given by *address* in | 
|  | 2246 | the form of a ``(host, port)`` tuple.  If *address* is not specified, | 
| Vinay Sajip | 1c77b7f | 2009-10-10 20:32:36 +0000 | [diff] [blame] | 2247 | ``('localhost', 514)`` is used.  The address is used to open a socket.  An | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2248 | alternative to providing a ``(host, port)`` tuple is providing an address as a | 
|  | 2249 | string, for example "/dev/log". In this case, a Unix domain socket is used to | 
|  | 2250 | send the message to the syslog. If *facility* is not specified, | 
| Vinay Sajip | 1c77b7f | 2009-10-10 20:32:36 +0000 | [diff] [blame] | 2251 | :const:`LOG_USER` is used. The type of socket opened depends on the | 
|  | 2252 | *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus | 
|  | 2253 | opens a UDP socket. To open a TCP socket (for use with the newer syslog | 
|  | 2254 | daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`. | 
|  | 2255 |  | 
|  | 2256 | .. versionchanged:: 2.7 | 
|  | 2257 | *socktype* was added. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2258 |  | 
|  | 2259 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2260 | .. method:: close() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2261 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2262 | Closes the socket to the remote host. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2263 |  | 
|  | 2264 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2265 | .. method:: emit(record) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2266 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2267 | The record is formatted, and then sent to the syslog server. If exception | 
|  | 2268 | information is present, it is *not* sent to the server. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2269 |  | 
|  | 2270 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2271 | .. method:: encodePriority(facility, priority) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2272 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2273 | Encodes the facility and priority into an integer. You can pass in strings | 
|  | 2274 | or integers - if strings are passed, internal mapping dictionaries are | 
|  | 2275 | used to convert them to integers. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2276 |  | 
| Vinay Sajip | a3c39c0 | 2010-03-24 15:10:40 +0000 | [diff] [blame] | 2277 | The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and | 
|  | 2278 | mirror the values defined in the ``sys/syslog.h`` header file. | 
| Vinay Sajip | b0623d6 | 2010-03-24 14:31:21 +0000 | [diff] [blame] | 2279 |  | 
| Georg Brandl | d3bab6a | 2010-04-02 09:03:18 +0000 | [diff] [blame] | 2280 | **Priorities** | 
|  | 2281 |  | 
| Vinay Sajip | b0623d6 | 2010-03-24 14:31:21 +0000 | [diff] [blame] | 2282 | +--------------------------+---------------+ | 
|  | 2283 | | Name (string)            | Symbolic value| | 
|  | 2284 | +==========================+===============+ | 
|  | 2285 | | ``alert``                | LOG_ALERT     | | 
|  | 2286 | +--------------------------+---------------+ | 
|  | 2287 | | ``crit`` or ``critical`` | LOG_CRIT      | | 
|  | 2288 | +--------------------------+---------------+ | 
|  | 2289 | | ``debug``                | LOG_DEBUG     | | 
|  | 2290 | +--------------------------+---------------+ | 
|  | 2291 | | ``emerg`` or ``panic``   | LOG_EMERG     | | 
|  | 2292 | +--------------------------+---------------+ | 
|  | 2293 | | ``err`` or ``error``     | LOG_ERR       | | 
|  | 2294 | +--------------------------+---------------+ | 
|  | 2295 | | ``info``                 | LOG_INFO      | | 
|  | 2296 | +--------------------------+---------------+ | 
|  | 2297 | | ``notice``               | LOG_NOTICE    | | 
|  | 2298 | +--------------------------+---------------+ | 
|  | 2299 | | ``warn`` or ``warning``  | LOG_WARNING   | | 
|  | 2300 | +--------------------------+---------------+ | 
|  | 2301 |  | 
| Georg Brandl | d3bab6a | 2010-04-02 09:03:18 +0000 | [diff] [blame] | 2302 | **Facilities** | 
|  | 2303 |  | 
| Vinay Sajip | b0623d6 | 2010-03-24 14:31:21 +0000 | [diff] [blame] | 2304 | +---------------+---------------+ | 
|  | 2305 | | Name (string) | Symbolic value| | 
|  | 2306 | +===============+===============+ | 
|  | 2307 | | ``auth``      | LOG_AUTH      | | 
|  | 2308 | +---------------+---------------+ | 
|  | 2309 | | ``authpriv``  | LOG_AUTHPRIV  | | 
|  | 2310 | +---------------+---------------+ | 
|  | 2311 | | ``cron``      | LOG_CRON      | | 
|  | 2312 | +---------------+---------------+ | 
|  | 2313 | | ``daemon``    | LOG_DAEMON    | | 
|  | 2314 | +---------------+---------------+ | 
|  | 2315 | | ``ftp``       | LOG_FTP       | | 
|  | 2316 | +---------------+---------------+ | 
|  | 2317 | | ``kern``      | LOG_KERN      | | 
|  | 2318 | +---------------+---------------+ | 
|  | 2319 | | ``lpr``       | LOG_LPR       | | 
|  | 2320 | +---------------+---------------+ | 
|  | 2321 | | ``mail``      | LOG_MAIL      | | 
|  | 2322 | +---------------+---------------+ | 
|  | 2323 | | ``news``      | LOG_NEWS      | | 
|  | 2324 | +---------------+---------------+ | 
|  | 2325 | | ``syslog``    | LOG_SYSLOG    | | 
|  | 2326 | +---------------+---------------+ | 
|  | 2327 | | ``user``      | LOG_USER      | | 
|  | 2328 | +---------------+---------------+ | 
|  | 2329 | | ``uucp``      | LOG_UUCP      | | 
|  | 2330 | +---------------+---------------+ | 
|  | 2331 | | ``local0``    | LOG_LOCAL0    | | 
|  | 2332 | +---------------+---------------+ | 
|  | 2333 | | ``local1``    | LOG_LOCAL1    | | 
|  | 2334 | +---------------+---------------+ | 
|  | 2335 | | ``local2``    | LOG_LOCAL2    | | 
|  | 2336 | +---------------+---------------+ | 
|  | 2337 | | ``local3``    | LOG_LOCAL3    | | 
|  | 2338 | +---------------+---------------+ | 
|  | 2339 | | ``local4``    | LOG_LOCAL4    | | 
|  | 2340 | +---------------+---------------+ | 
|  | 2341 | | ``local5``    | LOG_LOCAL5    | | 
|  | 2342 | +---------------+---------------+ | 
|  | 2343 | | ``local6``    | LOG_LOCAL6    | | 
|  | 2344 | +---------------+---------------+ | 
|  | 2345 | | ``local7``    | LOG_LOCAL7    | | 
|  | 2346 | +---------------+---------------+ | 
|  | 2347 |  | 
| Vinay Sajip | 66d19e2 | 2010-03-24 17:36:35 +0000 | [diff] [blame] | 2348 | .. method:: mapPriority(levelname) | 
|  | 2349 |  | 
|  | 2350 | Maps a logging level name to a syslog priority name. | 
|  | 2351 | You may need to override this if you are using custom levels, or | 
|  | 2352 | if the default algorithm is not suitable for your needs. The | 
|  | 2353 | default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and | 
|  | 2354 | ``CRITICAL`` to the equivalent syslog names, and all other level | 
|  | 2355 | names to "warning". | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2356 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 2357 | .. _nt-eventlog-handler: | 
|  | 2358 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2359 | NTEventLogHandler | 
|  | 2360 | ^^^^^^^^^^^^^^^^^ | 
|  | 2361 |  | 
|  | 2362 | The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers` | 
|  | 2363 | module, supports sending logging messages to a local Windows NT, Windows 2000 or | 
|  | 2364 | Windows XP event log. Before you can use it, you need Mark Hammond's Win32 | 
|  | 2365 | extensions for Python installed. | 
|  | 2366 |  | 
|  | 2367 |  | 
|  | 2368 | .. class:: NTEventLogHandler(appname[, dllname[, logtype]]) | 
|  | 2369 |  | 
|  | 2370 | Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is | 
|  | 2371 | used to define the application name as it appears in the event log. An | 
|  | 2372 | appropriate registry entry is created using this name. The *dllname* should give | 
|  | 2373 | the fully qualified pathname of a .dll or .exe which contains message | 
|  | 2374 | definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used | 
|  | 2375 | - this is installed with the Win32 extensions and contains some basic | 
|  | 2376 | placeholder message definitions. Note that use of these placeholders will make | 
|  | 2377 | your event logs big, as the entire message source is held in the log. If you | 
|  | 2378 | want slimmer logs, you have to pass in the name of your own .dll or .exe which | 
|  | 2379 | contains the message definitions you want to use in the event log). The | 
|  | 2380 | *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and | 
|  | 2381 | defaults to ``'Application'``. | 
|  | 2382 |  | 
|  | 2383 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2384 | .. method:: close() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2385 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2386 | At this point, you can remove the application name from the registry as a | 
|  | 2387 | source of event log entries. However, if you do this, you will not be able | 
|  | 2388 | to see the events as you intended in the Event Log Viewer - it needs to be | 
|  | 2389 | able to access the registry to get the .dll name. The current version does | 
| Vinay Sajip | aa5f873 | 2008-09-01 17:44:14 +0000 | [diff] [blame] | 2390 | not do this. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2391 |  | 
|  | 2392 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2393 | .. method:: emit(record) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2394 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2395 | Determines the message ID, event category and event type, and then logs | 
|  | 2396 | the message in the NT event log. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2397 |  | 
|  | 2398 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2399 | .. method:: getEventCategory(record) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2400 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2401 | Returns the event category for the record. Override this if you want to | 
|  | 2402 | specify your own categories. This version returns 0. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2403 |  | 
|  | 2404 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2405 | .. method:: getEventType(record) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2406 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2407 | Returns the event type for the record. Override this if you want to | 
|  | 2408 | specify your own types. This version does a mapping using the handler's | 
|  | 2409 | typemap attribute, which is set up in :meth:`__init__` to a dictionary | 
|  | 2410 | which contains mappings for :const:`DEBUG`, :const:`INFO`, | 
|  | 2411 | :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using | 
|  | 2412 | your own levels, you will either need to override this method or place a | 
|  | 2413 | suitable dictionary in the handler's *typemap* attribute. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2414 |  | 
|  | 2415 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2416 | .. method:: getMessageID(record) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2417 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2418 | Returns the message ID for the record. If you are using your own messages, | 
|  | 2419 | you could do this by having the *msg* passed to the logger being an ID | 
|  | 2420 | rather than a format string. Then, in here, you could use a dictionary | 
|  | 2421 | lookup to get the message ID. This version returns 1, which is the base | 
|  | 2422 | message ID in :file:`win32service.pyd`. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2423 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 2424 | .. _smtp-handler: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2425 |  | 
|  | 2426 | SMTPHandler | 
|  | 2427 | ^^^^^^^^^^^ | 
|  | 2428 |  | 
|  | 2429 | The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module, | 
|  | 2430 | supports sending logging messages to an email address via SMTP. | 
|  | 2431 |  | 
|  | 2432 |  | 
|  | 2433 | .. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject[, credentials]) | 
|  | 2434 |  | 
|  | 2435 | Returns a new instance of the :class:`SMTPHandler` class. The instance is | 
|  | 2436 | initialized with the from and to addresses and subject line of the email. The | 
|  | 2437 | *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use | 
|  | 2438 | the (host, port) tuple format for the *mailhost* argument. If you use a string, | 
|  | 2439 | the standard SMTP port is used. If your SMTP server requires authentication, you | 
|  | 2440 | can specify a (username, password) tuple for the *credentials* argument. | 
|  | 2441 |  | 
|  | 2442 | .. versionchanged:: 2.6 | 
|  | 2443 | *credentials* was added. | 
|  | 2444 |  | 
|  | 2445 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2446 | .. method:: emit(record) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2447 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2448 | Formats the record and sends it to the specified addressees. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2449 |  | 
|  | 2450 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2451 | .. method:: getSubject(record) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2452 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2453 | If you want to specify a subject line which is record-dependent, override | 
|  | 2454 | this method. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2455 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 2456 | .. _memory-handler: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2457 |  | 
|  | 2458 | MemoryHandler | 
|  | 2459 | ^^^^^^^^^^^^^ | 
|  | 2460 |  | 
|  | 2461 | The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module, | 
|  | 2462 | supports buffering of logging records in memory, periodically flushing them to a | 
|  | 2463 | :dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an | 
|  | 2464 | event of a certain severity or greater is seen. | 
|  | 2465 |  | 
|  | 2466 | :class:`MemoryHandler` is a subclass of the more general | 
|  | 2467 | :class:`BufferingHandler`, which is an abstract class. This buffers logging | 
|  | 2468 | records in memory. Whenever each record is added to the buffer, a check is made | 
|  | 2469 | by calling :meth:`shouldFlush` to see if the buffer should be flushed.  If it | 
|  | 2470 | should, then :meth:`flush` is expected to do the needful. | 
|  | 2471 |  | 
|  | 2472 |  | 
|  | 2473 | .. class:: BufferingHandler(capacity) | 
|  | 2474 |  | 
|  | 2475 | Initializes the handler with a buffer of the specified capacity. | 
|  | 2476 |  | 
|  | 2477 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2478 | .. method:: emit(record) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2479 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2480 | Appends the record to the buffer. If :meth:`shouldFlush` returns true, | 
|  | 2481 | calls :meth:`flush` to process the buffer. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2482 |  | 
|  | 2483 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2484 | .. method:: flush() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2485 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2486 | You can override this to implement custom flushing behavior. This version | 
|  | 2487 | just zaps the buffer to empty. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2488 |  | 
|  | 2489 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2490 | .. method:: shouldFlush(record) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2491 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2492 | Returns true if the buffer is up to capacity. This method can be | 
|  | 2493 | overridden to implement custom flushing strategies. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2494 |  | 
|  | 2495 |  | 
|  | 2496 | .. class:: MemoryHandler(capacity[, flushLevel [, target]]) | 
|  | 2497 |  | 
|  | 2498 | Returns a new instance of the :class:`MemoryHandler` class. The instance is | 
|  | 2499 | initialized with a buffer size of *capacity*. If *flushLevel* is not specified, | 
|  | 2500 | :const:`ERROR` is used. If no *target* is specified, the target will need to be | 
|  | 2501 | set using :meth:`setTarget` before this handler does anything useful. | 
|  | 2502 |  | 
|  | 2503 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2504 | .. method:: close() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2505 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2506 | Calls :meth:`flush`, sets the target to :const:`None` and clears the | 
|  | 2507 | buffer. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2508 |  | 
|  | 2509 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2510 | .. method:: flush() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2511 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2512 | For a :class:`MemoryHandler`, flushing means just sending the buffered | 
|  | 2513 | records to the target, if there is one. Override if you want different | 
|  | 2514 | behavior. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2515 |  | 
|  | 2516 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2517 | .. method:: setTarget(target) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2518 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2519 | Sets the target handler for this handler. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2520 |  | 
|  | 2521 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2522 | .. method:: shouldFlush(record) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2523 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2524 | Checks for buffer full or a record at the *flushLevel* or higher. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2525 |  | 
|  | 2526 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 2527 | .. _http-handler: | 
|  | 2528 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2529 | HTTPHandler | 
|  | 2530 | ^^^^^^^^^^^ | 
|  | 2531 |  | 
|  | 2532 | The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module, | 
|  | 2533 | supports sending logging messages to a Web server, using either ``GET`` or | 
|  | 2534 | ``POST`` semantics. | 
|  | 2535 |  | 
|  | 2536 |  | 
|  | 2537 | .. class:: HTTPHandler(host, url[, method]) | 
|  | 2538 |  | 
|  | 2539 | Returns a new instance of the :class:`HTTPHandler` class. The instance is | 
|  | 2540 | initialized with a host address, url and HTTP method. The *host* can be of the | 
|  | 2541 | form ``host:port``, should you need to use a specific port number. If no | 
|  | 2542 | *method* is specified, ``GET`` is used. | 
|  | 2543 |  | 
|  | 2544 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2545 | .. method:: emit(record) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2546 |  | 
| Senthil Kumaran | bd13f45 | 2010-08-09 20:14:11 +0000 | [diff] [blame] | 2547 | Sends the record to the Web server as a percent-encoded dictionary. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2548 |  | 
|  | 2549 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 2550 | .. _formatter: | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 2551 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2552 | Formatter Objects | 
|  | 2553 | ----------------- | 
|  | 2554 |  | 
| Georg Brandl | 430effb | 2009-01-01 13:05:13 +0000 | [diff] [blame] | 2555 | .. currentmodule:: logging | 
|  | 2556 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2557 | :class:`Formatter`\ s have the following attributes and methods. They are | 
|  | 2558 | responsible for converting a :class:`LogRecord` to (usually) a string which can | 
|  | 2559 | be interpreted by either a human or an external system. The base | 
|  | 2560 | :class:`Formatter` allows a formatting string to be specified. If none is | 
|  | 2561 | supplied, the default value of ``'%(message)s'`` is used. | 
|  | 2562 |  | 
|  | 2563 | A Formatter can be initialized with a format string which makes use of knowledge | 
|  | 2564 | of the :class:`LogRecord` attributes - such as the default value mentioned above | 
|  | 2565 | making use of the fact that the user's message and arguments are pre-formatted | 
|  | 2566 | into a :class:`LogRecord`'s *message* attribute.  This format string contains | 
| Ezio Melotti | 062d2b5 | 2009-12-19 22:41:49 +0000 | [diff] [blame] | 2567 | standard Python %-style mapping keys. See section :ref:`string-formatting` | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2568 | for more information on string formatting. | 
|  | 2569 |  | 
|  | 2570 | Currently, the useful mapping keys in a :class:`LogRecord` are: | 
|  | 2571 |  | 
|  | 2572 | +-------------------------+-----------------------------------------------+ | 
|  | 2573 | | Format                  | Description                                   | | 
|  | 2574 | +=========================+===============================================+ | 
|  | 2575 | | ``%(name)s``            | Name of the logger (logging channel).         | | 
|  | 2576 | +-------------------------+-----------------------------------------------+ | 
|  | 2577 | | ``%(levelno)s``         | Numeric logging level for the message         | | 
|  | 2578 | |                         | (:const:`DEBUG`, :const:`INFO`,               | | 
|  | 2579 | |                         | :const:`WARNING`, :const:`ERROR`,             | | 
|  | 2580 | |                         | :const:`CRITICAL`).                           | | 
|  | 2581 | +-------------------------+-----------------------------------------------+ | 
|  | 2582 | | ``%(levelname)s``       | Text logging level for the message            | | 
|  | 2583 | |                         | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``,      | | 
|  | 2584 | |                         | ``'ERROR'``, ``'CRITICAL'``).                 | | 
|  | 2585 | +-------------------------+-----------------------------------------------+ | 
|  | 2586 | | ``%(pathname)s``        | Full pathname of the source file where the    | | 
|  | 2587 | |                         | logging call was issued (if available).       | | 
|  | 2588 | +-------------------------+-----------------------------------------------+ | 
|  | 2589 | | ``%(filename)s``        | Filename portion of pathname.                 | | 
|  | 2590 | +-------------------------+-----------------------------------------------+ | 
|  | 2591 | | ``%(module)s``          | Module (name portion of filename).            | | 
|  | 2592 | +-------------------------+-----------------------------------------------+ | 
|  | 2593 | | ``%(funcName)s``        | Name of function containing the logging call. | | 
|  | 2594 | +-------------------------+-----------------------------------------------+ | 
|  | 2595 | | ``%(lineno)d``          | Source line number where the logging call was | | 
|  | 2596 | |                         | issued (if available).                        | | 
|  | 2597 | +-------------------------+-----------------------------------------------+ | 
|  | 2598 | | ``%(created)f``         | Time when the :class:`LogRecord` was created  | | 
|  | 2599 | |                         | (as returned by :func:`time.time`).           | | 
|  | 2600 | +-------------------------+-----------------------------------------------+ | 
|  | 2601 | | ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was   | | 
|  | 2602 | |                         | created, relative to the time the logging     | | 
|  | 2603 | |                         | module was loaded.                            | | 
|  | 2604 | +-------------------------+-----------------------------------------------+ | 
|  | 2605 | | ``%(asctime)s``         | Human-readable time when the                  | | 
|  | 2606 | |                         | :class:`LogRecord` was created.  By default   | | 
|  | 2607 | |                         | this is of the form "2003-07-08 16:49:45,896" | | 
|  | 2608 | |                         | (the numbers after the comma are millisecond  | | 
|  | 2609 | |                         | portion of the time).                         | | 
|  | 2610 | +-------------------------+-----------------------------------------------+ | 
|  | 2611 | | ``%(msecs)d``           | Millisecond portion of the time when the      | | 
|  | 2612 | |                         | :class:`LogRecord` was created.               | | 
|  | 2613 | +-------------------------+-----------------------------------------------+ | 
|  | 2614 | | ``%(thread)d``          | Thread ID (if available).                     | | 
|  | 2615 | +-------------------------+-----------------------------------------------+ | 
|  | 2616 | | ``%(threadName)s``      | Thread name (if available).                   | | 
|  | 2617 | +-------------------------+-----------------------------------------------+ | 
|  | 2618 | | ``%(process)d``         | Process ID (if available).                    | | 
|  | 2619 | +-------------------------+-----------------------------------------------+ | 
| Vinay Sajip | fe08e6f | 2010-09-11 10:25:28 +0000 | [diff] [blame] | 2620 | | ``%(processName)s``     | Process name (if available).                  | | 
|  | 2621 | +-------------------------+-----------------------------------------------+ | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2622 | | ``%(message)s``         | The logged message, computed as ``msg %       | | 
|  | 2623 | |                         | args``.                                       | | 
|  | 2624 | +-------------------------+-----------------------------------------------+ | 
|  | 2625 |  | 
|  | 2626 | .. versionchanged:: 2.5 | 
|  | 2627 | *funcName* was added. | 
|  | 2628 |  | 
| Georg Brandl | 9855ddf | 2010-10-17 11:27:00 +0000 | [diff] [blame] | 2629 | .. versionchanged:: 2.6 | 
|  | 2630 | *processName* was added. | 
|  | 2631 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2632 |  | 
|  | 2633 | .. class:: Formatter([fmt[, datefmt]]) | 
|  | 2634 |  | 
|  | 2635 | Returns a new instance of the :class:`Formatter` class. The instance is | 
| Vinay Sajip | fe08e6f | 2010-09-11 10:25:28 +0000 | [diff] [blame] | 2636 | initialized with a format string for the message as a whole, as well as a | 
|  | 2637 | format string for the date/time portion of a message. If no *fmt* is | 
|  | 2638 | specified, ``'%(message)s'`` is used. If no *datefmt* is specified, the | 
|  | 2639 | ISO8601 date format is used. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2640 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2641 | .. method:: format(record) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2642 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2643 | The record's attribute dictionary is used as the operand to a string | 
|  | 2644 | formatting operation. Returns the resulting string. Before formatting the | 
|  | 2645 | dictionary, a couple of preparatory steps are carried out. The *message* | 
|  | 2646 | attribute of the record is computed using *msg* % *args*. If the | 
|  | 2647 | formatting string contains ``'(asctime)'``, :meth:`formatTime` is called | 
|  | 2648 | to format the event time. If there is exception information, it is | 
|  | 2649 | formatted using :meth:`formatException` and appended to the message. Note | 
|  | 2650 | that the formatted exception information is cached in attribute | 
|  | 2651 | *exc_text*. This is useful because the exception information can be | 
|  | 2652 | pickled and sent across the wire, but you should be careful if you have | 
|  | 2653 | more than one :class:`Formatter` subclass which customizes the formatting | 
|  | 2654 | of exception information. In this case, you will have to clear the cached | 
|  | 2655 | value after a formatter has done its formatting, so that the next | 
|  | 2656 | formatter to handle the event doesn't use the cached value but | 
|  | 2657 | recalculates it afresh. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2658 |  | 
|  | 2659 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2660 | .. method:: formatTime(record[, datefmt]) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2661 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2662 | This method should be called from :meth:`format` by a formatter which | 
|  | 2663 | wants to make use of a formatted time. This method can be overridden in | 
|  | 2664 | formatters to provide for any specific requirement, but the basic behavior | 
|  | 2665 | is as follows: if *datefmt* (a string) is specified, it is used with | 
|  | 2666 | :func:`time.strftime` to format the creation time of the | 
|  | 2667 | record. Otherwise, the ISO8601 format is used.  The resulting string is | 
|  | 2668 | returned. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2669 |  | 
|  | 2670 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2671 | .. method:: formatException(exc_info) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2672 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2673 | Formats the specified exception information (a standard exception tuple as | 
|  | 2674 | returned by :func:`sys.exc_info`) as a string. This default implementation | 
|  | 2675 | just uses :func:`traceback.print_exception`. The resulting string is | 
|  | 2676 | returned. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2677 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 2678 | .. _filter: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2679 |  | 
|  | 2680 | Filter Objects | 
|  | 2681 | -------------- | 
|  | 2682 |  | 
| Vinay Sajip | fb7b505 | 2010-09-17 12:45:26 +0000 | [diff] [blame] | 2683 | :class:`Filter`\ s can be used by :class:`Handler`\ s and :class:`Logger`\ s for | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2684 | more sophisticated filtering than is provided by levels. The base filter class | 
|  | 2685 | only allows events which are below a certain point in the logger hierarchy. For | 
|  | 2686 | example, a filter initialized with "A.B" will allow events logged by loggers | 
|  | 2687 | "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If | 
|  | 2688 | initialized with the empty string, all events are passed. | 
|  | 2689 |  | 
|  | 2690 |  | 
|  | 2691 | .. class:: Filter([name]) | 
|  | 2692 |  | 
|  | 2693 | Returns an instance of the :class:`Filter` class. If *name* is specified, it | 
|  | 2694 | names a logger which, together with its children, will have its events allowed | 
| Vinay Sajip | fe08e6f | 2010-09-11 10:25:28 +0000 | [diff] [blame] | 2695 | through the filter. If *name* is the empty string, allows every event. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2696 |  | 
|  | 2697 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2698 | .. method:: filter(record) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2699 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2700 | Is the specified record to be logged? Returns zero for no, nonzero for | 
|  | 2701 | yes. If deemed appropriate, the record may be modified in-place by this | 
|  | 2702 | method. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2703 |  | 
| Vinay Sajip | 3478ac0 | 2010-08-19 19:17:41 +0000 | [diff] [blame] | 2704 | Note that filters attached to handlers are consulted whenever an event is | 
|  | 2705 | emitted by the handler, whereas filters attached to loggers are consulted | 
|  | 2706 | whenever an event is logged to the handler (using :meth:`debug`, :meth:`info`, | 
|  | 2707 | etc.) This means that events which have been generated by descendant loggers | 
|  | 2708 | will not be filtered by a logger's filter setting, unless the filter has also | 
|  | 2709 | been applied to those descendant loggers. | 
|  | 2710 |  | 
| Vinay Sajip | 7fc3824 | 2010-10-20 11:40:02 +0000 | [diff] [blame^] | 2711 | You don't actually need to subclass ``Filter``: you can pass any instance | 
|  | 2712 | which has a ``filter`` method with the same semantics. | 
|  | 2713 |  | 
| Vinay Sajip | fb7b505 | 2010-09-17 12:45:26 +0000 | [diff] [blame] | 2714 | Other uses for filters | 
|  | 2715 | ^^^^^^^^^^^^^^^^^^^^^^ | 
|  | 2716 |  | 
|  | 2717 | Although filters are used primarily to filter records based on more | 
|  | 2718 | sophisticated criteria than levels, they get to see every record which is | 
|  | 2719 | processed by the handler or logger they're attached to: this can be useful if | 
|  | 2720 | you want to do things like counting how many records were processed by a | 
|  | 2721 | particular logger or handler, or adding, changing or removing attributes in | 
|  | 2722 | the LogRecord being processed. Obviously changing the LogRecord needs to be | 
|  | 2723 | done with some care, but it does allow the injection of contextual information | 
|  | 2724 | into logs (see :ref:`filters-contextual`). | 
|  | 2725 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 2726 | .. _log-record: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2727 |  | 
|  | 2728 | LogRecord Objects | 
|  | 2729 | ----------------- | 
|  | 2730 |  | 
| Vinay Sajip | fe08e6f | 2010-09-11 10:25:28 +0000 | [diff] [blame] | 2731 | :class:`LogRecord` instances are created automatically by the :class:`Logger` | 
|  | 2732 | every time something is logged, and can be created manually via | 
|  | 2733 | :func:`makeLogRecord` (for example, from a pickled event received over the | 
|  | 2734 | wire). | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2735 |  | 
|  | 2736 |  | 
| Vinay Sajip | fe08e6f | 2010-09-11 10:25:28 +0000 | [diff] [blame] | 2737 | .. class:: | 
|  | 2738 | LogRecord(name, lvl, pathname, lineno, msg, args, exc_info [, func=None]) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2739 |  | 
| Vinay Sajip | fe08e6f | 2010-09-11 10:25:28 +0000 | [diff] [blame] | 2740 | Contains all the information pertinent to the event being logged. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2741 |  | 
| Vinay Sajip | fe08e6f | 2010-09-11 10:25:28 +0000 | [diff] [blame] | 2742 | The primary information is passed in :attr:`msg` and :attr:`args`, which | 
|  | 2743 | are combined using ``msg % args`` to create the :attr:`message` field of the | 
|  | 2744 | record. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2745 |  | 
| Vinay Sajip | fe08e6f | 2010-09-11 10:25:28 +0000 | [diff] [blame] | 2746 | .. attribute:: args | 
|  | 2747 |  | 
|  | 2748 | Tuple of arguments to be used in formatting :attr:`msg`. | 
|  | 2749 |  | 
|  | 2750 | .. attribute:: exc_info | 
|  | 2751 |  | 
|  | 2752 | Exception tuple (à la `sys.exc_info`) or `None` if no exception | 
| Georg Brandl | 0930228 | 2010-10-06 09:32:48 +0000 | [diff] [blame] | 2753 | information is available. | 
| Vinay Sajip | fe08e6f | 2010-09-11 10:25:28 +0000 | [diff] [blame] | 2754 |  | 
|  | 2755 | .. attribute:: func | 
|  | 2756 |  | 
|  | 2757 | Name of the function of origin (i.e. in which the logging call was made). | 
|  | 2758 |  | 
|  | 2759 | .. attribute:: lineno | 
|  | 2760 |  | 
|  | 2761 | Line number in the source file of origin. | 
|  | 2762 |  | 
|  | 2763 | .. attribute:: lvl | 
|  | 2764 |  | 
|  | 2765 | Numeric logging level. | 
|  | 2766 |  | 
|  | 2767 | .. attribute:: message | 
|  | 2768 |  | 
|  | 2769 | Bound to the result of :meth:`getMessage` when | 
|  | 2770 | :meth:`Formatter.format(record)<Formatter.format>` is invoked. | 
|  | 2771 |  | 
|  | 2772 | .. attribute:: msg | 
|  | 2773 |  | 
|  | 2774 | User-supplied :ref:`format string<string-formatting>` or arbitrary object | 
|  | 2775 | (see :ref:`arbitrary-object-messages`) used in :meth:`getMessage`. | 
|  | 2776 |  | 
|  | 2777 | .. attribute:: name | 
|  | 2778 |  | 
|  | 2779 | Name of the logger that emitted the record. | 
|  | 2780 |  | 
|  | 2781 | .. attribute:: pathname | 
|  | 2782 |  | 
|  | 2783 | Absolute pathname of the source file of origin. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2784 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2785 | .. method:: getMessage() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2786 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2787 | Returns the message for this :class:`LogRecord` instance after merging any | 
| Vinay Sajip | fe08e6f | 2010-09-11 10:25:28 +0000 | [diff] [blame] | 2788 | user-supplied arguments with the message. If the user-supplied message | 
|  | 2789 | argument to the logging call is not a string, :func:`str` is called on it to | 
|  | 2790 | convert it to a string. This allows use of user-defined classes as | 
|  | 2791 | messages, whose ``__str__`` method can return the actual format string to | 
|  | 2792 | be used. | 
|  | 2793 |  | 
|  | 2794 | .. versionchanged:: 2.5 | 
|  | 2795 | *func* was added. | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2796 |  | 
| Vinay Sajip | 4b78233 | 2009-01-19 06:49:19 +0000 | [diff] [blame] | 2797 | .. _logger-adapter: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2798 |  | 
| Vinay Sajip | c740335 | 2008-01-18 15:54:14 +0000 | [diff] [blame] | 2799 | LoggerAdapter Objects | 
|  | 2800 | --------------------- | 
|  | 2801 |  | 
|  | 2802 | .. versionadded:: 2.6 | 
|  | 2803 |  | 
|  | 2804 | :class:`LoggerAdapter` instances are used to conveniently pass contextual | 
| Vinay Sajip | 733024a | 2008-01-21 17:39:22 +0000 | [diff] [blame] | 2805 | information into logging calls. For a usage example , see the section on | 
|  | 2806 | `adding contextual information to your logging output`__. | 
|  | 2807 |  | 
|  | 2808 | __ context-info_ | 
| Vinay Sajip | c740335 | 2008-01-18 15:54:14 +0000 | [diff] [blame] | 2809 |  | 
|  | 2810 | .. class:: LoggerAdapter(logger, extra) | 
|  | 2811 |  | 
|  | 2812 | Returns an instance of :class:`LoggerAdapter` initialized with an | 
|  | 2813 | underlying :class:`Logger` instance and a dict-like object. | 
|  | 2814 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2815 | .. method:: process(msg, kwargs) | 
| Vinay Sajip | c740335 | 2008-01-18 15:54:14 +0000 | [diff] [blame] | 2816 |  | 
| Benjamin Peterson | c7b0592 | 2008-04-25 01:29:10 +0000 | [diff] [blame] | 2817 | Modifies the message and/or keyword arguments passed to a logging call in | 
|  | 2818 | order to insert contextual information. This implementation takes the object | 
|  | 2819 | passed as *extra* to the constructor and adds it to *kwargs* using key | 
|  | 2820 | 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the | 
|  | 2821 | (possibly modified) versions of the arguments passed in. | 
| Vinay Sajip | c740335 | 2008-01-18 15:54:14 +0000 | [diff] [blame] | 2822 |  | 
|  | 2823 | In addition to the above, :class:`LoggerAdapter` supports all the logging | 
|  | 2824 | methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`, | 
|  | 2825 | :meth:`error`, :meth:`exception`, :meth:`critical` and :meth:`log`. These | 
|  | 2826 | methods have the same signatures as their counterparts in :class:`Logger`, so | 
|  | 2827 | you can use the two types of instances interchangeably. | 
|  | 2828 |  | 
| Vinay Sajip | 804899b | 2010-03-22 15:29:01 +0000 | [diff] [blame] | 2829 | .. versionchanged:: 2.7 | 
|  | 2830 |  | 
|  | 2831 | The :meth:`isEnabledFor` method was added to :class:`LoggerAdapter`. This method | 
|  | 2832 | delegates to the underlying logger. | 
|  | 2833 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2834 |  | 
|  | 2835 | Thread Safety | 
|  | 2836 | ------------- | 
|  | 2837 |  | 
|  | 2838 | The logging module is intended to be thread-safe without any special work | 
|  | 2839 | needing to be done by its clients. It achieves this though using threading | 
|  | 2840 | locks; there is one lock to serialize access to the module's shared data, and | 
|  | 2841 | each handler also creates a lock to serialize access to its underlying I/O. | 
|  | 2842 |  | 
| Vinay Sajip | 353a85f | 2009-04-03 21:58:16 +0000 | [diff] [blame] | 2843 | If you are implementing asynchronous signal handlers using the :mod:`signal` | 
|  | 2844 | module, you may not be able to use logging from within such handlers. This is | 
|  | 2845 | because lock implementations in the :mod:`threading` module are not always | 
|  | 2846 | re-entrant, and so cannot be invoked from such signal handlers. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2847 |  | 
| Vinay Sajip | 61afd26 | 2010-02-19 23:53:17 +0000 | [diff] [blame] | 2848 |  | 
|  | 2849 | Integration with the warnings module | 
|  | 2850 | ------------------------------------ | 
|  | 2851 |  | 
|  | 2852 | The :func:`captureWarnings` function can be used to integrate :mod:`logging` | 
|  | 2853 | with the :mod:`warnings` module. | 
|  | 2854 |  | 
|  | 2855 | .. function:: captureWarnings(capture) | 
|  | 2856 |  | 
|  | 2857 | This function is used to turn the capture of warnings by logging on and | 
|  | 2858 | off. | 
|  | 2859 |  | 
| Georg Brandl | f6d36745 | 2010-03-12 10:02:03 +0000 | [diff] [blame] | 2860 | If *capture* is ``True``, warnings issued by the :mod:`warnings` module | 
| Vinay Sajip | 61afd26 | 2010-02-19 23:53:17 +0000 | [diff] [blame] | 2861 | will be redirected to the logging system. Specifically, a warning will be | 
|  | 2862 | formatted using :func:`warnings.formatwarning` and the resulting string | 
| Georg Brandl | f6d36745 | 2010-03-12 10:02:03 +0000 | [diff] [blame] | 2863 | logged to a logger named "py.warnings" with a severity of ``WARNING``. | 
| Vinay Sajip | 61afd26 | 2010-02-19 23:53:17 +0000 | [diff] [blame] | 2864 |  | 
| Georg Brandl | f6d36745 | 2010-03-12 10:02:03 +0000 | [diff] [blame] | 2865 | If *capture* is ``False``, the redirection of warnings to the logging system | 
| Vinay Sajip | 61afd26 | 2010-02-19 23:53:17 +0000 | [diff] [blame] | 2866 | will stop, and warnings will be redirected to their original destinations | 
| Georg Brandl | f6d36745 | 2010-03-12 10:02:03 +0000 | [diff] [blame] | 2867 | (i.e. those in effect before ``captureWarnings(True)`` was called). | 
| Vinay Sajip | 61afd26 | 2010-02-19 23:53:17 +0000 | [diff] [blame] | 2868 |  | 
|  | 2869 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2870 | Configuration | 
|  | 2871 | ------------- | 
|  | 2872 |  | 
|  | 2873 |  | 
|  | 2874 | .. _logging-config-api: | 
|  | 2875 |  | 
|  | 2876 | Configuration functions | 
|  | 2877 | ^^^^^^^^^^^^^^^^^^^^^^^ | 
|  | 2878 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2879 | The following functions configure the logging module. They are located in the | 
|  | 2880 | :mod:`logging.config` module.  Their use is optional --- you can configure the | 
|  | 2881 | logging module using these functions or by making calls to the main API (defined | 
|  | 2882 | in :mod:`logging` itself) and defining handlers which are declared either in | 
|  | 2883 | :mod:`logging` or :mod:`logging.handlers`. | 
|  | 2884 |  | 
| Andrew M. Kuchling | f09bc66 | 2010-05-12 18:56:48 +0000 | [diff] [blame] | 2885 | .. function:: dictConfig(config) | 
|  | 2886 |  | 
|  | 2887 | Takes the logging configuration from a dictionary.  The contents of | 
|  | 2888 | this dictionary are described in :ref:`logging-config-dictschema` | 
|  | 2889 | below. | 
|  | 2890 |  | 
|  | 2891 | If an error is encountered during configuration, this function will | 
|  | 2892 | raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError` | 
|  | 2893 | or :exc:`ImportError` with a suitably descriptive message.  The | 
|  | 2894 | following is a (possibly incomplete) list of conditions which will | 
|  | 2895 | raise an error: | 
|  | 2896 |  | 
|  | 2897 | * A ``level`` which is not a string or which is a string not | 
|  | 2898 | corresponding to an actual logging level. | 
|  | 2899 | * A ``propagate`` value which is not a boolean. | 
|  | 2900 | * An id which does not have a corresponding destination. | 
|  | 2901 | * A non-existent handler id found during an incremental call. | 
|  | 2902 | * An invalid logger name. | 
|  | 2903 | * Inability to resolve to an internal or external object. | 
|  | 2904 |  | 
|  | 2905 | Parsing is performed by the :class:`DictConfigurator` class, whose | 
|  | 2906 | constructor is passed the dictionary used for configuration, and | 
|  | 2907 | has a :meth:`configure` method.  The :mod:`logging.config` module | 
|  | 2908 | has a callable attribute :attr:`dictConfigClass` | 
|  | 2909 | which is initially set to :class:`DictConfigurator`. | 
|  | 2910 | You can replace the value of :attr:`dictConfigClass` with a | 
|  | 2911 | suitable implementation of your own. | 
|  | 2912 |  | 
|  | 2913 | :func:`dictConfig` calls :attr:`dictConfigClass` passing | 
|  | 2914 | the specified dictionary, and then calls the :meth:`configure` method on | 
|  | 2915 | the returned object to put the configuration into effect:: | 
|  | 2916 |  | 
|  | 2917 | def dictConfig(config): | 
|  | 2918 | dictConfigClass(config).configure() | 
|  | 2919 |  | 
|  | 2920 | For example, a subclass of :class:`DictConfigurator` could call | 
|  | 2921 | ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then | 
|  | 2922 | set up custom prefixes which would be usable in the subsequent | 
|  | 2923 | :meth:`configure` call. :attr:`dictConfigClass` would be bound to | 
|  | 2924 | this new subclass, and then :func:`dictConfig` could be called exactly as | 
|  | 2925 | in the default, uncustomized state. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2926 |  | 
|  | 2927 | .. function:: fileConfig(fname[, defaults]) | 
|  | 2928 |  | 
| Vinay Sajip | 5110486 | 2009-01-02 18:53:04 +0000 | [diff] [blame] | 2929 | Reads the logging configuration from a :mod:`ConfigParser`\-format file named | 
|  | 2930 | *fname*. This function can be called several times from an application, | 
| Andrew M. Kuchling | f09bc66 | 2010-05-12 18:56:48 +0000 | [diff] [blame] | 2931 | allowing an end user to select from various pre-canned | 
| Vinay Sajip | 5110486 | 2009-01-02 18:53:04 +0000 | [diff] [blame] | 2932 | configurations (if the developer provides a mechanism to present the choices | 
|  | 2933 | and load the chosen configuration). Defaults to be passed to the ConfigParser | 
|  | 2934 | can be specified in the *defaults* argument. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2935 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2936 | .. function:: listen([port]) | 
|  | 2937 |  | 
|  | 2938 | Starts up a socket server on the specified port, and listens for new | 
|  | 2939 | configurations. If no port is specified, the module's default | 
|  | 2940 | :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be | 
|  | 2941 | sent as a file suitable for processing by :func:`fileConfig`. Returns a | 
|  | 2942 | :class:`Thread` instance on which you can call :meth:`start` to start the | 
|  | 2943 | server, and which you can :meth:`join` when appropriate. To stop the server, | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 2944 | call :func:`stopListening`. | 
|  | 2945 |  | 
|  | 2946 | To send a configuration to the socket, read in the configuration file and | 
|  | 2947 | send it to the socket as a string of bytes preceded by a four-byte length | 
|  | 2948 | string packed in binary using ``struct.pack('>L', n)``. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2949 |  | 
|  | 2950 |  | 
|  | 2951 | .. function:: stopListening() | 
|  | 2952 |  | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 2953 | Stops the listening server which was created with a call to :func:`listen`. | 
|  | 2954 | This is typically called before calling :meth:`join` on the return value from | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2955 | :func:`listen`. | 
|  | 2956 |  | 
|  | 2957 |  | 
| Andrew M. Kuchling | f09bc66 | 2010-05-12 18:56:48 +0000 | [diff] [blame] | 2958 | .. _logging-config-dictschema: | 
|  | 2959 |  | 
|  | 2960 | Configuration dictionary schema | 
|  | 2961 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | 
|  | 2962 |  | 
|  | 2963 | Describing a logging configuration requires listing the various | 
|  | 2964 | objects to create and the connections between them; for example, you | 
|  | 2965 | may create a handler named "console" and then say that the logger | 
|  | 2966 | named "startup" will send its messages to the "console" handler. | 
|  | 2967 | These objects aren't limited to those provided by the :mod:`logging` | 
|  | 2968 | module because you might write your own formatter or handler class. | 
|  | 2969 | The parameters to these classes may also need to include external | 
|  | 2970 | objects such as ``sys.stderr``.  The syntax for describing these | 
|  | 2971 | objects and connections is defined in :ref:`logging-config-dict-connections` | 
|  | 2972 | below. | 
|  | 2973 |  | 
|  | 2974 | Dictionary Schema Details | 
|  | 2975 | """"""""""""""""""""""""" | 
|  | 2976 |  | 
|  | 2977 | The dictionary passed to :func:`dictConfig` must contain the following | 
|  | 2978 | keys: | 
|  | 2979 |  | 
|  | 2980 | * `version` - to be set to an integer value representing the schema | 
|  | 2981 | version.  The only valid value at present is 1, but having this key | 
|  | 2982 | allows the schema to evolve while still preserving backwards | 
|  | 2983 | compatibility. | 
|  | 2984 |  | 
|  | 2985 | All other keys are optional, but if present they will be interpreted | 
|  | 2986 | as described below.  In all cases below where a 'configuring dict' is | 
|  | 2987 | mentioned, it will be checked for the special ``'()'`` key to see if a | 
| Andrew M. Kuchling | 1b55347 | 2010-05-16 23:31:16 +0000 | [diff] [blame] | 2988 | custom instantiation is required.  If so, the mechanism described in | 
|  | 2989 | :ref:`logging-config-dict-userdef` below is used to create an instance; | 
|  | 2990 | otherwise, the context is used to determine what to instantiate. | 
| Andrew M. Kuchling | f09bc66 | 2010-05-12 18:56:48 +0000 | [diff] [blame] | 2991 |  | 
|  | 2992 | * `formatters` - the corresponding value will be a dict in which each | 
|  | 2993 | key is a formatter id and each value is a dict describing how to | 
|  | 2994 | configure the corresponding Formatter instance. | 
|  | 2995 |  | 
|  | 2996 | The configuring dict is searched for keys ``format`` and ``datefmt`` | 
|  | 2997 | (with defaults of ``None``) and these are used to construct a | 
|  | 2998 | :class:`logging.Formatter` instance. | 
|  | 2999 |  | 
|  | 3000 | * `filters` - the corresponding value will be a dict in which each key | 
|  | 3001 | is a filter id and each value is a dict describing how to configure | 
|  | 3002 | the corresponding Filter instance. | 
|  | 3003 |  | 
|  | 3004 | The configuring dict is searched for the key ``name`` (defaulting to the | 
|  | 3005 | empty string) and this is used to construct a :class:`logging.Filter` | 
|  | 3006 | instance. | 
|  | 3007 |  | 
|  | 3008 | * `handlers` - the corresponding value will be a dict in which each | 
|  | 3009 | key is a handler id and each value is a dict describing how to | 
|  | 3010 | configure the corresponding Handler instance. | 
|  | 3011 |  | 
|  | 3012 | The configuring dict is searched for the following keys: | 
|  | 3013 |  | 
|  | 3014 | * ``class`` (mandatory).  This is the fully qualified name of the | 
|  | 3015 | handler class. | 
|  | 3016 |  | 
|  | 3017 | * ``level`` (optional).  The level of the handler. | 
|  | 3018 |  | 
|  | 3019 | * ``formatter`` (optional).  The id of the formatter for this | 
|  | 3020 | handler. | 
|  | 3021 |  | 
|  | 3022 | * ``filters`` (optional).  A list of ids of the filters for this | 
|  | 3023 | handler. | 
|  | 3024 |  | 
|  | 3025 | All *other* keys are passed through as keyword arguments to the | 
|  | 3026 | handler's constructor.  For example, given the snippet:: | 
|  | 3027 |  | 
|  | 3028 | handlers: | 
|  | 3029 | console: | 
|  | 3030 | class : logging.StreamHandler | 
|  | 3031 | formatter: brief | 
|  | 3032 | level   : INFO | 
|  | 3033 | filters: [allow_foo] | 
|  | 3034 | stream  : ext://sys.stdout | 
|  | 3035 | file: | 
|  | 3036 | class : logging.handlers.RotatingFileHandler | 
|  | 3037 | formatter: precise | 
|  | 3038 | filename: logconfig.log | 
|  | 3039 | maxBytes: 1024 | 
|  | 3040 | backupCount: 3 | 
|  | 3041 |  | 
|  | 3042 | the handler with id ``console`` is instantiated as a | 
|  | 3043 | :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying | 
|  | 3044 | stream.  The handler with id ``file`` is instantiated as a | 
|  | 3045 | :class:`logging.handlers.RotatingFileHandler` with the keyword arguments | 
|  | 3046 | ``filename='logconfig.log', maxBytes=1024, backupCount=3``. | 
|  | 3047 |  | 
|  | 3048 | * `loggers` - the corresponding value will be a dict in which each key | 
|  | 3049 | is a logger name and each value is a dict describing how to | 
|  | 3050 | configure the corresponding Logger instance. | 
|  | 3051 |  | 
|  | 3052 | The configuring dict is searched for the following keys: | 
|  | 3053 |  | 
|  | 3054 | * ``level`` (optional).  The level of the logger. | 
|  | 3055 |  | 
|  | 3056 | * ``propagate`` (optional).  The propagation setting of the logger. | 
|  | 3057 |  | 
|  | 3058 | * ``filters`` (optional).  A list of ids of the filters for this | 
|  | 3059 | logger. | 
|  | 3060 |  | 
|  | 3061 | * ``handlers`` (optional).  A list of ids of the handlers for this | 
|  | 3062 | logger. | 
|  | 3063 |  | 
|  | 3064 | The specified loggers will be configured according to the level, | 
|  | 3065 | propagation, filters and handlers specified. | 
|  | 3066 |  | 
|  | 3067 | * `root` - this will be the configuration for the root logger. | 
|  | 3068 | Processing of the configuration will be as for any logger, except | 
|  | 3069 | that the ``propagate`` setting will not be applicable. | 
|  | 3070 |  | 
|  | 3071 | * `incremental` - whether the configuration is to be interpreted as | 
|  | 3072 | incremental to the existing configuration.  This value defaults to | 
|  | 3073 | ``False``, which means that the specified configuration replaces the | 
|  | 3074 | existing configuration with the same semantics as used by the | 
|  | 3075 | existing :func:`fileConfig` API. | 
|  | 3076 |  | 
|  | 3077 | If the specified value is ``True``, the configuration is processed | 
|  | 3078 | as described in the section on :ref:`logging-config-dict-incremental`. | 
|  | 3079 |  | 
|  | 3080 | * `disable_existing_loggers` - whether any existing loggers are to be | 
|  | 3081 | disabled. This setting mirrors the parameter of the same name in | 
|  | 3082 | :func:`fileConfig`. If absent, this parameter defaults to ``True``. | 
|  | 3083 | This value is ignored if `incremental` is ``True``. | 
|  | 3084 |  | 
|  | 3085 | .. _logging-config-dict-incremental: | 
|  | 3086 |  | 
|  | 3087 | Incremental Configuration | 
|  | 3088 | """"""""""""""""""""""""" | 
|  | 3089 |  | 
|  | 3090 | It is difficult to provide complete flexibility for incremental | 
|  | 3091 | configuration.  For example, because objects such as filters | 
|  | 3092 | and formatters are anonymous, once a configuration is set up, it is | 
|  | 3093 | not possible to refer to such anonymous objects when augmenting a | 
|  | 3094 | configuration. | 
|  | 3095 |  | 
|  | 3096 | Furthermore, there is not a compelling case for arbitrarily altering | 
|  | 3097 | the object graph of loggers, handlers, filters, formatters at | 
|  | 3098 | run-time, once a configuration is set up; the verbosity of loggers and | 
|  | 3099 | handlers can be controlled just by setting levels (and, in the case of | 
|  | 3100 | loggers, propagation flags).  Changing the object graph arbitrarily in | 
|  | 3101 | a safe way is problematic in a multi-threaded environment; while not | 
|  | 3102 | impossible, the benefits are not worth the complexity it adds to the | 
|  | 3103 | implementation. | 
|  | 3104 |  | 
|  | 3105 | Thus, when the ``incremental`` key of a configuration dict is present | 
|  | 3106 | and is ``True``, the system will completely ignore any ``formatters`` and | 
|  | 3107 | ``filters`` entries, and process only the ``level`` | 
|  | 3108 | settings in the ``handlers`` entries, and the ``level`` and | 
|  | 3109 | ``propagate`` settings in the ``loggers`` and ``root`` entries. | 
|  | 3110 |  | 
|  | 3111 | Using a value in the configuration dict lets configurations to be sent | 
|  | 3112 | over the wire as pickled dicts to a socket listener. Thus, the logging | 
|  | 3113 | verbosity of a long-running application can be altered over time with | 
|  | 3114 | no need to stop and restart the application. | 
|  | 3115 |  | 
|  | 3116 | .. _logging-config-dict-connections: | 
|  | 3117 |  | 
|  | 3118 | Object connections | 
|  | 3119 | """""""""""""""""" | 
|  | 3120 |  | 
|  | 3121 | The schema describes a set of logging objects - loggers, | 
|  | 3122 | handlers, formatters, filters - which are connected to each other in | 
|  | 3123 | an object graph.  Thus, the schema needs to represent connections | 
|  | 3124 | between the objects.  For example, say that, once configured, a | 
|  | 3125 | particular logger has attached to it a particular handler.  For the | 
|  | 3126 | purposes of this discussion, we can say that the logger represents the | 
|  | 3127 | source, and the handler the destination, of a connection between the | 
|  | 3128 | two.  Of course in the configured objects this is represented by the | 
|  | 3129 | logger holding a reference to the handler.  In the configuration dict, | 
|  | 3130 | this is done by giving each destination object an id which identifies | 
|  | 3131 | it unambiguously, and then using the id in the source object's | 
|  | 3132 | configuration to indicate that a connection exists between the source | 
|  | 3133 | and the destination object with that id. | 
|  | 3134 |  | 
|  | 3135 | So, for example, consider the following YAML snippet:: | 
|  | 3136 |  | 
|  | 3137 | formatters: | 
|  | 3138 | brief: | 
|  | 3139 | # configuration for formatter with id 'brief' goes here | 
|  | 3140 | precise: | 
|  | 3141 | # configuration for formatter with id 'precise' goes here | 
|  | 3142 | handlers: | 
|  | 3143 | h1: #This is an id | 
|  | 3144 | # configuration of handler with id 'h1' goes here | 
|  | 3145 | formatter: brief | 
|  | 3146 | h2: #This is another id | 
|  | 3147 | # configuration of handler with id 'h2' goes here | 
|  | 3148 | formatter: precise | 
|  | 3149 | loggers: | 
|  | 3150 | foo.bar.baz: | 
|  | 3151 | # other configuration for logger 'foo.bar.baz' | 
|  | 3152 | handlers: [h1, h2] | 
|  | 3153 |  | 
|  | 3154 | (Note: YAML used here because it's a little more readable than the | 
|  | 3155 | equivalent Python source form for the dictionary.) | 
|  | 3156 |  | 
|  | 3157 | The ids for loggers are the logger names which would be used | 
|  | 3158 | programmatically to obtain a reference to those loggers, e.g. | 
|  | 3159 | ``foo.bar.baz``.  The ids for Formatters and Filters can be any string | 
|  | 3160 | value (such as ``brief``, ``precise`` above) and they are transient, | 
|  | 3161 | in that they are only meaningful for processing the configuration | 
|  | 3162 | dictionary and used to determine connections between objects, and are | 
|  | 3163 | not persisted anywhere when the configuration call is complete. | 
|  | 3164 |  | 
|  | 3165 | The above snippet indicates that logger named ``foo.bar.baz`` should | 
|  | 3166 | have two handlers attached to it, which are described by the handler | 
|  | 3167 | ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id | 
|  | 3168 | ``brief``, and the formatter for ``h2`` is that described by id | 
|  | 3169 | ``precise``. | 
|  | 3170 |  | 
|  | 3171 |  | 
|  | 3172 | .. _logging-config-dict-userdef: | 
|  | 3173 |  | 
|  | 3174 | User-defined objects | 
|  | 3175 | """""""""""""""""""" | 
|  | 3176 |  | 
|  | 3177 | The schema supports user-defined objects for handlers, filters and | 
|  | 3178 | formatters.  (Loggers do not need to have different types for | 
|  | 3179 | different instances, so there is no support in this configuration | 
|  | 3180 | schema for user-defined logger classes.) | 
|  | 3181 |  | 
|  | 3182 | Objects to be configured are described by dictionaries | 
|  | 3183 | which detail their configuration.  In some places, the logging system | 
|  | 3184 | will be able to infer from the context how an object is to be | 
|  | 3185 | instantiated, but when a user-defined object is to be instantiated, | 
|  | 3186 | the system will not know how to do this.  In order to provide complete | 
|  | 3187 | flexibility for user-defined object instantiation, the user needs | 
|  | 3188 | to provide a 'factory' - a callable which is called with a | 
|  | 3189 | configuration dictionary and which returns the instantiated object. | 
|  | 3190 | This is signalled by an absolute import path to the factory being | 
|  | 3191 | made available under the special key ``'()'``.  Here's a concrete | 
|  | 3192 | example:: | 
|  | 3193 |  | 
|  | 3194 | formatters: | 
|  | 3195 | brief: | 
|  | 3196 | format: '%(message)s' | 
|  | 3197 | default: | 
|  | 3198 | format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s' | 
|  | 3199 | datefmt: '%Y-%m-%d %H:%M:%S' | 
|  | 3200 | custom: | 
|  | 3201 | (): my.package.customFormatterFactory | 
|  | 3202 | bar: baz | 
|  | 3203 | spam: 99.9 | 
|  | 3204 | answer: 42 | 
|  | 3205 |  | 
|  | 3206 | The above YAML snippet defines three formatters.  The first, with id | 
|  | 3207 | ``brief``, is a standard :class:`logging.Formatter` instance with the | 
|  | 3208 | specified format string.  The second, with id ``default``, has a | 
|  | 3209 | longer format and also defines the time format explicitly, and will | 
|  | 3210 | result in a :class:`logging.Formatter` initialized with those two format | 
|  | 3211 | strings.  Shown in Python source form, the ``brief`` and ``default`` | 
|  | 3212 | formatters have configuration sub-dictionaries:: | 
|  | 3213 |  | 
|  | 3214 | { | 
|  | 3215 | 'format' : '%(message)s' | 
|  | 3216 | } | 
|  | 3217 |  | 
|  | 3218 | and:: | 
|  | 3219 |  | 
|  | 3220 | { | 
|  | 3221 | 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s', | 
|  | 3222 | 'datefmt' : '%Y-%m-%d %H:%M:%S' | 
|  | 3223 | } | 
|  | 3224 |  | 
|  | 3225 | respectively, and as these dictionaries do not contain the special key | 
|  | 3226 | ``'()'``, the instantiation is inferred from the context: as a result, | 
|  | 3227 | standard :class:`logging.Formatter` instances are created.  The | 
|  | 3228 | configuration sub-dictionary for the third formatter, with id | 
|  | 3229 | ``custom``, is:: | 
|  | 3230 |  | 
|  | 3231 | { | 
|  | 3232 | '()' : 'my.package.customFormatterFactory', | 
|  | 3233 | 'bar' : 'baz', | 
|  | 3234 | 'spam' : 99.9, | 
|  | 3235 | 'answer' : 42 | 
|  | 3236 | } | 
|  | 3237 |  | 
|  | 3238 | and this contains the special key ``'()'``, which means that | 
|  | 3239 | user-defined instantiation is wanted.  In this case, the specified | 
|  | 3240 | factory callable will be used. If it is an actual callable it will be | 
|  | 3241 | used directly - otherwise, if you specify a string (as in the example) | 
|  | 3242 | the actual callable will be located using normal import mechanisms. | 
|  | 3243 | The callable will be called with the **remaining** items in the | 
|  | 3244 | configuration sub-dictionary as keyword arguments.  In the above | 
|  | 3245 | example, the formatter with id ``custom`` will be assumed to be | 
|  | 3246 | returned by the call:: | 
|  | 3247 |  | 
|  | 3248 | my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42) | 
|  | 3249 |  | 
|  | 3250 | The key ``'()'`` has been used as the special key because it is not a | 
|  | 3251 | valid keyword parameter name, and so will not clash with the names of | 
|  | 3252 | the keyword arguments used in the call.  The ``'()'`` also serves as a | 
|  | 3253 | mnemonic that the corresponding value is a callable. | 
|  | 3254 |  | 
|  | 3255 |  | 
|  | 3256 | .. _logging-config-dict-externalobj: | 
|  | 3257 |  | 
|  | 3258 | Access to external objects | 
|  | 3259 | """""""""""""""""""""""""" | 
|  | 3260 |  | 
|  | 3261 | There are times where a configuration needs to refer to objects | 
|  | 3262 | external to the configuration, for example ``sys.stderr``.  If the | 
|  | 3263 | configuration dict is constructed using Python code, this is | 
|  | 3264 | straightforward, but a problem arises when the configuration is | 
|  | 3265 | provided via a text file (e.g. JSON, YAML).  In a text file, there is | 
|  | 3266 | no standard way to distinguish ``sys.stderr`` from the literal string | 
|  | 3267 | ``'sys.stderr'``.  To facilitate this distinction, the configuration | 
|  | 3268 | system looks for certain special prefixes in string values and | 
|  | 3269 | treat them specially.  For example, if the literal string | 
|  | 3270 | ``'ext://sys.stderr'`` is provided as a value in the configuration, | 
|  | 3271 | then the ``ext://`` will be stripped off and the remainder of the | 
|  | 3272 | value processed using normal import mechanisms. | 
|  | 3273 |  | 
|  | 3274 | The handling of such prefixes is done in a way analogous to protocol | 
|  | 3275 | handling: there is a generic mechanism to look for prefixes which | 
|  | 3276 | match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$`` | 
|  | 3277 | whereby, if the ``prefix`` is recognised, the ``suffix`` is processed | 
|  | 3278 | in a prefix-dependent manner and the result of the processing replaces | 
|  | 3279 | the string value.  If the prefix is not recognised, then the string | 
|  | 3280 | value will be left as-is. | 
|  | 3281 |  | 
|  | 3282 |  | 
|  | 3283 | .. _logging-config-dict-internalobj: | 
|  | 3284 |  | 
|  | 3285 | Access to internal objects | 
|  | 3286 | """""""""""""""""""""""""" | 
|  | 3287 |  | 
|  | 3288 | As well as external objects, there is sometimes also a need to refer | 
|  | 3289 | to objects in the configuration.  This will be done implicitly by the | 
|  | 3290 | configuration system for things that it knows about.  For example, the | 
|  | 3291 | string value ``'DEBUG'`` for a ``level`` in a logger or handler will | 
|  | 3292 | automatically be converted to the value ``logging.DEBUG``, and the | 
|  | 3293 | ``handlers``, ``filters`` and ``formatter`` entries will take an | 
|  | 3294 | object id and resolve to the appropriate destination object. | 
|  | 3295 |  | 
|  | 3296 | However, a more generic mechanism is needed for user-defined | 
|  | 3297 | objects which are not known to the :mod:`logging` module.  For | 
|  | 3298 | example, consider :class:`logging.handlers.MemoryHandler`, which takes | 
|  | 3299 | a ``target`` argument which is another handler to delegate to. Since | 
|  | 3300 | the system already knows about this class, then in the configuration, | 
|  | 3301 | the given ``target`` just needs to be the object id of the relevant | 
|  | 3302 | target handler, and the system will resolve to the handler from the | 
|  | 3303 | id.  If, however, a user defines a ``my.package.MyHandler`` which has | 
|  | 3304 | an ``alternate`` handler, the configuration system would not know that | 
|  | 3305 | the ``alternate`` referred to a handler.  To cater for this, a generic | 
|  | 3306 | resolution system allows the user to specify:: | 
|  | 3307 |  | 
|  | 3308 | handlers: | 
|  | 3309 | file: | 
|  | 3310 | # configuration of file handler goes here | 
|  | 3311 |  | 
|  | 3312 | custom: | 
|  | 3313 | (): my.package.MyHandler | 
|  | 3314 | alternate: cfg://handlers.file | 
|  | 3315 |  | 
|  | 3316 | The literal string ``'cfg://handlers.file'`` will be resolved in an | 
|  | 3317 | analogous way to strings with the ``ext://`` prefix, but looking | 
|  | 3318 | in the configuration itself rather than the import namespace.  The | 
|  | 3319 | mechanism allows access by dot or by index, in a similar way to | 
|  | 3320 | that provided by ``str.format``.  Thus, given the following snippet:: | 
|  | 3321 |  | 
|  | 3322 | handlers: | 
|  | 3323 | email: | 
|  | 3324 | class: logging.handlers.SMTPHandler | 
|  | 3325 | mailhost: localhost | 
|  | 3326 | fromaddr: my_app@domain.tld | 
|  | 3327 | toaddrs: | 
|  | 3328 | - support_team@domain.tld | 
|  | 3329 | - dev_team@domain.tld | 
|  | 3330 | subject: Houston, we have a problem. | 
|  | 3331 |  | 
|  | 3332 | in the configuration, the string ``'cfg://handlers'`` would resolve to | 
|  | 3333 | the dict with key ``handlers``, the string ``'cfg://handlers.email`` | 
|  | 3334 | would resolve to the dict with key ``email`` in the ``handlers`` dict, | 
|  | 3335 | and so on.  The string ``'cfg://handlers.email.toaddrs[1]`` would | 
|  | 3336 | resolve to ``'dev_team.domain.tld'`` and the string | 
|  | 3337 | ``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value | 
|  | 3338 | ``'support_team@domain.tld'``. The ``subject`` value could be accessed | 
|  | 3339 | using either ``'cfg://handlers.email.subject'`` or, equivalently, | 
|  | 3340 | ``'cfg://handlers.email[subject]'``.  The latter form only needs to be | 
|  | 3341 | used if the key contains spaces or non-alphanumeric characters.  If an | 
|  | 3342 | index value consists only of decimal digits, access will be attempted | 
|  | 3343 | using the corresponding integer value, falling back to the string | 
|  | 3344 | value if needed. | 
|  | 3345 |  | 
|  | 3346 | Given a string ``cfg://handlers.myhandler.mykey.123``, this will | 
|  | 3347 | resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``. | 
|  | 3348 | If the string is specified as ``cfg://handlers.myhandler.mykey[123]``, | 
|  | 3349 | the system will attempt to retrieve the value from | 
|  | 3350 | ``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back | 
|  | 3351 | to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that | 
|  | 3352 | fails. | 
|  | 3353 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 3354 | .. _logging-config-fileformat: | 
|  | 3355 |  | 
|  | 3356 | Configuration file format | 
|  | 3357 | ^^^^^^^^^^^^^^^^^^^^^^^^^ | 
|  | 3358 |  | 
| Georg Brandl | 392c6fc | 2008-05-25 07:25:25 +0000 | [diff] [blame] | 3359 | The configuration file format understood by :func:`fileConfig` is based on | 
| Vinay Sajip | 5110486 | 2009-01-02 18:53:04 +0000 | [diff] [blame] | 3360 | :mod:`ConfigParser` functionality. The file must contain sections called | 
|  | 3361 | ``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the | 
|  | 3362 | entities of each type which are defined in the file. For each such entity, | 
|  | 3363 | there is a separate section which identifies how that entity is configured. | 
|  | 3364 | Thus, for a logger named ``log01`` in the ``[loggers]`` section, the relevant | 
|  | 3365 | configuration details are held in a section ``[logger_log01]``. Similarly, a | 
|  | 3366 | handler called ``hand01`` in the ``[handlers]`` section will have its | 
|  | 3367 | configuration held in a section called ``[handler_hand01]``, while a formatter | 
|  | 3368 | called ``form01`` in the ``[formatters]`` section will have its configuration | 
|  | 3369 | specified in a section called ``[formatter_form01]``. The root logger | 
|  | 3370 | configuration must be specified in a section called ``[logger_root]``. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 3371 |  | 
|  | 3372 | Examples of these sections in the file are given below. :: | 
|  | 3373 |  | 
|  | 3374 | [loggers] | 
|  | 3375 | keys=root,log02,log03,log04,log05,log06,log07 | 
|  | 3376 |  | 
|  | 3377 | [handlers] | 
|  | 3378 | keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09 | 
|  | 3379 |  | 
|  | 3380 | [formatters] | 
|  | 3381 | keys=form01,form02,form03,form04,form05,form06,form07,form08,form09 | 
|  | 3382 |  | 
|  | 3383 | The root logger must specify a level and a list of handlers. An example of a | 
|  | 3384 | root logger section is given below. :: | 
|  | 3385 |  | 
|  | 3386 | [logger_root] | 
|  | 3387 | level=NOTSET | 
|  | 3388 | handlers=hand01 | 
|  | 3389 |  | 
|  | 3390 | The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or | 
|  | 3391 | ``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be | 
|  | 3392 | logged. Level values are :func:`eval`\ uated in the context of the ``logging`` | 
|  | 3393 | package's namespace. | 
|  | 3394 |  | 
|  | 3395 | The ``handlers`` entry is a comma-separated list of handler names, which must | 
|  | 3396 | appear in the ``[handlers]`` section. These names must appear in the | 
|  | 3397 | ``[handlers]`` section and have corresponding sections in the configuration | 
|  | 3398 | file. | 
|  | 3399 |  | 
|  | 3400 | For loggers other than the root logger, some additional information is required. | 
|  | 3401 | This is illustrated by the following example. :: | 
|  | 3402 |  | 
|  | 3403 | [logger_parser] | 
|  | 3404 | level=DEBUG | 
|  | 3405 | handlers=hand01 | 
|  | 3406 | propagate=1 | 
|  | 3407 | qualname=compiler.parser | 
|  | 3408 |  | 
|  | 3409 | The ``level`` and ``handlers`` entries are interpreted as for the root logger, | 
|  | 3410 | except that if a non-root logger's level is specified as ``NOTSET``, the system | 
|  | 3411 | consults loggers higher up the hierarchy to determine the effective level of the | 
|  | 3412 | logger. The ``propagate`` entry is set to 1 to indicate that messages must | 
|  | 3413 | propagate to handlers higher up the logger hierarchy from this logger, or 0 to | 
|  | 3414 | indicate that messages are **not** propagated to handlers up the hierarchy. The | 
|  | 3415 | ``qualname`` entry is the hierarchical channel name of the logger, that is to | 
|  | 3416 | say the name used by the application to get the logger. | 
|  | 3417 |  | 
|  | 3418 | Sections which specify handler configuration are exemplified by the following. | 
|  | 3419 | :: | 
|  | 3420 |  | 
|  | 3421 | [handler_hand01] | 
|  | 3422 | class=StreamHandler | 
|  | 3423 | level=NOTSET | 
|  | 3424 | formatter=form01 | 
|  | 3425 | args=(sys.stdout,) | 
|  | 3426 |  | 
|  | 3427 | The ``class`` entry indicates the handler's class (as determined by :func:`eval` | 
|  | 3428 | in the ``logging`` package's namespace). The ``level`` is interpreted as for | 
|  | 3429 | loggers, and ``NOTSET`` is taken to mean "log everything". | 
|  | 3430 |  | 
| Vinay Sajip | 2a649f9 | 2008-07-18 09:00:35 +0000 | [diff] [blame] | 3431 | .. versionchanged:: 2.6 | 
|  | 3432 | Added support for resolving the handler's class as a dotted module and class | 
|  | 3433 | name. | 
|  | 3434 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 3435 | The ``formatter`` entry indicates the key name of the formatter for this | 
|  | 3436 | handler. If blank, a default formatter (``logging._defaultFormatter``) is used. | 
|  | 3437 | If a name is specified, it must appear in the ``[formatters]`` section and have | 
|  | 3438 | a corresponding section in the configuration file. | 
|  | 3439 |  | 
|  | 3440 | The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging`` | 
|  | 3441 | package's namespace, is the list of arguments to the constructor for the handler | 
|  | 3442 | class. Refer to the constructors for the relevant handlers, or to the examples | 
|  | 3443 | below, to see how typical entries are constructed. :: | 
|  | 3444 |  | 
|  | 3445 | [handler_hand02] | 
|  | 3446 | class=FileHandler | 
|  | 3447 | level=DEBUG | 
|  | 3448 | formatter=form02 | 
|  | 3449 | args=('python.log', 'w') | 
|  | 3450 |  | 
|  | 3451 | [handler_hand03] | 
|  | 3452 | class=handlers.SocketHandler | 
|  | 3453 | level=INFO | 
|  | 3454 | formatter=form03 | 
|  | 3455 | args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT) | 
|  | 3456 |  | 
|  | 3457 | [handler_hand04] | 
|  | 3458 | class=handlers.DatagramHandler | 
|  | 3459 | level=WARN | 
|  | 3460 | formatter=form04 | 
|  | 3461 | args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT) | 
|  | 3462 |  | 
|  | 3463 | [handler_hand05] | 
|  | 3464 | class=handlers.SysLogHandler | 
|  | 3465 | level=ERROR | 
|  | 3466 | formatter=form05 | 
|  | 3467 | args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER) | 
|  | 3468 |  | 
|  | 3469 | [handler_hand06] | 
|  | 3470 | class=handlers.NTEventLogHandler | 
|  | 3471 | level=CRITICAL | 
|  | 3472 | formatter=form06 | 
|  | 3473 | args=('Python Application', '', 'Application') | 
|  | 3474 |  | 
|  | 3475 | [handler_hand07] | 
|  | 3476 | class=handlers.SMTPHandler | 
|  | 3477 | level=WARN | 
|  | 3478 | formatter=form07 | 
|  | 3479 | args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject') | 
|  | 3480 |  | 
|  | 3481 | [handler_hand08] | 
|  | 3482 | class=handlers.MemoryHandler | 
|  | 3483 | level=NOTSET | 
|  | 3484 | formatter=form08 | 
|  | 3485 | target= | 
|  | 3486 | args=(10, ERROR) | 
|  | 3487 |  | 
|  | 3488 | [handler_hand09] | 
|  | 3489 | class=handlers.HTTPHandler | 
|  | 3490 | level=NOTSET | 
|  | 3491 | formatter=form09 | 
|  | 3492 | args=('localhost:9022', '/log', 'GET') | 
|  | 3493 |  | 
|  | 3494 | Sections which specify formatter configuration are typified by the following. :: | 
|  | 3495 |  | 
|  | 3496 | [formatter_form01] | 
|  | 3497 | format=F1 %(asctime)s %(levelname)s %(message)s | 
|  | 3498 | datefmt= | 
|  | 3499 | class=logging.Formatter | 
|  | 3500 |  | 
|  | 3501 | The ``format`` entry is the overall format string, and the ``datefmt`` entry is | 
| Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 3502 | the :func:`strftime`\ -compatible date/time format string.  If empty, the | 
|  | 3503 | package substitutes ISO8601 format date/times, which is almost equivalent to | 
|  | 3504 | specifying the date format string ``"%Y-%m-%d %H:%M:%S"``.  The ISO8601 format | 
|  | 3505 | also specifies milliseconds, which are appended to the result of using the above | 
|  | 3506 | format string, with a comma separator.  An example time in ISO8601 format is | 
|  | 3507 | ``2003-01-23 00:29:50,411``. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 3508 |  | 
|  | 3509 | The ``class`` entry is optional.  It indicates the name of the formatter's class | 
|  | 3510 | (as a dotted module and class name.)  This option is useful for instantiating a | 
|  | 3511 | :class:`Formatter` subclass.  Subclasses of :class:`Formatter` can present | 
|  | 3512 | exception tracebacks in an expanded or condensed format. | 
|  | 3513 |  | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 3514 |  | 
|  | 3515 | Configuration server example | 
|  | 3516 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | 
|  | 3517 |  | 
|  | 3518 | Here is an example of a module using the logging configuration server:: | 
|  | 3519 |  | 
|  | 3520 | import logging | 
|  | 3521 | import logging.config | 
|  | 3522 | import time | 
|  | 3523 | import os | 
|  | 3524 |  | 
|  | 3525 | # read initial config file | 
|  | 3526 | logging.config.fileConfig("logging.conf") | 
|  | 3527 |  | 
|  | 3528 | # create and start listener on port 9999 | 
|  | 3529 | t = logging.config.listen(9999) | 
|  | 3530 | t.start() | 
|  | 3531 |  | 
|  | 3532 | logger = logging.getLogger("simpleExample") | 
|  | 3533 |  | 
|  | 3534 | try: | 
|  | 3535 | # loop through logging calls to see the difference | 
|  | 3536 | # new configurations make, until Ctrl+C is pressed | 
|  | 3537 | while True: | 
|  | 3538 | logger.debug("debug message") | 
|  | 3539 | logger.info("info message") | 
|  | 3540 | logger.warn("warn message") | 
|  | 3541 | logger.error("error message") | 
|  | 3542 | logger.critical("critical message") | 
|  | 3543 | time.sleep(5) | 
|  | 3544 | except KeyboardInterrupt: | 
|  | 3545 | # cleanup | 
|  | 3546 | logging.config.stopListening() | 
|  | 3547 | t.join() | 
|  | 3548 |  | 
|  | 3549 | And here is a script that takes a filename and sends that file to the server, | 
|  | 3550 | properly preceded with the binary-encoded length, as the new logging | 
|  | 3551 | configuration:: | 
|  | 3552 |  | 
|  | 3553 | #!/usr/bin/env python | 
| Benjamin Peterson | a7b55a3 | 2009-02-20 03:31:23 +0000 | [diff] [blame] | 3554 | import socket, sys, struct | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 3555 |  | 
|  | 3556 | data_to_send = open(sys.argv[1], "r").read() | 
|  | 3557 |  | 
|  | 3558 | HOST = 'localhost' | 
|  | 3559 | PORT = 9999 | 
|  | 3560 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | 
|  | 3561 | print "connecting..." | 
|  | 3562 | s.connect((HOST, PORT)) | 
|  | 3563 | print "sending config..." | 
|  | 3564 | s.send(struct.pack(">L", len(data_to_send))) | 
|  | 3565 | s.send(data_to_send) | 
|  | 3566 | s.close() | 
|  | 3567 | print "complete" | 
|  | 3568 |  | 
|  | 3569 |  | 
|  | 3570 | More examples | 
|  | 3571 | ------------- | 
|  | 3572 |  | 
|  | 3573 | Multiple handlers and formatters | 
|  | 3574 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | 
|  | 3575 |  | 
|  | 3576 | Loggers are plain Python objects.  The :func:`addHandler` method has no minimum | 
|  | 3577 | or maximum quota for the number of handlers you may add.  Sometimes it will be | 
|  | 3578 | beneficial for an application to log all messages of all severities to a text | 
|  | 3579 | file while simultaneously logging errors or above to the console.  To set this | 
|  | 3580 | up, simply configure the appropriate handlers.  The logging calls in the | 
|  | 3581 | application code will remain unchanged.  Here is a slight modification to the | 
|  | 3582 | previous simple module-based configuration example:: | 
|  | 3583 |  | 
|  | 3584 | import logging | 
|  | 3585 |  | 
|  | 3586 | logger = logging.getLogger("simple_example") | 
|  | 3587 | logger.setLevel(logging.DEBUG) | 
|  | 3588 | # create file handler which logs even debug messages | 
|  | 3589 | fh = logging.FileHandler("spam.log") | 
|  | 3590 | fh.setLevel(logging.DEBUG) | 
|  | 3591 | # create console handler with a higher log level | 
|  | 3592 | ch = logging.StreamHandler() | 
|  | 3593 | ch.setLevel(logging.ERROR) | 
|  | 3594 | # create formatter and add it to the handlers | 
|  | 3595 | formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") | 
|  | 3596 | ch.setFormatter(formatter) | 
|  | 3597 | fh.setFormatter(formatter) | 
|  | 3598 | # add the handlers to logger | 
|  | 3599 | logger.addHandler(ch) | 
|  | 3600 | logger.addHandler(fh) | 
|  | 3601 |  | 
|  | 3602 | # "application" code | 
|  | 3603 | logger.debug("debug message") | 
|  | 3604 | logger.info("info message") | 
|  | 3605 | logger.warn("warn message") | 
|  | 3606 | logger.error("error message") | 
|  | 3607 | logger.critical("critical message") | 
|  | 3608 |  | 
|  | 3609 | Notice that the "application" code does not care about multiple handlers.  All | 
|  | 3610 | that changed was the addition and configuration of a new handler named *fh*. | 
|  | 3611 |  | 
|  | 3612 | The ability to create new handlers with higher- or lower-severity filters can be | 
|  | 3613 | very helpful when writing and testing an application.  Instead of using many | 
|  | 3614 | ``print`` statements for debugging, use ``logger.debug``: Unlike the print | 
|  | 3615 | statements, which you will have to delete or comment out later, the logger.debug | 
|  | 3616 | statements can remain intact in the source code and remain dormant until you | 
|  | 3617 | need them again.  At that time, the only change that needs to happen is to | 
|  | 3618 | modify the severity level of the logger and/or handler to debug. | 
|  | 3619 |  | 
|  | 3620 |  | 
|  | 3621 | Using logging in multiple modules | 
|  | 3622 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | 
|  | 3623 |  | 
|  | 3624 | It was mentioned above that multiple calls to | 
|  | 3625 | ``logging.getLogger('someLogger')`` return a reference to the same logger | 
|  | 3626 | object.  This is true not only within the same module, but also across modules | 
|  | 3627 | as long as it is in the same Python interpreter process.  It is true for | 
|  | 3628 | references to the same object; additionally, application code can define and | 
|  | 3629 | configure a parent logger in one module and create (but not configure) a child | 
|  | 3630 | logger in a separate module, and all logger calls to the child will pass up to | 
|  | 3631 | the parent.  Here is a main module:: | 
|  | 3632 |  | 
|  | 3633 | import logging | 
|  | 3634 | import auxiliary_module | 
|  | 3635 |  | 
|  | 3636 | # create logger with "spam_application" | 
|  | 3637 | logger = logging.getLogger("spam_application") | 
|  | 3638 | logger.setLevel(logging.DEBUG) | 
|  | 3639 | # create file handler which logs even debug messages | 
|  | 3640 | fh = logging.FileHandler("spam.log") | 
|  | 3641 | fh.setLevel(logging.DEBUG) | 
|  | 3642 | # create console handler with a higher log level | 
|  | 3643 | ch = logging.StreamHandler() | 
|  | 3644 | ch.setLevel(logging.ERROR) | 
|  | 3645 | # create formatter and add it to the handlers | 
|  | 3646 | formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") | 
|  | 3647 | fh.setFormatter(formatter) | 
|  | 3648 | ch.setFormatter(formatter) | 
|  | 3649 | # add the handlers to the logger | 
|  | 3650 | logger.addHandler(fh) | 
|  | 3651 | logger.addHandler(ch) | 
|  | 3652 |  | 
|  | 3653 | logger.info("creating an instance of auxiliary_module.Auxiliary") | 
|  | 3654 | a = auxiliary_module.Auxiliary() | 
|  | 3655 | logger.info("created an instance of auxiliary_module.Auxiliary") | 
|  | 3656 | logger.info("calling auxiliary_module.Auxiliary.do_something") | 
|  | 3657 | a.do_something() | 
|  | 3658 | logger.info("finished auxiliary_module.Auxiliary.do_something") | 
|  | 3659 | logger.info("calling auxiliary_module.some_function()") | 
|  | 3660 | auxiliary_module.some_function() | 
|  | 3661 | logger.info("done with auxiliary_module.some_function()") | 
|  | 3662 |  | 
|  | 3663 | Here is the auxiliary module:: | 
|  | 3664 |  | 
|  | 3665 | import logging | 
|  | 3666 |  | 
|  | 3667 | # create logger | 
|  | 3668 | module_logger = logging.getLogger("spam_application.auxiliary") | 
|  | 3669 |  | 
|  | 3670 | class Auxiliary: | 
|  | 3671 | def __init__(self): | 
|  | 3672 | self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary") | 
|  | 3673 | self.logger.info("creating an instance of Auxiliary") | 
|  | 3674 | def do_something(self): | 
|  | 3675 | self.logger.info("doing something") | 
|  | 3676 | a = 1 + 1 | 
|  | 3677 | self.logger.info("done doing something") | 
|  | 3678 |  | 
|  | 3679 | def some_function(): | 
|  | 3680 | module_logger.info("received a call to \"some_function\"") | 
|  | 3681 |  | 
|  | 3682 | The output looks like this:: | 
|  | 3683 |  | 
| Vinay Sajip | e28fa29 | 2008-01-07 15:30:36 +0000 | [diff] [blame] | 3684 | 2005-03-23 23:47:11,663 - spam_application - INFO - | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 3685 | creating an instance of auxiliary_module.Auxiliary | 
| Vinay Sajip | e28fa29 | 2008-01-07 15:30:36 +0000 | [diff] [blame] | 3686 | 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO - | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 3687 | creating an instance of Auxiliary | 
| Vinay Sajip | e28fa29 | 2008-01-07 15:30:36 +0000 | [diff] [blame] | 3688 | 2005-03-23 23:47:11,665 - spam_application - INFO - | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 3689 | created an instance of auxiliary_module.Auxiliary | 
| Vinay Sajip | e28fa29 | 2008-01-07 15:30:36 +0000 | [diff] [blame] | 3690 | 2005-03-23 23:47:11,668 - spam_application - INFO - | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 3691 | calling auxiliary_module.Auxiliary.do_something | 
| Vinay Sajip | e28fa29 | 2008-01-07 15:30:36 +0000 | [diff] [blame] | 3692 | 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO - | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 3693 | doing something | 
| Vinay Sajip | e28fa29 | 2008-01-07 15:30:36 +0000 | [diff] [blame] | 3694 | 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO - | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 3695 | done doing something | 
| Vinay Sajip | e28fa29 | 2008-01-07 15:30:36 +0000 | [diff] [blame] | 3696 | 2005-03-23 23:47:11,670 - spam_application - INFO - | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 3697 | finished auxiliary_module.Auxiliary.do_something | 
| Vinay Sajip | e28fa29 | 2008-01-07 15:30:36 +0000 | [diff] [blame] | 3698 | 2005-03-23 23:47:11,671 - spam_application - INFO - | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 3699 | calling auxiliary_module.some_function() | 
| Vinay Sajip | e28fa29 | 2008-01-07 15:30:36 +0000 | [diff] [blame] | 3700 | 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO - | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 3701 | received a call to "some_function" | 
| Vinay Sajip | e28fa29 | 2008-01-07 15:30:36 +0000 | [diff] [blame] | 3702 | 2005-03-23 23:47:11,673 - spam_application - INFO - | 
| Georg Brandl | c37f288 | 2007-12-04 17:46:27 +0000 | [diff] [blame] | 3703 | done with auxiliary_module.some_function() | 
|  | 3704 |  |