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