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