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