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