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