Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 1 | .. _logging-cookbook: |
| 2 | |
| 3 | ================ |
| 4 | Logging Cookbook |
| 5 | ================ |
| 6 | |
| 7 | :Author: Vinay Sajip <vinay_sajip at red-dove dot com> |
| 8 | |
Georg Brandl | 375aec2 | 2011-01-15 17:03:02 +0000 | [diff] [blame] | 9 | This page contains a number of recipes related to logging, which have been found |
| 10 | useful in the past. |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 11 | |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 12 | .. currentmodule:: logging |
| 13 | |
| 14 | Using logging in multiple modules |
| 15 | --------------------------------- |
| 16 | |
Vinay Sajip | 1397ce1 | 2010-12-24 12:03:48 +0000 | [diff] [blame] | 17 | Multiple calls to ``logging.getLogger('someLogger')`` return a reference to the |
| 18 | same logger object. This is true not only within the same module, but also |
| 19 | across modules as long as it is in the same Python interpreter process. It is |
| 20 | true for references to the same object; additionally, application code can |
| 21 | define and configure a parent logger in one module and create (but not |
| 22 | configure) a child logger in a separate module, and all logger calls to the |
| 23 | child will pass up to the parent. Here is a main module:: |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 24 | |
| 25 | import logging |
| 26 | import auxiliary_module |
| 27 | |
| 28 | # create logger with 'spam_application' |
| 29 | logger = logging.getLogger('spam_application') |
| 30 | logger.setLevel(logging.DEBUG) |
| 31 | # create file handler which logs even debug messages |
| 32 | fh = logging.FileHandler('spam.log') |
| 33 | fh.setLevel(logging.DEBUG) |
| 34 | # create console handler with a higher log level |
| 35 | ch = logging.StreamHandler() |
| 36 | ch.setLevel(logging.ERROR) |
| 37 | # create formatter and add it to the handlers |
| 38 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') |
| 39 | fh.setFormatter(formatter) |
| 40 | ch.setFormatter(formatter) |
| 41 | # add the handlers to the logger |
| 42 | logger.addHandler(fh) |
| 43 | logger.addHandler(ch) |
| 44 | |
| 45 | logger.info('creating an instance of auxiliary_module.Auxiliary') |
| 46 | a = auxiliary_module.Auxiliary() |
| 47 | logger.info('created an instance of auxiliary_module.Auxiliary') |
| 48 | logger.info('calling auxiliary_module.Auxiliary.do_something') |
| 49 | a.do_something() |
| 50 | logger.info('finished auxiliary_module.Auxiliary.do_something') |
| 51 | logger.info('calling auxiliary_module.some_function()') |
| 52 | auxiliary_module.some_function() |
| 53 | logger.info('done with auxiliary_module.some_function()') |
| 54 | |
| 55 | Here is the auxiliary module:: |
| 56 | |
| 57 | import logging |
| 58 | |
| 59 | # create logger |
| 60 | module_logger = logging.getLogger('spam_application.auxiliary') |
| 61 | |
| 62 | class Auxiliary: |
| 63 | def __init__(self): |
| 64 | self.logger = logging.getLogger('spam_application.auxiliary.Auxiliary') |
| 65 | self.logger.info('creating an instance of Auxiliary') |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 66 | |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 67 | def do_something(self): |
| 68 | self.logger.info('doing something') |
| 69 | a = 1 + 1 |
| 70 | self.logger.info('done doing something') |
| 71 | |
| 72 | def some_function(): |
| 73 | module_logger.info('received a call to "some_function"') |
| 74 | |
| 75 | The output looks like this:: |
| 76 | |
| 77 | 2005-03-23 23:47:11,663 - spam_application - INFO - |
| 78 | creating an instance of auxiliary_module.Auxiliary |
| 79 | 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO - |
| 80 | creating an instance of Auxiliary |
| 81 | 2005-03-23 23:47:11,665 - spam_application - INFO - |
| 82 | created an instance of auxiliary_module.Auxiliary |
| 83 | 2005-03-23 23:47:11,668 - spam_application - INFO - |
| 84 | calling auxiliary_module.Auxiliary.do_something |
| 85 | 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO - |
| 86 | doing something |
| 87 | 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO - |
| 88 | done doing something |
| 89 | 2005-03-23 23:47:11,670 - spam_application - INFO - |
| 90 | finished auxiliary_module.Auxiliary.do_something |
| 91 | 2005-03-23 23:47:11,671 - spam_application - INFO - |
| 92 | calling auxiliary_module.some_function() |
| 93 | 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO - |
| 94 | received a call to 'some_function' |
| 95 | 2005-03-23 23:47:11,673 - spam_application - INFO - |
| 96 | done with auxiliary_module.some_function() |
| 97 | |
Vinay Sajip | e10d370 | 2016-02-20 19:02:46 +0000 | [diff] [blame] | 98 | Logging from multiple threads |
| 99 | ----------------------------- |
| 100 | |
| 101 | Logging from multiple threads requires no special effort. The following example |
Berker Peksag | 563c949 | 2016-03-20 12:50:56 +0200 | [diff] [blame] | 102 | shows logging from the main (initial) thread and another thread:: |
Vinay Sajip | e10d370 | 2016-02-20 19:02:46 +0000 | [diff] [blame] | 103 | |
| 104 | import logging |
| 105 | import threading |
| 106 | import time |
| 107 | |
| 108 | def worker(arg): |
| 109 | while not arg['stop']: |
| 110 | logging.debug('Hi from myfunc') |
| 111 | time.sleep(0.5) |
| 112 | |
| 113 | def main(): |
| 114 | logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s') |
| 115 | info = {'stop': False} |
| 116 | thread = threading.Thread(target=worker, args=(info,)) |
| 117 | thread.start() |
| 118 | while True: |
| 119 | try: |
| 120 | logging.debug('Hello from main') |
| 121 | time.sleep(0.75) |
| 122 | except KeyboardInterrupt: |
| 123 | info['stop'] = True |
| 124 | break |
| 125 | thread.join() |
| 126 | |
| 127 | if __name__ == '__main__': |
| 128 | main() |
| 129 | |
| 130 | When run, the script should print something like the following:: |
| 131 | |
| 132 | 0 Thread-1 Hi from myfunc |
| 133 | 3 MainThread Hello from main |
| 134 | 505 Thread-1 Hi from myfunc |
| 135 | 755 MainThread Hello from main |
| 136 | 1007 Thread-1 Hi from myfunc |
| 137 | 1507 MainThread Hello from main |
| 138 | 1508 Thread-1 Hi from myfunc |
| 139 | 2010 Thread-1 Hi from myfunc |
| 140 | 2258 MainThread Hello from main |
| 141 | 2512 Thread-1 Hi from myfunc |
| 142 | 3009 MainThread Hello from main |
| 143 | 3013 Thread-1 Hi from myfunc |
| 144 | 3515 Thread-1 Hi from myfunc |
| 145 | 3761 MainThread Hello from main |
| 146 | 4017 Thread-1 Hi from myfunc |
| 147 | 4513 MainThread Hello from main |
| 148 | 4518 Thread-1 Hi from myfunc |
| 149 | |
| 150 | This shows the logging output interspersed as one might expect. This approach |
| 151 | works for more threads than shown here, of course. |
| 152 | |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 153 | Multiple handlers and formatters |
| 154 | -------------------------------- |
| 155 | |
Vinay Sajip | 67f3977 | 2013-08-17 00:39:42 +0100 | [diff] [blame] | 156 | Loggers are plain Python objects. The :meth:`~Logger.addHandler` method has no |
| 157 | minimum or maximum quota for the number of handlers you may add. Sometimes it |
| 158 | will be beneficial for an application to log all messages of all severities to a |
| 159 | text file while simultaneously logging errors or above to the console. To set |
| 160 | this up, simply configure the appropriate handlers. The logging calls in the |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 161 | application code will remain unchanged. Here is a slight modification to the |
| 162 | previous simple module-based configuration example:: |
| 163 | |
| 164 | import logging |
| 165 | |
| 166 | logger = logging.getLogger('simple_example') |
| 167 | logger.setLevel(logging.DEBUG) |
| 168 | # create file handler which logs even debug messages |
| 169 | fh = logging.FileHandler('spam.log') |
| 170 | fh.setLevel(logging.DEBUG) |
| 171 | # create console handler with a higher log level |
| 172 | ch = logging.StreamHandler() |
| 173 | ch.setLevel(logging.ERROR) |
| 174 | # create formatter and add it to the handlers |
| 175 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') |
| 176 | ch.setFormatter(formatter) |
| 177 | fh.setFormatter(formatter) |
| 178 | # add the handlers to logger |
| 179 | logger.addHandler(ch) |
| 180 | logger.addHandler(fh) |
| 181 | |
| 182 | # 'application' code |
| 183 | logger.debug('debug message') |
| 184 | logger.info('info message') |
| 185 | logger.warn('warn message') |
| 186 | logger.error('error message') |
| 187 | logger.critical('critical message') |
| 188 | |
| 189 | Notice that the 'application' code does not care about multiple handlers. All |
| 190 | that changed was the addition and configuration of a new handler named *fh*. |
| 191 | |
| 192 | The ability to create new handlers with higher- or lower-severity filters can be |
| 193 | very helpful when writing and testing an application. Instead of using many |
| 194 | ``print`` statements for debugging, use ``logger.debug``: Unlike the print |
| 195 | statements, which you will have to delete or comment out later, the logger.debug |
| 196 | statements can remain intact in the source code and remain dormant until you |
| 197 | need them again. At that time, the only change that needs to happen is to |
| 198 | modify the severity level of the logger and/or handler to debug. |
| 199 | |
| 200 | .. _multiple-destinations: |
| 201 | |
| 202 | Logging to multiple destinations |
| 203 | -------------------------------- |
| 204 | |
| 205 | Let's say you want to log to console and file with different message formats and |
| 206 | in differing circumstances. Say you want to log messages with levels of DEBUG |
| 207 | and higher to file, and those messages at level INFO and higher to the console. |
| 208 | Let's also assume that the file should contain timestamps, but the console |
| 209 | messages should not. Here's how you can achieve this:: |
| 210 | |
| 211 | import logging |
| 212 | |
| 213 | # set up logging to file - see previous section for more details |
| 214 | logging.basicConfig(level=logging.DEBUG, |
| 215 | format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', |
| 216 | datefmt='%m-%d %H:%M', |
| 217 | filename='/temp/myapp.log', |
| 218 | filemode='w') |
| 219 | # define a Handler which writes INFO messages or higher to the sys.stderr |
| 220 | console = logging.StreamHandler() |
| 221 | console.setLevel(logging.INFO) |
| 222 | # set a format which is simpler for console use |
| 223 | formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') |
| 224 | # tell the handler to use this format |
| 225 | console.setFormatter(formatter) |
| 226 | # add the handler to the root logger |
| 227 | logging.getLogger('').addHandler(console) |
| 228 | |
| 229 | # Now, we can log to the root logger, or any other logger. First the root... |
| 230 | logging.info('Jackdaws love my big sphinx of quartz.') |
| 231 | |
| 232 | # Now, define a couple of other loggers which might represent areas in your |
| 233 | # application: |
| 234 | |
| 235 | logger1 = logging.getLogger('myapp.area1') |
| 236 | logger2 = logging.getLogger('myapp.area2') |
| 237 | |
| 238 | logger1.debug('Quick zephyrs blow, vexing daft Jim.') |
| 239 | logger1.info('How quickly daft jumping zebras vex.') |
| 240 | logger2.warning('Jail zesty vixen who grabbed pay from quack.') |
| 241 | logger2.error('The five boxing wizards jump quickly.') |
| 242 | |
| 243 | When you run this, on the console you will see :: |
| 244 | |
| 245 | root : INFO Jackdaws love my big sphinx of quartz. |
| 246 | myapp.area1 : INFO How quickly daft jumping zebras vex. |
| 247 | myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack. |
| 248 | myapp.area2 : ERROR The five boxing wizards jump quickly. |
| 249 | |
| 250 | and in the file you will see something like :: |
| 251 | |
| 252 | 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz. |
| 253 | 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim. |
| 254 | 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex. |
| 255 | 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack. |
| 256 | 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly. |
| 257 | |
| 258 | As you can see, the DEBUG message only shows up in the file. The other messages |
| 259 | are sent to both destinations. |
| 260 | |
| 261 | This example uses console and file handlers, but you can use any number and |
| 262 | combination of handlers you choose. |
| 263 | |
| 264 | |
| 265 | Configuration server example |
| 266 | ---------------------------- |
| 267 | |
| 268 | Here is an example of a module using the logging configuration server:: |
| 269 | |
| 270 | import logging |
| 271 | import logging.config |
| 272 | import time |
| 273 | import os |
| 274 | |
| 275 | # read initial config file |
| 276 | logging.config.fileConfig('logging.conf') |
| 277 | |
| 278 | # create and start listener on port 9999 |
| 279 | t = logging.config.listen(9999) |
| 280 | t.start() |
| 281 | |
| 282 | logger = logging.getLogger('simpleExample') |
| 283 | |
| 284 | try: |
| 285 | # loop through logging calls to see the difference |
| 286 | # new configurations make, until Ctrl+C is pressed |
| 287 | while True: |
| 288 | logger.debug('debug message') |
| 289 | logger.info('info message') |
| 290 | logger.warn('warn message') |
| 291 | logger.error('error message') |
| 292 | logger.critical('critical message') |
| 293 | time.sleep(5) |
| 294 | except KeyboardInterrupt: |
| 295 | # cleanup |
| 296 | logging.config.stopListening() |
| 297 | t.join() |
| 298 | |
| 299 | And here is a script that takes a filename and sends that file to the server, |
| 300 | properly preceded with the binary-encoded length, as the new logging |
| 301 | configuration:: |
| 302 | |
| 303 | #!/usr/bin/env python |
| 304 | import socket, sys, struct |
| 305 | |
Vinay Sajip | 689b68a | 2010-12-22 15:04:15 +0000 | [diff] [blame] | 306 | with open(sys.argv[1], 'rb') as f: |
| 307 | data_to_send = f.read() |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 308 | |
| 309 | HOST = 'localhost' |
| 310 | PORT = 9999 |
| 311 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 312 | print('connecting...') |
| 313 | s.connect((HOST, PORT)) |
| 314 | print('sending config...') |
| 315 | s.send(struct.pack('>L', len(data_to_send))) |
| 316 | s.send(data_to_send) |
| 317 | s.close() |
| 318 | print('complete') |
| 319 | |
| 320 | |
| 321 | Dealing with handlers that block |
| 322 | -------------------------------- |
| 323 | |
| 324 | .. currentmodule:: logging.handlers |
| 325 | |
| 326 | Sometimes you have to get your logging handlers to do their work without |
Vinay Sajip | 6b883a2 | 2012-02-27 11:02:45 +0000 | [diff] [blame] | 327 | blocking the thread you're logging from. This is common in Web applications, |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 328 | though of course it also occurs in other scenarios. |
| 329 | |
| 330 | A common culprit which demonstrates sluggish behaviour is the |
| 331 | :class:`SMTPHandler`: sending emails can take a long time, for a |
Vinay Sajip | 6b883a2 | 2012-02-27 11:02:45 +0000 | [diff] [blame] | 332 | number of reasons outside the developer's control (for example, a poorly |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 333 | performing mail or network infrastructure). But almost any network-based |
| 334 | handler can block: Even a :class:`SocketHandler` operation may do a |
| 335 | DNS query under the hood which is too slow (and this query can be deep in the |
| 336 | socket library code, below the Python layer, and outside your control). |
| 337 | |
| 338 | One solution is to use a two-part approach. For the first part, attach only a |
| 339 | :class:`QueueHandler` to those loggers which are accessed from |
| 340 | performance-critical threads. They simply write to their queue, which can be |
| 341 | sized to a large enough capacity or initialized with no upper bound to their |
| 342 | size. The write to the queue will typically be accepted quickly, though you |
Georg Brandl | 375aec2 | 2011-01-15 17:03:02 +0000 | [diff] [blame] | 343 | will probably need to catch the :exc:`queue.Full` exception as a precaution |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 344 | in your code. If you are a library developer who has performance-critical |
| 345 | threads in their code, be sure to document this (together with a suggestion to |
| 346 | attach only ``QueueHandlers`` to your loggers) for the benefit of other |
| 347 | developers who will use your code. |
| 348 | |
| 349 | The second part of the solution is :class:`QueueListener`, which has been |
| 350 | designed as the counterpart to :class:`QueueHandler`. A |
Vinay Sajip | 6b883a2 | 2012-02-27 11:02:45 +0000 | [diff] [blame] | 351 | :class:`QueueListener` is very simple: it's passed a queue and some handlers, |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 352 | and it fires up an internal thread which listens to its queue for LogRecords |
| 353 | sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that |
| 354 | matter). The ``LogRecords`` are removed from the queue and passed to the |
| 355 | handlers for processing. |
| 356 | |
| 357 | The advantage of having a separate :class:`QueueListener` class is that you |
| 358 | can use the same instance to service multiple ``QueueHandlers``. This is more |
| 359 | resource-friendly than, say, having threaded versions of the existing handler |
| 360 | classes, which would eat up one thread per handler for no particular benefit. |
| 361 | |
| 362 | An example of using these two classes follows (imports omitted):: |
| 363 | |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 364 | que = queue.Queue(-1) # no limit on size |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 365 | queue_handler = QueueHandler(que) |
| 366 | handler = logging.StreamHandler() |
| 367 | listener = QueueListener(que, handler) |
| 368 | root = logging.getLogger() |
| 369 | root.addHandler(queue_handler) |
| 370 | formatter = logging.Formatter('%(threadName)s: %(message)s') |
| 371 | handler.setFormatter(formatter) |
| 372 | listener.start() |
| 373 | # The log output will display the thread which generated |
| 374 | # the event (the main thread) rather than the internal |
| 375 | # thread which monitors the internal queue. This is what |
| 376 | # you want to happen. |
| 377 | root.warning('Look out!') |
| 378 | listener.stop() |
| 379 | |
Martin Panter | 1050d2d | 2016-07-26 11:18:21 +0200 | [diff] [blame] | 380 | which, when run, will produce: |
| 381 | |
| 382 | .. code-block:: none |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 383 | |
| 384 | MainThread: Look out! |
| 385 | |
Vinay Sajip | 365701a | 2015-02-09 19:49:00 +0000 | [diff] [blame] | 386 | .. versionchanged:: 3.5 |
| 387 | Prior to Python 3.5, the :class:`QueueListener` always passed every message |
| 388 | received from the queue to every handler it was initialized with. (This was |
| 389 | because it was assumed that level filtering was all done on the other side, |
| 390 | where the queue is filled.) From 3.5 onwards, this behaviour can be changed |
| 391 | by passing a keyword argument ``respect_handler_level=True`` to the |
| 392 | listener's constructor. When this is done, the listener compares the level |
| 393 | of each message with the handler's level, and only passes a message to a |
| 394 | handler if it's appropriate to do so. |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 395 | |
| 396 | .. _network-logging: |
| 397 | |
| 398 | Sending and receiving logging events across a network |
| 399 | ----------------------------------------------------- |
| 400 | |
| 401 | Let's say you want to send logging events across a network, and handle them at |
| 402 | the receiving end. A simple way of doing this is attaching a |
| 403 | :class:`SocketHandler` instance to the root logger at the sending end:: |
| 404 | |
| 405 | import logging, logging.handlers |
| 406 | |
| 407 | rootLogger = logging.getLogger('') |
| 408 | rootLogger.setLevel(logging.DEBUG) |
| 409 | socketHandler = logging.handlers.SocketHandler('localhost', |
| 410 | logging.handlers.DEFAULT_TCP_LOGGING_PORT) |
| 411 | # don't bother with a formatter, since a socket handler sends the event as |
| 412 | # an unformatted pickle |
| 413 | rootLogger.addHandler(socketHandler) |
| 414 | |
| 415 | # Now, we can log to the root logger, or any other logger. First the root... |
| 416 | logging.info('Jackdaws love my big sphinx of quartz.') |
| 417 | |
| 418 | # Now, define a couple of other loggers which might represent areas in your |
| 419 | # application: |
| 420 | |
| 421 | logger1 = logging.getLogger('myapp.area1') |
| 422 | logger2 = logging.getLogger('myapp.area2') |
| 423 | |
| 424 | logger1.debug('Quick zephyrs blow, vexing daft Jim.') |
| 425 | logger1.info('How quickly daft jumping zebras vex.') |
| 426 | logger2.warning('Jail zesty vixen who grabbed pay from quack.') |
| 427 | logger2.error('The five boxing wizards jump quickly.') |
| 428 | |
| 429 | At the receiving end, you can set up a receiver using the :mod:`socketserver` |
| 430 | module. Here is a basic working example:: |
| 431 | |
| 432 | import pickle |
| 433 | import logging |
| 434 | import logging.handlers |
| 435 | import socketserver |
| 436 | import struct |
| 437 | |
| 438 | |
| 439 | class LogRecordStreamHandler(socketserver.StreamRequestHandler): |
| 440 | """Handler for a streaming logging request. |
| 441 | |
| 442 | This basically logs the record using whatever logging policy is |
| 443 | configured locally. |
| 444 | """ |
| 445 | |
| 446 | def handle(self): |
| 447 | """ |
| 448 | Handle multiple requests - each expected to be a 4-byte length, |
| 449 | followed by the LogRecord in pickle format. Logs the record |
| 450 | according to whatever policy is configured locally. |
| 451 | """ |
| 452 | while True: |
| 453 | chunk = self.connection.recv(4) |
| 454 | if len(chunk) < 4: |
| 455 | break |
| 456 | slen = struct.unpack('>L', chunk)[0] |
| 457 | chunk = self.connection.recv(slen) |
| 458 | while len(chunk) < slen: |
| 459 | chunk = chunk + self.connection.recv(slen - len(chunk)) |
| 460 | obj = self.unPickle(chunk) |
| 461 | record = logging.makeLogRecord(obj) |
| 462 | self.handleLogRecord(record) |
| 463 | |
| 464 | def unPickle(self, data): |
| 465 | return pickle.loads(data) |
| 466 | |
| 467 | def handleLogRecord(self, record): |
| 468 | # if a name is specified, we use the named logger rather than the one |
| 469 | # implied by the record. |
| 470 | if self.server.logname is not None: |
| 471 | name = self.server.logname |
| 472 | else: |
| 473 | name = record.name |
| 474 | logger = logging.getLogger(name) |
| 475 | # N.B. EVERY record gets logged. This is because Logger.handle |
| 476 | # is normally called AFTER logger-level filtering. If you want |
| 477 | # to do filtering, do it at the client end to save wasting |
| 478 | # cycles and network bandwidth! |
| 479 | logger.handle(record) |
| 480 | |
| 481 | class LogRecordSocketReceiver(socketserver.ThreadingTCPServer): |
| 482 | """ |
| 483 | Simple TCP socket-based logging receiver suitable for testing. |
| 484 | """ |
| 485 | |
Raymond Hettinger | 4ab532b | 2014-03-28 16:39:25 -0700 | [diff] [blame] | 486 | allow_reuse_address = True |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 487 | |
| 488 | def __init__(self, host='localhost', |
| 489 | port=logging.handlers.DEFAULT_TCP_LOGGING_PORT, |
| 490 | handler=LogRecordStreamHandler): |
| 491 | socketserver.ThreadingTCPServer.__init__(self, (host, port), handler) |
| 492 | self.abort = 0 |
| 493 | self.timeout = 1 |
| 494 | self.logname = None |
| 495 | |
| 496 | def serve_until_stopped(self): |
| 497 | import select |
| 498 | abort = 0 |
| 499 | while not abort: |
| 500 | rd, wr, ex = select.select([self.socket.fileno()], |
| 501 | [], [], |
| 502 | self.timeout) |
| 503 | if rd: |
| 504 | self.handle_request() |
| 505 | abort = self.abort |
| 506 | |
| 507 | def main(): |
| 508 | logging.basicConfig( |
| 509 | format='%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s') |
| 510 | tcpserver = LogRecordSocketReceiver() |
| 511 | print('About to start TCP server...') |
| 512 | tcpserver.serve_until_stopped() |
| 513 | |
| 514 | if __name__ == '__main__': |
| 515 | main() |
| 516 | |
| 517 | First run the server, and then the client. On the client side, nothing is |
| 518 | printed on the console; on the server side, you should see something like:: |
| 519 | |
| 520 | About to start TCP server... |
| 521 | 59 root INFO Jackdaws love my big sphinx of quartz. |
| 522 | 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim. |
| 523 | 69 myapp.area1 INFO How quickly daft jumping zebras vex. |
| 524 | 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack. |
| 525 | 69 myapp.area2 ERROR The five boxing wizards jump quickly. |
| 526 | |
| 527 | Note that there are some security issues with pickle in some scenarios. If |
| 528 | these affect you, you can use an alternative serialization scheme by overriding |
Vinay Sajip | 67f3977 | 2013-08-17 00:39:42 +0100 | [diff] [blame] | 529 | the :meth:`~handlers.SocketHandler.makePickle` method and implementing your |
| 530 | alternative there, as well as adapting the above script to use your alternative |
| 531 | serialization. |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 532 | |
| 533 | |
| 534 | .. _context-info: |
| 535 | |
| 536 | Adding contextual information to your logging output |
| 537 | ---------------------------------------------------- |
| 538 | |
| 539 | Sometimes you want logging output to contain contextual information in |
| 540 | addition to the parameters passed to the logging call. For example, in a |
| 541 | networked application, it may be desirable to log client-specific information |
| 542 | in the log (e.g. remote client's username, or IP address). Although you could |
| 543 | use the *extra* parameter to achieve this, it's not always convenient to pass |
| 544 | the information in this way. While it might be tempting to create |
| 545 | :class:`Logger` instances on a per-connection basis, this is not a good idea |
| 546 | because these instances are not garbage collected. While this is not a problem |
| 547 | in practice, when the number of :class:`Logger` instances is dependent on the |
| 548 | level of granularity you want to use in logging an application, it could |
| 549 | be hard to manage if the number of :class:`Logger` instances becomes |
| 550 | effectively unbounded. |
| 551 | |
| 552 | |
| 553 | Using LoggerAdapters to impart contextual information |
| 554 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 555 | |
| 556 | An easy way in which you can pass contextual information to be output along |
| 557 | with logging event information is to use the :class:`LoggerAdapter` class. |
| 558 | This class is designed to look like a :class:`Logger`, so that you can call |
| 559 | :meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`, |
| 560 | :meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the |
| 561 | same signatures as their counterparts in :class:`Logger`, so you can use the |
| 562 | two types of instances interchangeably. |
| 563 | |
| 564 | When you create an instance of :class:`LoggerAdapter`, you pass it a |
| 565 | :class:`Logger` instance and a dict-like object which contains your contextual |
| 566 | information. When you call one of the logging methods on an instance of |
| 567 | :class:`LoggerAdapter`, it delegates the call to the underlying instance of |
| 568 | :class:`Logger` passed to its constructor, and arranges to pass the contextual |
| 569 | information in the delegated call. Here's a snippet from the code of |
| 570 | :class:`LoggerAdapter`:: |
| 571 | |
| 572 | def debug(self, msg, *args, **kwargs): |
| 573 | """ |
| 574 | Delegate a debug call to the underlying logger, after adding |
| 575 | contextual information from this adapter instance. |
| 576 | """ |
| 577 | msg, kwargs = self.process(msg, kwargs) |
| 578 | self.logger.debug(msg, *args, **kwargs) |
| 579 | |
Vinay Sajip | 67f3977 | 2013-08-17 00:39:42 +0100 | [diff] [blame] | 580 | The :meth:`~LoggerAdapter.process` method of :class:`LoggerAdapter` is where the |
| 581 | contextual information is added to the logging output. It's passed the message |
| 582 | and keyword arguments of the logging call, and it passes back (potentially) |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 583 | modified versions of these to use in the call to the underlying logger. The |
| 584 | default implementation of this method leaves the message alone, but inserts |
| 585 | an 'extra' key in the keyword argument whose value is the dict-like object |
| 586 | passed to the constructor. Of course, if you had passed an 'extra' keyword |
| 587 | argument in the call to the adapter, it will be silently overwritten. |
| 588 | |
| 589 | The advantage of using 'extra' is that the values in the dict-like object are |
| 590 | merged into the :class:`LogRecord` instance's __dict__, allowing you to use |
| 591 | customized strings with your :class:`Formatter` instances which know about |
| 592 | the keys of the dict-like object. If you need a different method, e.g. if you |
| 593 | want to prepend or append the contextual information to the message string, |
Vinay Sajip | 67f3977 | 2013-08-17 00:39:42 +0100 | [diff] [blame] | 594 | you just need to subclass :class:`LoggerAdapter` and override |
| 595 | :meth:`~LoggerAdapter.process` to do what you need. Here is a simple example:: |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 596 | |
Vinay Sajip | a92fbe6 | 2013-07-24 17:52:01 +0100 | [diff] [blame] | 597 | class CustomAdapter(logging.LoggerAdapter): |
| 598 | """ |
| 599 | This example adapter expects the passed in dict-like object to have a |
| 600 | 'connid' key, whose value in brackets is prepended to the log message. |
| 601 | """ |
| 602 | def process(self, msg, kwargs): |
| 603 | return '[%s] %s' % (self.extra['connid'], msg), kwargs |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 604 | |
Vinay Sajip | a92fbe6 | 2013-07-24 17:52:01 +0100 | [diff] [blame] | 605 | which you can use like this:: |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 606 | |
Vinay Sajip | a92fbe6 | 2013-07-24 17:52:01 +0100 | [diff] [blame] | 607 | logger = logging.getLogger(__name__) |
| 608 | adapter = CustomAdapter(logger, {'connid': some_conn_id}) |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 609 | |
Vinay Sajip | a92fbe6 | 2013-07-24 17:52:01 +0100 | [diff] [blame] | 610 | Then any events that you log to the adapter will have the value of |
| 611 | ``some_conn_id`` prepended to the log messages. |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 612 | |
Vinay Sajip | a92fbe6 | 2013-07-24 17:52:01 +0100 | [diff] [blame] | 613 | Using objects other than dicts to pass contextual information |
| 614 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 615 | |
Vinay Sajip | a92fbe6 | 2013-07-24 17:52:01 +0100 | [diff] [blame] | 616 | You don't need to pass an actual dict to a :class:`LoggerAdapter` - you could |
| 617 | pass an instance of a class which implements ``__getitem__`` and ``__iter__`` so |
| 618 | that it looks like a dict to logging. This would be useful if you want to |
| 619 | generate values dynamically (whereas the values in a dict would be constant). |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 620 | |
| 621 | |
| 622 | .. _filters-contextual: |
| 623 | |
| 624 | Using Filters to impart contextual information |
| 625 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 626 | |
| 627 | You can also add contextual information to log output using a user-defined |
| 628 | :class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords`` |
| 629 | passed to them, including adding additional attributes which can then be output |
| 630 | using a suitable format string, or if needed a custom :class:`Formatter`. |
| 631 | |
| 632 | For example in a web application, the request being processed (or at least, |
| 633 | the interesting parts of it) can be stored in a threadlocal |
| 634 | (:class:`threading.local`) variable, and then accessed from a ``Filter`` to |
| 635 | add, say, information from the request - say, the remote IP address and remote |
| 636 | user's username - to the ``LogRecord``, using the attribute names 'ip' and |
| 637 | 'user' as in the ``LoggerAdapter`` example above. In that case, the same format |
| 638 | string can be used to get similar output to that shown above. Here's an example |
| 639 | script:: |
| 640 | |
| 641 | import logging |
| 642 | from random import choice |
| 643 | |
| 644 | class ContextFilter(logging.Filter): |
| 645 | """ |
| 646 | This is a filter which injects contextual information into the log. |
| 647 | |
| 648 | Rather than use actual contextual information, we just use random |
| 649 | data in this demo. |
| 650 | """ |
| 651 | |
| 652 | USERS = ['jim', 'fred', 'sheila'] |
| 653 | IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1'] |
| 654 | |
| 655 | def filter(self, record): |
| 656 | |
| 657 | record.ip = choice(ContextFilter.IPS) |
| 658 | record.user = choice(ContextFilter.USERS) |
| 659 | return True |
| 660 | |
| 661 | if __name__ == '__main__': |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 662 | levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL) |
| 663 | logging.basicConfig(level=logging.DEBUG, |
| 664 | format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s') |
| 665 | a1 = logging.getLogger('a.b.c') |
| 666 | a2 = logging.getLogger('d.e.f') |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 667 | |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 668 | f = ContextFilter() |
| 669 | a1.addFilter(f) |
| 670 | a2.addFilter(f) |
| 671 | a1.debug('A debug message') |
| 672 | a1.info('An info message with %s', 'some parameters') |
| 673 | for x in range(10): |
| 674 | lvl = choice(levels) |
| 675 | lvlname = logging.getLevelName(lvl) |
| 676 | a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters') |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 677 | |
| 678 | which, when run, produces something like:: |
| 679 | |
| 680 | 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message |
| 681 | 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters |
| 682 | 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 |
| 683 | 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 |
| 684 | 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 |
| 685 | 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 |
| 686 | 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 |
| 687 | 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 |
| 688 | 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 |
| 689 | 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 |
| 690 | 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 |
| 691 | 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 |
| 692 | |
| 693 | |
| 694 | .. _multiple-processes: |
| 695 | |
| 696 | Logging to a single file from multiple processes |
| 697 | ------------------------------------------------ |
| 698 | |
| 699 | Although logging is thread-safe, and logging to a single file from multiple |
| 700 | threads in a single process *is* supported, logging to a single file from |
| 701 | *multiple processes* is *not* supported, because there is no standard way to |
| 702 | serialize access to a single file across multiple processes in Python. If you |
| 703 | need to log to a single file from multiple processes, one way of doing this is |
Vinay Sajip | 67f3977 | 2013-08-17 00:39:42 +0100 | [diff] [blame] | 704 | to have all the processes log to a :class:`~handlers.SocketHandler`, and have a |
| 705 | separate process which implements a socket server which reads from the socket |
| 706 | and logs to file. (If you prefer, you can dedicate one thread in one of the |
| 707 | existing processes to perform this function.) |
| 708 | :ref:`This section <network-logging>` documents this approach in more detail and |
| 709 | includes a working socket receiver which can be used as a starting point for you |
| 710 | to adapt in your own applications. |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 711 | |
| 712 | If you are using a recent version of Python which includes the |
| 713 | :mod:`multiprocessing` module, you could write your own handler which uses the |
Vinay Sajip | 67f3977 | 2013-08-17 00:39:42 +0100 | [diff] [blame] | 714 | :class:`~multiprocessing.Lock` class from this module to serialize access to the |
| 715 | file from your processes. The existing :class:`FileHandler` and subclasses do |
| 716 | not make use of :mod:`multiprocessing` at present, though they may do so in the |
| 717 | future. Note that at present, the :mod:`multiprocessing` module does not provide |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 718 | working lock functionality on all platforms (see |
Georg Brandl | e73778c | 2014-10-29 08:36:35 +0100 | [diff] [blame] | 719 | https://bugs.python.org/issue3770). |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 720 | |
| 721 | .. currentmodule:: logging.handlers |
| 722 | |
| 723 | Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send |
| 724 | all logging events to one of the processes in your multi-process application. |
| 725 | The following example script demonstrates how you can do this; in the example |
| 726 | a separate listener process listens for events sent by other processes and logs |
| 727 | them according to its own logging configuration. Although the example only |
| 728 | demonstrates one way of doing it (for example, you may want to use a listener |
Georg Brandl | 7a0afd3 | 2011-02-07 15:44:27 +0000 | [diff] [blame] | 729 | thread rather than a separate listener process -- the implementation would be |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 730 | analogous) it does allow for completely different logging configurations for |
| 731 | the listener and the other processes in your application, and can be used as |
| 732 | the basis for code meeting your own specific requirements:: |
| 733 | |
| 734 | # You'll need these imports in your own code |
| 735 | import logging |
| 736 | import logging.handlers |
| 737 | import multiprocessing |
| 738 | |
| 739 | # Next two import lines for this demo only |
| 740 | from random import choice, random |
| 741 | import time |
| 742 | |
| 743 | # |
| 744 | # Because you'll want to define the logging configurations for listener and workers, the |
| 745 | # listener and worker process functions take a configurer parameter which is a callable |
| 746 | # for configuring logging for that process. These functions are also passed the queue, |
| 747 | # which they use for communication. |
| 748 | # |
| 749 | # In practice, you can configure the listener however you want, but note that in this |
| 750 | # simple example, the listener does not apply level or filter logic to received records. |
Georg Brandl | 7a0afd3 | 2011-02-07 15:44:27 +0000 | [diff] [blame] | 751 | # In practice, you would probably want to do this logic in the worker processes, to avoid |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 752 | # sending events which would be filtered out between processes. |
| 753 | # |
| 754 | # The size of the rotated files is made small so you can see the results easily. |
| 755 | def listener_configurer(): |
| 756 | root = logging.getLogger() |
Raymond Hettinger | b34705f | 2011-06-26 15:29:06 +0200 | [diff] [blame] | 757 | h = logging.handlers.RotatingFileHandler('mptest.log', 'a', 300, 10) |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 758 | f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s') |
| 759 | h.setFormatter(f) |
| 760 | root.addHandler(h) |
| 761 | |
| 762 | # This is the listener process top-level loop: wait for logging events |
| 763 | # (LogRecords)on the queue and handle them, quit when you get a None for a |
| 764 | # LogRecord. |
| 765 | def listener_process(queue, configurer): |
| 766 | configurer() |
| 767 | while True: |
| 768 | try: |
| 769 | record = queue.get() |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 770 | if record is None: # We send this as a sentinel to tell the listener to quit. |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 771 | break |
| 772 | logger = logging.getLogger(record.name) |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 773 | logger.handle(record) # No level or filter logic applied - just do it! |
Andrew Svetlov | 4739561 | 2012-11-02 22:07:26 +0200 | [diff] [blame] | 774 | except Exception: |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 775 | import sys, traceback |
Vinay Sajip | 6b883a2 | 2012-02-27 11:02:45 +0000 | [diff] [blame] | 776 | print('Whoops! Problem:', file=sys.stderr) |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 777 | traceback.print_exc(file=sys.stderr) |
| 778 | |
| 779 | # Arrays used for random selections in this demo |
| 780 | |
| 781 | LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING, |
| 782 | logging.ERROR, logging.CRITICAL] |
| 783 | |
| 784 | LOGGERS = ['a.b.c', 'd.e.f'] |
| 785 | |
| 786 | MESSAGES = [ |
| 787 | 'Random message #1', |
| 788 | 'Random message #2', |
| 789 | 'Random message #3', |
| 790 | ] |
| 791 | |
| 792 | # The worker configuration is done at the start of the worker process run. |
| 793 | # Note that on Windows you can't rely on fork semantics, so each process |
| 794 | # will run the logging configuration code when it starts. |
| 795 | def worker_configurer(queue): |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 796 | h = logging.handlers.QueueHandler(queue) # Just the one handler needed |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 797 | root = logging.getLogger() |
| 798 | root.addHandler(h) |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 799 | # send all messages, for demo; no other level or filter logic applied. |
| 800 | root.setLevel(logging.DEBUG) |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 801 | |
| 802 | # This is the worker process top-level loop, which just logs ten events with |
| 803 | # random intervening delays before terminating. |
| 804 | # The print messages are just so you know it's doing something! |
| 805 | def worker_process(queue, configurer): |
| 806 | configurer(queue) |
| 807 | name = multiprocessing.current_process().name |
| 808 | print('Worker started: %s' % name) |
| 809 | for i in range(10): |
| 810 | time.sleep(random()) |
| 811 | logger = logging.getLogger(choice(LOGGERS)) |
| 812 | level = choice(LEVELS) |
| 813 | message = choice(MESSAGES) |
| 814 | logger.log(level, message) |
| 815 | print('Worker finished: %s' % name) |
| 816 | |
| 817 | # Here's where the demo gets orchestrated. Create the queue, create and start |
| 818 | # the listener, create ten workers and start them, wait for them to finish, |
| 819 | # then send a None to the queue to tell the listener to finish. |
| 820 | def main(): |
| 821 | queue = multiprocessing.Queue(-1) |
| 822 | listener = multiprocessing.Process(target=listener_process, |
| 823 | args=(queue, listener_configurer)) |
| 824 | listener.start() |
| 825 | workers = [] |
| 826 | for i in range(10): |
| 827 | worker = multiprocessing.Process(target=worker_process, |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 828 | args=(queue, worker_configurer)) |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 829 | workers.append(worker) |
| 830 | worker.start() |
| 831 | for w in workers: |
| 832 | w.join() |
| 833 | queue.put_nowait(None) |
| 834 | listener.join() |
| 835 | |
| 836 | if __name__ == '__main__': |
| 837 | main() |
| 838 | |
Vinay Sajip | e6f1e43 | 2010-12-26 18:47:51 +0000 | [diff] [blame] | 839 | A variant of the above script keeps the logging in the main process, in a |
| 840 | separate thread:: |
| 841 | |
| 842 | import logging |
| 843 | import logging.config |
| 844 | import logging.handlers |
| 845 | from multiprocessing import Process, Queue |
| 846 | import random |
| 847 | import threading |
| 848 | import time |
| 849 | |
| 850 | def logger_thread(q): |
| 851 | while True: |
| 852 | record = q.get() |
| 853 | if record is None: |
| 854 | break |
| 855 | logger = logging.getLogger(record.name) |
| 856 | logger.handle(record) |
| 857 | |
| 858 | |
| 859 | def worker_process(q): |
| 860 | qh = logging.handlers.QueueHandler(q) |
| 861 | root = logging.getLogger() |
| 862 | root.setLevel(logging.DEBUG) |
| 863 | root.addHandler(qh) |
| 864 | levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, |
| 865 | logging.CRITICAL] |
| 866 | loggers = ['foo', 'foo.bar', 'foo.bar.baz', |
| 867 | 'spam', 'spam.ham', 'spam.ham.eggs'] |
| 868 | for i in range(100): |
| 869 | lvl = random.choice(levels) |
| 870 | logger = logging.getLogger(random.choice(loggers)) |
| 871 | logger.log(lvl, 'Message no. %d', i) |
| 872 | |
| 873 | if __name__ == '__main__': |
| 874 | q = Queue() |
| 875 | d = { |
| 876 | 'version': 1, |
| 877 | 'formatters': { |
| 878 | 'detailed': { |
| 879 | 'class': 'logging.Formatter', |
| 880 | 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s' |
| 881 | } |
| 882 | }, |
| 883 | 'handlers': { |
| 884 | 'console': { |
| 885 | 'class': 'logging.StreamHandler', |
| 886 | 'level': 'INFO', |
| 887 | }, |
| 888 | 'file': { |
| 889 | 'class': 'logging.FileHandler', |
| 890 | 'filename': 'mplog.log', |
| 891 | 'mode': 'w', |
| 892 | 'formatter': 'detailed', |
| 893 | }, |
| 894 | 'foofile': { |
| 895 | 'class': 'logging.FileHandler', |
| 896 | 'filename': 'mplog-foo.log', |
| 897 | 'mode': 'w', |
| 898 | 'formatter': 'detailed', |
| 899 | }, |
| 900 | 'errors': { |
| 901 | 'class': 'logging.FileHandler', |
| 902 | 'filename': 'mplog-errors.log', |
| 903 | 'mode': 'w', |
| 904 | 'level': 'ERROR', |
| 905 | 'formatter': 'detailed', |
| 906 | }, |
| 907 | }, |
| 908 | 'loggers': { |
| 909 | 'foo': { |
Serhiy Storchaka | f47036c | 2013-12-24 11:04:36 +0200 | [diff] [blame] | 910 | 'handlers': ['foofile'] |
Vinay Sajip | e6f1e43 | 2010-12-26 18:47:51 +0000 | [diff] [blame] | 911 | } |
| 912 | }, |
| 913 | 'root': { |
| 914 | 'level': 'DEBUG', |
| 915 | 'handlers': ['console', 'file', 'errors'] |
| 916 | }, |
| 917 | } |
| 918 | workers = [] |
| 919 | for i in range(5): |
| 920 | wp = Process(target=worker_process, name='worker %d' % (i + 1), args=(q,)) |
| 921 | workers.append(wp) |
| 922 | wp.start() |
| 923 | logging.config.dictConfig(d) |
| 924 | lp = threading.Thread(target=logger_thread, args=(q,)) |
| 925 | lp.start() |
| 926 | # At this point, the main process could do some useful work of its own |
| 927 | # Once it's done that, it can wait for the workers to terminate... |
| 928 | for wp in workers: |
| 929 | wp.join() |
| 930 | # And now tell the logging thread to finish up, too |
| 931 | q.put(None) |
| 932 | lp.join() |
| 933 | |
| 934 | This variant shows how you can e.g. apply configuration for particular loggers |
| 935 | - e.g. the ``foo`` logger has a special handler which stores all events in the |
| 936 | ``foo`` subsystem in a file ``mplog-foo.log``. This will be used by the logging |
| 937 | machinery in the main process (even though the logging events are generated in |
| 938 | the worker processes) to direct the messages to the appropriate destinations. |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 939 | |
| 940 | Using file rotation |
| 941 | ------------------- |
| 942 | |
| 943 | .. sectionauthor:: Doug Hellmann, Vinay Sajip (changes) |
| 944 | .. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>) |
| 945 | |
| 946 | Sometimes you want to let a log file grow to a certain size, then open a new |
| 947 | file and log to that. You may want to keep a certain number of these files, and |
| 948 | when that many files have been created, rotate the files so that the number of |
Georg Brandl | 7a0afd3 | 2011-02-07 15:44:27 +0000 | [diff] [blame] | 949 | files and the size of the files both remain bounded. For this usage pattern, the |
Vinay Sajip | 67f3977 | 2013-08-17 00:39:42 +0100 | [diff] [blame] | 950 | logging package provides a :class:`~handlers.RotatingFileHandler`:: |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 951 | |
| 952 | import glob |
| 953 | import logging |
| 954 | import logging.handlers |
| 955 | |
| 956 | LOG_FILENAME = 'logging_rotatingfile_example.out' |
| 957 | |
| 958 | # Set up a specific logger with our desired output level |
| 959 | my_logger = logging.getLogger('MyLogger') |
| 960 | my_logger.setLevel(logging.DEBUG) |
| 961 | |
| 962 | # Add the log message handler to the logger |
| 963 | handler = logging.handlers.RotatingFileHandler( |
| 964 | LOG_FILENAME, maxBytes=20, backupCount=5) |
| 965 | |
| 966 | my_logger.addHandler(handler) |
| 967 | |
| 968 | # Log some messages |
| 969 | for i in range(20): |
| 970 | my_logger.debug('i = %d' % i) |
| 971 | |
| 972 | # See what files are created |
| 973 | logfiles = glob.glob('%s*' % LOG_FILENAME) |
| 974 | |
| 975 | for filename in logfiles: |
| 976 | print(filename) |
| 977 | |
| 978 | The result should be 6 separate files, each with part of the log history for the |
| 979 | application:: |
| 980 | |
| 981 | logging_rotatingfile_example.out |
| 982 | logging_rotatingfile_example.out.1 |
| 983 | logging_rotatingfile_example.out.2 |
| 984 | logging_rotatingfile_example.out.3 |
| 985 | logging_rotatingfile_example.out.4 |
| 986 | logging_rotatingfile_example.out.5 |
| 987 | |
| 988 | The most current file is always :file:`logging_rotatingfile_example.out`, |
| 989 | and each time it reaches the size limit it is renamed with the suffix |
| 990 | ``.1``. Each of the existing backup files is renamed to increment the suffix |
| 991 | (``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased. |
| 992 | |
Ezio Melotti | e130a52 | 2011-10-19 10:58:56 +0300 | [diff] [blame] | 993 | Obviously this example sets the log length much too small as an extreme |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 994 | example. You would want to set *maxBytes* to an appropriate value. |
| 995 | |
Vinay Sajip | 6b883a2 | 2012-02-27 11:02:45 +0000 | [diff] [blame] | 996 | .. _format-styles: |
| 997 | |
| 998 | Use of alternative formatting styles |
| 999 | ------------------------------------ |
| 1000 | |
| 1001 | When logging was added to the Python standard library, the only way of |
| 1002 | formatting messages with variable content was to use the %-formatting |
| 1003 | method. Since then, Python has gained two new formatting approaches: |
Vinay Sajip | 39b83ac | 2012-02-28 08:05:23 +0000 | [diff] [blame] | 1004 | :class:`string.Template` (added in Python 2.4) and :meth:`str.format` |
| 1005 | (added in Python 2.6). |
Vinay Sajip | 6b883a2 | 2012-02-27 11:02:45 +0000 | [diff] [blame] | 1006 | |
Vinay Sajip | 39b83ac | 2012-02-28 08:05:23 +0000 | [diff] [blame] | 1007 | Logging (as of 3.2) provides improved support for these two additional |
| 1008 | formatting styles. The :class:`Formatter` class been enhanced to take an |
| 1009 | additional, optional keyword parameter named ``style``. This defaults to |
| 1010 | ``'%'``, but other possible values are ``'{'`` and ``'$'``, which correspond |
Vinay Sajip | 6b883a2 | 2012-02-27 11:02:45 +0000 | [diff] [blame] | 1011 | to the other two formatting styles. Backwards compatibility is maintained by |
| 1012 | default (as you would expect), but by explicitly specifying a style parameter, |
| 1013 | you get the ability to specify format strings which work with |
| 1014 | :meth:`str.format` or :class:`string.Template`. Here's an example console |
| 1015 | session to show the possibilities: |
| 1016 | |
| 1017 | .. code-block:: pycon |
| 1018 | |
| 1019 | >>> import logging |
| 1020 | >>> root = logging.getLogger() |
| 1021 | >>> root.setLevel(logging.DEBUG) |
| 1022 | >>> handler = logging.StreamHandler() |
| 1023 | >>> bf = logging.Formatter('{asctime} {name} {levelname:8s} {message}', |
| 1024 | ... style='{') |
| 1025 | >>> handler.setFormatter(bf) |
| 1026 | >>> root.addHandler(handler) |
| 1027 | >>> logger = logging.getLogger('foo.bar') |
| 1028 | >>> logger.debug('This is a DEBUG message') |
| 1029 | 2010-10-28 15:11:55,341 foo.bar DEBUG This is a DEBUG message |
| 1030 | >>> logger.critical('This is a CRITICAL message') |
| 1031 | 2010-10-28 15:12:11,526 foo.bar CRITICAL This is a CRITICAL message |
| 1032 | >>> df = logging.Formatter('$asctime $name ${levelname} $message', |
| 1033 | ... style='$') |
| 1034 | >>> handler.setFormatter(df) |
| 1035 | >>> logger.debug('This is a DEBUG message') |
| 1036 | 2010-10-28 15:13:06,924 foo.bar DEBUG This is a DEBUG message |
| 1037 | >>> logger.critical('This is a CRITICAL message') |
| 1038 | 2010-10-28 15:13:11,494 foo.bar CRITICAL This is a CRITICAL message |
| 1039 | >>> |
| 1040 | |
| 1041 | Note that the formatting of logging messages for final output to logs is |
| 1042 | completely independent of how an individual logging message is constructed. |
| 1043 | That can still use %-formatting, as shown here:: |
| 1044 | |
| 1045 | >>> logger.error('This is an%s %s %s', 'other,', 'ERROR,', 'message') |
| 1046 | 2010-10-28 15:19:29,833 foo.bar ERROR This is another, ERROR, message |
| 1047 | >>> |
| 1048 | |
| 1049 | Logging calls (``logger.debug()``, ``logger.info()`` etc.) only take |
| 1050 | positional parameters for the actual logging message itself, with keyword |
| 1051 | parameters used only for determining options for how to handle the actual |
| 1052 | logging call (e.g. the ``exc_info`` keyword parameter to indicate that |
| 1053 | traceback information should be logged, or the ``extra`` keyword parameter |
| 1054 | to indicate additional contextual information to be added to the log). So |
| 1055 | you cannot directly make logging calls using :meth:`str.format` or |
| 1056 | :class:`string.Template` syntax, because internally the logging package |
| 1057 | uses %-formatting to merge the format string and the variable arguments. |
| 1058 | There would no changing this while preserving backward compatibility, since |
| 1059 | all logging calls which are out there in existing code will be using %-format |
| 1060 | strings. |
| 1061 | |
| 1062 | There is, however, a way that you can use {}- and $- formatting to construct |
| 1063 | your individual log messages. Recall that for a message you can use an |
| 1064 | arbitrary object as a message format string, and that the logging package will |
| 1065 | call ``str()`` on that object to get the actual format string. Consider the |
| 1066 | following two classes:: |
| 1067 | |
Ezio Melotti | af8838f | 2013-03-11 09:30:21 +0200 | [diff] [blame] | 1068 | class BraceMessage: |
Vinay Sajip | 6b883a2 | 2012-02-27 11:02:45 +0000 | [diff] [blame] | 1069 | def __init__(self, fmt, *args, **kwargs): |
| 1070 | self.fmt = fmt |
| 1071 | self.args = args |
| 1072 | self.kwargs = kwargs |
| 1073 | |
| 1074 | def __str__(self): |
| 1075 | return self.fmt.format(*self.args, **self.kwargs) |
| 1076 | |
Ezio Melotti | af8838f | 2013-03-11 09:30:21 +0200 | [diff] [blame] | 1077 | class DollarMessage: |
Vinay Sajip | 6b883a2 | 2012-02-27 11:02:45 +0000 | [diff] [blame] | 1078 | def __init__(self, fmt, **kwargs): |
| 1079 | self.fmt = fmt |
| 1080 | self.kwargs = kwargs |
| 1081 | |
| 1082 | def __str__(self): |
| 1083 | from string import Template |
| 1084 | return Template(self.fmt).substitute(**self.kwargs) |
| 1085 | |
| 1086 | Either of these can be used in place of a format string, to allow {}- or |
| 1087 | $-formatting to be used to build the actual "message" part which appears in the |
| 1088 | formatted log output in place of "%(message)s" or "{message}" or "$message". |
| 1089 | It's a little unwieldy to use the class names whenever you want to log |
| 1090 | something, but it's quite palatable if you use an alias such as __ (double |
Serhiy Storchaka | 29b0a26 | 2016-12-04 10:20:55 +0200 | [diff] [blame] | 1091 | underscore --- not to be confused with _, the single underscore used as a |
Vinay Sajip | 6b883a2 | 2012-02-27 11:02:45 +0000 | [diff] [blame] | 1092 | synonym/alias for :func:`gettext.gettext` or its brethren). |
| 1093 | |
| 1094 | The above classes are not included in Python, though they're easy enough to |
| 1095 | copy and paste into your own code. They can be used as follows (assuming that |
| 1096 | they're declared in a module called ``wherever``): |
| 1097 | |
| 1098 | .. code-block:: pycon |
| 1099 | |
| 1100 | >>> from wherever import BraceMessage as __ |
Vinay Sajip | 39b83ac | 2012-02-28 08:05:23 +0000 | [diff] [blame] | 1101 | >>> print(__('Message with {0} {name}', 2, name='placeholders')) |
Vinay Sajip | 6b883a2 | 2012-02-27 11:02:45 +0000 | [diff] [blame] | 1102 | Message with 2 placeholders |
| 1103 | >>> class Point: pass |
| 1104 | ... |
| 1105 | >>> p = Point() |
| 1106 | >>> p.x = 0.5 |
| 1107 | >>> p.y = 0.5 |
| 1108 | >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', |
| 1109 | ... point=p)) |
| 1110 | Message with coordinates: (0.50, 0.50) |
| 1111 | >>> from wherever import DollarMessage as __ |
| 1112 | >>> print(__('Message with $num $what', num=2, what='placeholders')) |
| 1113 | Message with 2 placeholders |
| 1114 | >>> |
| 1115 | |
Vinay Sajip | 39b83ac | 2012-02-28 08:05:23 +0000 | [diff] [blame] | 1116 | While the above examples use ``print()`` to show how the formatting works, you |
| 1117 | would of course use ``logger.debug()`` or similar to actually log using this |
| 1118 | approach. |
| 1119 | |
Vinay Sajip | 6b883a2 | 2012-02-27 11:02:45 +0000 | [diff] [blame] | 1120 | One thing to note is that you pay no significant performance penalty with this |
| 1121 | approach: the actual formatting happens not when you make the logging call, but |
| 1122 | when (and if) the logged message is actually about to be output to a log by a |
| 1123 | handler. So the only slightly unusual thing which might trip you up is that the |
| 1124 | parentheses go around the format string and the arguments, not just the format |
| 1125 | string. That's because the __ notation is just syntax sugar for a constructor |
| 1126 | call to one of the XXXMessage classes. |
| 1127 | |
Vinay Sajip | 8028a5c | 2013-03-30 11:56:18 +0000 | [diff] [blame] | 1128 | If you prefer, you can use a :class:`LoggerAdapter` to achieve a similar effect |
| 1129 | to the above, as in the following example:: |
| 1130 | |
| 1131 | import logging |
| 1132 | |
| 1133 | class Message(object): |
| 1134 | def __init__(self, fmt, args): |
| 1135 | self.fmt = fmt |
| 1136 | self.args = args |
| 1137 | |
| 1138 | def __str__(self): |
| 1139 | return self.fmt.format(*self.args) |
| 1140 | |
| 1141 | class StyleAdapter(logging.LoggerAdapter): |
| 1142 | def __init__(self, logger, extra=None): |
| 1143 | super(StyleAdapter, self).__init__(logger, extra or {}) |
| 1144 | |
| 1145 | def log(self, level, msg, *args, **kwargs): |
| 1146 | if self.isEnabledFor(level): |
| 1147 | msg, kwargs = self.process(msg, kwargs) |
| 1148 | self.logger._log(level, Message(msg, args), (), **kwargs) |
| 1149 | |
| 1150 | logger = StyleAdapter(logging.getLogger(__name__)) |
| 1151 | |
| 1152 | def main(): |
| 1153 | logger.debug('Hello, {}', 'world!') |
| 1154 | |
| 1155 | if __name__ == '__main__': |
| 1156 | logging.basicConfig(level=logging.DEBUG) |
| 1157 | main() |
| 1158 | |
| 1159 | The above script should log the message ``Hello, world!`` when run with |
| 1160 | Python 3.2 or later. |
| 1161 | |
Vinay Sajip | 6b883a2 | 2012-02-27 11:02:45 +0000 | [diff] [blame] | 1162 | |
Vinay Sajip | 982f534 | 2012-02-27 11:56:29 +0000 | [diff] [blame] | 1163 | .. currentmodule:: logging |
| 1164 | |
Georg Brandl | e998386 | 2012-02-28 08:21:40 +0100 | [diff] [blame] | 1165 | .. _custom-logrecord: |
Vinay Sajip | 982f534 | 2012-02-27 11:56:29 +0000 | [diff] [blame] | 1166 | |
Vinay Sajip | 9c10d6b | 2013-11-15 20:58:13 +0000 | [diff] [blame] | 1167 | Customizing ``LogRecord`` |
Vinay Sajip | 982f534 | 2012-02-27 11:56:29 +0000 | [diff] [blame] | 1168 | ------------------------- |
| 1169 | |
| 1170 | Every logging event is represented by a :class:`LogRecord` instance. |
| 1171 | When an event is logged and not filtered out by a logger's level, a |
| 1172 | :class:`LogRecord` is created, populated with information about the event and |
| 1173 | then passed to the handlers for that logger (and its ancestors, up to and |
| 1174 | including the logger where further propagation up the hierarchy is disabled). |
| 1175 | Before Python 3.2, there were only two places where this creation was done: |
| 1176 | |
| 1177 | * :meth:`Logger.makeRecord`, which is called in the normal process of |
| 1178 | logging an event. This invoked :class:`LogRecord` directly to create an |
| 1179 | instance. |
| 1180 | * :func:`makeLogRecord`, which is called with a dictionary containing |
| 1181 | attributes to be added to the LogRecord. This is typically invoked when a |
| 1182 | suitable dictionary has been received over the network (e.g. in pickle form |
| 1183 | via a :class:`~handlers.SocketHandler`, or in JSON form via an |
| 1184 | :class:`~handlers.HTTPHandler`). |
| 1185 | |
| 1186 | This has usually meant that if you need to do anything special with a |
| 1187 | :class:`LogRecord`, you've had to do one of the following. |
| 1188 | |
| 1189 | * Create your own :class:`Logger` subclass, which overrides |
| 1190 | :meth:`Logger.makeRecord`, and set it using :func:`~logging.setLoggerClass` |
| 1191 | before any loggers that you care about are instantiated. |
| 1192 | * Add a :class:`Filter` to a logger or handler, which does the |
| 1193 | necessary special manipulation you need when its |
| 1194 | :meth:`~Filter.filter` method is called. |
| 1195 | |
| 1196 | The first approach would be a little unwieldy in the scenario where (say) |
| 1197 | several different libraries wanted to do different things. Each would attempt |
| 1198 | to set its own :class:`Logger` subclass, and the one which did this last would |
| 1199 | win. |
| 1200 | |
| 1201 | The second approach works reasonably well for many cases, but does not allow |
| 1202 | you to e.g. use a specialized subclass of :class:`LogRecord`. Library |
| 1203 | developers can set a suitable filter on their loggers, but they would have to |
| 1204 | remember to do this every time they introduced a new logger (which they would |
Georg Brandl | e998386 | 2012-02-28 08:21:40 +0100 | [diff] [blame] | 1205 | do simply by adding new packages or modules and doing :: |
Vinay Sajip | 982f534 | 2012-02-27 11:56:29 +0000 | [diff] [blame] | 1206 | |
| 1207 | logger = logging.getLogger(__name__) |
| 1208 | |
| 1209 | at module level). It's probably one too many things to think about. Developers |
| 1210 | could also add the filter to a :class:`~logging.NullHandler` attached to their |
| 1211 | top-level logger, but this would not be invoked if an application developer |
Serhiy Storchaka | 29b0a26 | 2016-12-04 10:20:55 +0200 | [diff] [blame] | 1212 | attached a handler to a lower-level library logger --- so output from that |
Vinay Sajip | 982f534 | 2012-02-27 11:56:29 +0000 | [diff] [blame] | 1213 | handler would not reflect the intentions of the library developer. |
| 1214 | |
| 1215 | In Python 3.2 and later, :class:`~logging.LogRecord` creation is done through a |
| 1216 | factory, which you can specify. The factory is just a callable you can set with |
| 1217 | :func:`~logging.setLogRecordFactory`, and interrogate with |
| 1218 | :func:`~logging.getLogRecordFactory`. The factory is invoked with the same |
| 1219 | signature as the :class:`~logging.LogRecord` constructor, as :class:`LogRecord` |
| 1220 | is the default setting for the factory. |
| 1221 | |
| 1222 | This approach allows a custom factory to control all aspects of LogRecord |
| 1223 | creation. For example, you could return a subclass, or just add some additional |
| 1224 | attributes to the record once created, using a pattern similar to this:: |
| 1225 | |
| 1226 | old_factory = logging.getLogRecordFactory() |
| 1227 | |
| 1228 | def record_factory(*args, **kwargs): |
| 1229 | record = old_factory(*args, **kwargs) |
| 1230 | record.custom_attribute = 0xdecafbad |
| 1231 | return record |
| 1232 | |
| 1233 | logging.setLogRecordFactory(record_factory) |
| 1234 | |
| 1235 | This pattern allows different libraries to chain factories together, and as |
| 1236 | long as they don't overwrite each other's attributes or unintentionally |
| 1237 | overwrite the attributes provided as standard, there should be no surprises. |
| 1238 | However, it should be borne in mind that each link in the chain adds run-time |
| 1239 | overhead to all logging operations, and the technique should only be used when |
| 1240 | the use of a :class:`Filter` does not provide the desired result. |
| 1241 | |
| 1242 | |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 1243 | .. _zeromq-handlers: |
| 1244 | |
Vinay Sajip | 7d10129 | 2010-12-26 21:22:33 +0000 | [diff] [blame] | 1245 | Subclassing QueueHandler - a ZeroMQ example |
| 1246 | ------------------------------------------- |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 1247 | |
| 1248 | You can use a :class:`QueueHandler` subclass to send messages to other kinds |
| 1249 | of queues, for example a ZeroMQ 'publish' socket. In the example below,the |
| 1250 | socket is created separately and passed to the handler (as its 'queue'):: |
| 1251 | |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 1252 | import zmq # using pyzmq, the Python binding for ZeroMQ |
| 1253 | import json # for serializing records portably |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 1254 | |
| 1255 | ctx = zmq.Context() |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 1256 | sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value |
| 1257 | sock.bind('tcp://*:5556') # or wherever |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 1258 | |
| 1259 | class ZeroMQSocketHandler(QueueHandler): |
| 1260 | def enqueue(self, record): |
| 1261 | data = json.dumps(record.__dict__) |
| 1262 | self.queue.send(data) |
| 1263 | |
| 1264 | handler = ZeroMQSocketHandler(sock) |
| 1265 | |
| 1266 | |
| 1267 | Of course there are other ways of organizing this, for example passing in the |
| 1268 | data needed by the handler to create the socket:: |
| 1269 | |
| 1270 | class ZeroMQSocketHandler(QueueHandler): |
| 1271 | def __init__(self, uri, socktype=zmq.PUB, ctx=None): |
| 1272 | self.ctx = ctx or zmq.Context() |
| 1273 | socket = zmq.Socket(self.ctx, socktype) |
| 1274 | socket.bind(uri) |
| 1275 | QueueHandler.__init__(self, socket) |
| 1276 | |
| 1277 | def enqueue(self, record): |
| 1278 | data = json.dumps(record.__dict__) |
| 1279 | self.queue.send(data) |
| 1280 | |
| 1281 | def close(self): |
| 1282 | self.queue.close() |
| 1283 | |
| 1284 | |
Vinay Sajip | 7d10129 | 2010-12-26 21:22:33 +0000 | [diff] [blame] | 1285 | Subclassing QueueListener - a ZeroMQ example |
| 1286 | -------------------------------------------- |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 1287 | |
| 1288 | You can also subclass :class:`QueueListener` to get messages from other kinds |
| 1289 | of queues, for example a ZeroMQ 'subscribe' socket. Here's an example:: |
| 1290 | |
| 1291 | class ZeroMQSocketListener(QueueListener): |
| 1292 | def __init__(self, uri, *handlers, **kwargs): |
| 1293 | self.ctx = kwargs.get('ctx') or zmq.Context() |
| 1294 | socket = zmq.Socket(self.ctx, zmq.SUB) |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 1295 | socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 1296 | socket.connect(uri) |
| 1297 | |
| 1298 | def dequeue(self): |
| 1299 | msg = self.queue.recv() |
| 1300 | return logging.makeLogRecord(json.loads(msg)) |
| 1301 | |
| 1302 | |
Vinay Sajip | 7d10129 | 2010-12-26 21:22:33 +0000 | [diff] [blame] | 1303 | .. seealso:: |
Vinay Sajip | c63619b | 2010-12-19 12:56:57 +0000 | [diff] [blame] | 1304 | |
Vinay Sajip | 7d10129 | 2010-12-26 21:22:33 +0000 | [diff] [blame] | 1305 | Module :mod:`logging` |
| 1306 | API reference for the logging module. |
| 1307 | |
| 1308 | Module :mod:`logging.config` |
| 1309 | Configuration API for the logging module. |
| 1310 | |
| 1311 | Module :mod:`logging.handlers` |
| 1312 | Useful handlers included with the logging module. |
| 1313 | |
| 1314 | :ref:`A basic logging tutorial <logging-basic-tutorial>` |
| 1315 | |
| 1316 | :ref:`A more advanced logging tutorial <logging-advanced-tutorial>` |
Vinay Sajip | 631a7e2 | 2011-11-23 14:27:54 +0000 | [diff] [blame] | 1317 | |
| 1318 | |
| 1319 | An example dictionary-based configuration |
| 1320 | ----------------------------------------- |
| 1321 | |
| 1322 | Below is an example of a logging configuration dictionary - it's taken from |
Serhiy Storchaka | 90be733 | 2016-04-11 12:18:56 +0300 | [diff] [blame] | 1323 | the `documentation on the Django project <https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging>`_. |
Vinay Sajip | 67f3977 | 2013-08-17 00:39:42 +0100 | [diff] [blame] | 1324 | This dictionary is passed to :func:`~config.dictConfig` to put the configuration into effect:: |
Vinay Sajip | 631a7e2 | 2011-11-23 14:27:54 +0000 | [diff] [blame] | 1325 | |
| 1326 | LOGGING = { |
| 1327 | 'version': 1, |
| 1328 | 'disable_existing_loggers': True, |
| 1329 | 'formatters': { |
| 1330 | 'verbose': { |
| 1331 | 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' |
| 1332 | }, |
| 1333 | 'simple': { |
| 1334 | 'format': '%(levelname)s %(message)s' |
| 1335 | }, |
| 1336 | }, |
| 1337 | 'filters': { |
| 1338 | 'special': { |
| 1339 | '()': 'project.logging.SpecialFilter', |
| 1340 | 'foo': 'bar', |
| 1341 | } |
| 1342 | }, |
| 1343 | 'handlers': { |
| 1344 | 'null': { |
| 1345 | 'level':'DEBUG', |
| 1346 | 'class':'django.utils.log.NullHandler', |
| 1347 | }, |
| 1348 | 'console':{ |
| 1349 | 'level':'DEBUG', |
| 1350 | 'class':'logging.StreamHandler', |
| 1351 | 'formatter': 'simple' |
| 1352 | }, |
| 1353 | 'mail_admins': { |
| 1354 | 'level': 'ERROR', |
| 1355 | 'class': 'django.utils.log.AdminEmailHandler', |
| 1356 | 'filters': ['special'] |
| 1357 | } |
| 1358 | }, |
| 1359 | 'loggers': { |
| 1360 | 'django': { |
| 1361 | 'handlers':['null'], |
| 1362 | 'propagate': True, |
| 1363 | 'level':'INFO', |
| 1364 | }, |
| 1365 | 'django.request': { |
| 1366 | 'handlers': ['mail_admins'], |
| 1367 | 'level': 'ERROR', |
| 1368 | 'propagate': False, |
| 1369 | }, |
| 1370 | 'myproject.custom': { |
| 1371 | 'handlers': ['console', 'mail_admins'], |
| 1372 | 'level': 'INFO', |
| 1373 | 'filters': ['special'] |
| 1374 | } |
| 1375 | } |
| 1376 | } |
| 1377 | |
| 1378 | For more information about this configuration, you can see the `relevant |
Serhiy Storchaka | 90be733 | 2016-04-11 12:18:56 +0300 | [diff] [blame] | 1379 | section <https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging>`_ |
Vinay Sajip | 631a7e2 | 2011-11-23 14:27:54 +0000 | [diff] [blame] | 1380 | of the Django documentation. |
Vinay Sajip | 23b94d0 | 2012-01-04 12:02:26 +0000 | [diff] [blame] | 1381 | |
| 1382 | .. _cookbook-rotator-namer: |
| 1383 | |
Vinay Sajip | 9c10d6b | 2013-11-15 20:58:13 +0000 | [diff] [blame] | 1384 | Using a rotator and namer to customize log rotation processing |
Vinay Sajip | 23b94d0 | 2012-01-04 12:02:26 +0000 | [diff] [blame] | 1385 | -------------------------------------------------------------- |
| 1386 | |
| 1387 | An example of how you can define a namer and rotator is given in the following |
| 1388 | snippet, which shows zlib-based compression of the log file:: |
| 1389 | |
| 1390 | def namer(name): |
| 1391 | return name + ".gz" |
| 1392 | |
| 1393 | def rotator(source, dest): |
| 1394 | with open(source, "rb") as sf: |
| 1395 | data = sf.read() |
| 1396 | compressed = zlib.compress(data, 9) |
| 1397 | with open(dest, "wb") as df: |
| 1398 | df.write(compressed) |
| 1399 | os.remove(source) |
| 1400 | |
| 1401 | rh = logging.handlers.RotatingFileHandler(...) |
| 1402 | rh.rotator = rotator |
| 1403 | rh.namer = namer |
| 1404 | |
Ezio Melotti | 226231c | 2012-01-18 05:40:00 +0200 | [diff] [blame] | 1405 | These are not "true" .gz files, as they are bare compressed data, with no |
| 1406 | "container" such as you’d find in an actual gzip file. This snippet is just |
Vinay Sajip | 23b94d0 | 2012-01-04 12:02:26 +0000 | [diff] [blame] | 1407 | for illustration purposes. |
| 1408 | |
Vinay Sajip | 0292fa9 | 2012-04-08 01:49:12 +0100 | [diff] [blame] | 1409 | A more elaborate multiprocessing example |
| 1410 | ---------------------------------------- |
| 1411 | |
| 1412 | The following working example shows how logging can be used with multiprocessing |
| 1413 | using configuration files. The configurations are fairly simple, but serve to |
| 1414 | illustrate how more complex ones could be implemented in a real multiprocessing |
| 1415 | scenario. |
| 1416 | |
| 1417 | In the example, the main process spawns a listener process and some worker |
| 1418 | processes. Each of the main process, the listener and the workers have three |
| 1419 | separate configurations (the workers all share the same configuration). We can |
| 1420 | see logging in the main process, how the workers log to a QueueHandler and how |
| 1421 | the listener implements a QueueListener and a more complex logging |
| 1422 | configuration, and arranges to dispatch events received via the queue to the |
| 1423 | handlers specified in the configuration. Note that these configurations are |
| 1424 | purely illustrative, but you should be able to adapt this example to your own |
| 1425 | scenario. |
| 1426 | |
| 1427 | Here's the script - the docstrings and the comments hopefully explain how it |
| 1428 | works:: |
| 1429 | |
| 1430 | import logging |
| 1431 | import logging.config |
| 1432 | import logging.handlers |
| 1433 | from multiprocessing import Process, Queue, Event, current_process |
| 1434 | import os |
| 1435 | import random |
| 1436 | import time |
| 1437 | |
Ezio Melotti | af8838f | 2013-03-11 09:30:21 +0200 | [diff] [blame] | 1438 | class MyHandler: |
Vinay Sajip | 0292fa9 | 2012-04-08 01:49:12 +0100 | [diff] [blame] | 1439 | """ |
| 1440 | A simple handler for logging events. It runs in the listener process and |
| 1441 | dispatches events to loggers based on the name in the received record, |
| 1442 | which then get dispatched, by the logging system, to the handlers |
Vinay Sajip | 838e638 | 2012-04-09 19:46:24 +0100 | [diff] [blame] | 1443 | configured for those loggers. |
Vinay Sajip | 0292fa9 | 2012-04-08 01:49:12 +0100 | [diff] [blame] | 1444 | """ |
| 1445 | def handle(self, record): |
| 1446 | logger = logging.getLogger(record.name) |
| 1447 | # The process name is transformed just to show that it's the listener |
| 1448 | # doing the logging to files and console |
| 1449 | record.processName = '%s (for %s)' % (current_process().name, record.processName) |
| 1450 | logger.handle(record) |
| 1451 | |
| 1452 | def listener_process(q, stop_event, config): |
| 1453 | """ |
| 1454 | This could be done in the main process, but is just done in a separate |
| 1455 | process for illustrative purposes. |
| 1456 | |
| 1457 | This initialises logging according to the specified configuration, |
| 1458 | starts the listener and waits for the main process to signal completion |
| 1459 | via the event. The listener is then stopped, and the process exits. |
| 1460 | """ |
| 1461 | logging.config.dictConfig(config) |
| 1462 | listener = logging.handlers.QueueListener(q, MyHandler()) |
| 1463 | listener.start() |
| 1464 | if os.name == 'posix': |
| 1465 | # On POSIX, the setup logger will have been configured in the |
| 1466 | # parent process, but should have been disabled following the |
| 1467 | # dictConfig call. |
| 1468 | # On Windows, since fork isn't used, the setup logger won't |
| 1469 | # exist in the child, so it would be created and the message |
| 1470 | # would appear - hence the "if posix" clause. |
| 1471 | logger = logging.getLogger('setup') |
| 1472 | logger.critical('Should not appear, because of disabled logger ...') |
| 1473 | stop_event.wait() |
| 1474 | listener.stop() |
| 1475 | |
| 1476 | def worker_process(config): |
| 1477 | """ |
| 1478 | A number of these are spawned for the purpose of illustration. In |
Berker Peksag | 315e104 | 2015-05-19 01:36:55 +0300 | [diff] [blame] | 1479 | practice, they could be a heterogeneous bunch of processes rather than |
Vinay Sajip | 0292fa9 | 2012-04-08 01:49:12 +0100 | [diff] [blame] | 1480 | ones which are identical to each other. |
| 1481 | |
| 1482 | This initialises logging according to the specified configuration, |
| 1483 | and logs a hundred messages with random levels to randomly selected |
| 1484 | loggers. |
| 1485 | |
| 1486 | A small sleep is added to allow other processes a chance to run. This |
| 1487 | is not strictly needed, but it mixes the output from the different |
| 1488 | processes a bit more than if it's left out. |
| 1489 | """ |
| 1490 | logging.config.dictConfig(config) |
| 1491 | levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, |
| 1492 | logging.CRITICAL] |
| 1493 | loggers = ['foo', 'foo.bar', 'foo.bar.baz', |
| 1494 | 'spam', 'spam.ham', 'spam.ham.eggs'] |
| 1495 | if os.name == 'posix': |
| 1496 | # On POSIX, the setup logger will have been configured in the |
| 1497 | # parent process, but should have been disabled following the |
| 1498 | # dictConfig call. |
| 1499 | # On Windows, since fork isn't used, the setup logger won't |
| 1500 | # exist in the child, so it would be created and the message |
| 1501 | # would appear - hence the "if posix" clause. |
| 1502 | logger = logging.getLogger('setup') |
| 1503 | logger.critical('Should not appear, because of disabled logger ...') |
| 1504 | for i in range(100): |
| 1505 | lvl = random.choice(levels) |
| 1506 | logger = logging.getLogger(random.choice(loggers)) |
| 1507 | logger.log(lvl, 'Message no. %d', i) |
| 1508 | time.sleep(0.01) |
| 1509 | |
| 1510 | def main(): |
| 1511 | q = Queue() |
| 1512 | # The main process gets a simple configuration which prints to the console. |
| 1513 | config_initial = { |
| 1514 | 'version': 1, |
| 1515 | 'formatters': { |
| 1516 | 'detailed': { |
| 1517 | 'class': 'logging.Formatter', |
| 1518 | 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s' |
| 1519 | } |
| 1520 | }, |
| 1521 | 'handlers': { |
| 1522 | 'console': { |
| 1523 | 'class': 'logging.StreamHandler', |
| 1524 | 'level': 'INFO', |
| 1525 | }, |
| 1526 | }, |
| 1527 | 'root': { |
| 1528 | 'level': 'DEBUG', |
| 1529 | 'handlers': ['console'] |
| 1530 | }, |
| 1531 | } |
| 1532 | # The worker process configuration is just a QueueHandler attached to the |
| 1533 | # root logger, which allows all messages to be sent to the queue. |
| 1534 | # We disable existing loggers to disable the "setup" logger used in the |
| 1535 | # parent process. This is needed on POSIX because the logger will |
| 1536 | # be there in the child following a fork(). |
| 1537 | config_worker = { |
| 1538 | 'version': 1, |
| 1539 | 'disable_existing_loggers': True, |
| 1540 | 'handlers': { |
| 1541 | 'queue': { |
| 1542 | 'class': 'logging.handlers.QueueHandler', |
| 1543 | 'queue': q, |
| 1544 | }, |
| 1545 | }, |
| 1546 | 'root': { |
| 1547 | 'level': 'DEBUG', |
| 1548 | 'handlers': ['queue'] |
| 1549 | }, |
| 1550 | } |
| 1551 | # The listener process configuration shows that the full flexibility of |
| 1552 | # logging configuration is available to dispatch events to handlers however |
| 1553 | # you want. |
| 1554 | # We disable existing loggers to disable the "setup" logger used in the |
| 1555 | # parent process. This is needed on POSIX because the logger will |
| 1556 | # be there in the child following a fork(). |
| 1557 | config_listener = { |
| 1558 | 'version': 1, |
| 1559 | 'disable_existing_loggers': True, |
| 1560 | 'formatters': { |
| 1561 | 'detailed': { |
| 1562 | 'class': 'logging.Formatter', |
| 1563 | 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s' |
| 1564 | }, |
| 1565 | 'simple': { |
| 1566 | 'class': 'logging.Formatter', |
| 1567 | 'format': '%(name)-15s %(levelname)-8s %(processName)-10s %(message)s' |
| 1568 | } |
| 1569 | }, |
| 1570 | 'handlers': { |
| 1571 | 'console': { |
| 1572 | 'class': 'logging.StreamHandler', |
| 1573 | 'level': 'INFO', |
| 1574 | 'formatter': 'simple', |
| 1575 | }, |
| 1576 | 'file': { |
| 1577 | 'class': 'logging.FileHandler', |
| 1578 | 'filename': 'mplog.log', |
| 1579 | 'mode': 'w', |
| 1580 | 'formatter': 'detailed', |
| 1581 | }, |
| 1582 | 'foofile': { |
| 1583 | 'class': 'logging.FileHandler', |
| 1584 | 'filename': 'mplog-foo.log', |
| 1585 | 'mode': 'w', |
| 1586 | 'formatter': 'detailed', |
| 1587 | }, |
| 1588 | 'errors': { |
| 1589 | 'class': 'logging.FileHandler', |
| 1590 | 'filename': 'mplog-errors.log', |
| 1591 | 'mode': 'w', |
| 1592 | 'level': 'ERROR', |
| 1593 | 'formatter': 'detailed', |
| 1594 | }, |
| 1595 | }, |
| 1596 | 'loggers': { |
| 1597 | 'foo': { |
Serhiy Storchaka | f47036c | 2013-12-24 11:04:36 +0200 | [diff] [blame] | 1598 | 'handlers': ['foofile'] |
Vinay Sajip | 0292fa9 | 2012-04-08 01:49:12 +0100 | [diff] [blame] | 1599 | } |
| 1600 | }, |
| 1601 | 'root': { |
| 1602 | 'level': 'DEBUG', |
| 1603 | 'handlers': ['console', 'file', 'errors'] |
| 1604 | }, |
| 1605 | } |
| 1606 | # Log some initial events, just to show that logging in the parent works |
| 1607 | # normally. |
| 1608 | logging.config.dictConfig(config_initial) |
| 1609 | logger = logging.getLogger('setup') |
| 1610 | logger.info('About to create workers ...') |
| 1611 | workers = [] |
| 1612 | for i in range(5): |
| 1613 | wp = Process(target=worker_process, name='worker %d' % (i + 1), |
| 1614 | args=(config_worker,)) |
| 1615 | workers.append(wp) |
| 1616 | wp.start() |
| 1617 | logger.info('Started worker: %s', wp.name) |
| 1618 | logger.info('About to create listener ...') |
| 1619 | stop_event = Event() |
| 1620 | lp = Process(target=listener_process, name='listener', |
| 1621 | args=(q, stop_event, config_listener)) |
| 1622 | lp.start() |
| 1623 | logger.info('Started listener') |
| 1624 | # We now hang around for the workers to finish their work. |
| 1625 | for wp in workers: |
| 1626 | wp.join() |
| 1627 | # Workers all done, listening can now stop. |
| 1628 | # Logging in the parent still works normally. |
| 1629 | logger.info('Telling listener to stop ...') |
| 1630 | stop_event.set() |
| 1631 | lp.join() |
| 1632 | logger.info('All done.') |
| 1633 | |
| 1634 | if __name__ == '__main__': |
| 1635 | main() |
| 1636 | |
Vinay Sajip | b00e8f1 | 2012-04-16 15:28:50 +0100 | [diff] [blame] | 1637 | |
| 1638 | Inserting a BOM into messages sent to a SysLogHandler |
| 1639 | ----------------------------------------------------- |
| 1640 | |
Serhiy Storchaka | 6dff020 | 2016-05-07 10:49:07 +0300 | [diff] [blame] | 1641 | `RFC 5424 <https://tools.ietf.org/html/rfc5424>`_ requires that a |
Vinay Sajip | b00e8f1 | 2012-04-16 15:28:50 +0100 | [diff] [blame] | 1642 | Unicode message be sent to a syslog daemon as a set of bytes which have the |
| 1643 | following structure: an optional pure-ASCII component, followed by a UTF-8 Byte |
| 1644 | Order Mark (BOM), followed by Unicode encoded using UTF-8. (See the `relevant |
Serhiy Storchaka | 6dff020 | 2016-05-07 10:49:07 +0300 | [diff] [blame] | 1645 | section of the specification <https://tools.ietf.org/html/rfc5424#section-6>`_.) |
Vinay Sajip | b00e8f1 | 2012-04-16 15:28:50 +0100 | [diff] [blame] | 1646 | |
Vinay Sajip | 62930e1 | 2012-04-17 00:40:48 +0100 | [diff] [blame] | 1647 | In Python 3.1, code was added to |
Vinay Sajip | b00e8f1 | 2012-04-16 15:28:50 +0100 | [diff] [blame] | 1648 | :class:`~logging.handlers.SysLogHandler` to insert a BOM into the message, but |
| 1649 | unfortunately, it was implemented incorrectly, with the BOM appearing at the |
| 1650 | beginning of the message and hence not allowing any pure-ASCII component to |
| 1651 | appear before it. |
| 1652 | |
| 1653 | As this behaviour is broken, the incorrect BOM insertion code is being removed |
Vinay Sajip | 62930e1 | 2012-04-17 00:40:48 +0100 | [diff] [blame] | 1654 | from Python 3.2.4 and later. However, it is not being replaced, and if you |
Vinay Sajip | a58d668 | 2012-07-27 10:54:10 +0100 | [diff] [blame] | 1655 | want to produce RFC 5424-compliant messages which include a BOM, an optional |
Vinay Sajip | b00e8f1 | 2012-04-16 15:28:50 +0100 | [diff] [blame] | 1656 | pure-ASCII sequence before it and arbitrary Unicode after it, encoded using |
| 1657 | UTF-8, then you need to do the following: |
| 1658 | |
| 1659 | #. Attach a :class:`~logging.Formatter` instance to your |
| 1660 | :class:`~logging.handlers.SysLogHandler` instance, with a format string |
| 1661 | such as:: |
| 1662 | |
Vinay Sajip | 59b9a79 | 2012-04-16 15:46:18 +0100 | [diff] [blame] | 1663 | 'ASCII section\ufeffUnicode section' |
Vinay Sajip | b00e8f1 | 2012-04-16 15:28:50 +0100 | [diff] [blame] | 1664 | |
Georg Brandl | d50fe72 | 2013-03-23 16:00:41 +0100 | [diff] [blame] | 1665 | The Unicode code point U+FEFF, when encoded using UTF-8, will be |
Vinay Sajip | 59b9a79 | 2012-04-16 15:46:18 +0100 | [diff] [blame] | 1666 | encoded as a UTF-8 BOM -- the byte-string ``b'\xef\xbb\xbf'``. |
Vinay Sajip | b00e8f1 | 2012-04-16 15:28:50 +0100 | [diff] [blame] | 1667 | |
| 1668 | #. Replace the ASCII section with whatever placeholders you like, but make sure |
| 1669 | that the data that appears in there after substitution is always ASCII (that |
| 1670 | way, it will remain unchanged after UTF-8 encoding). |
| 1671 | |
| 1672 | #. Replace the Unicode section with whatever placeholders you like; if the data |
Vinay Sajip | a58d668 | 2012-07-27 10:54:10 +0100 | [diff] [blame] | 1673 | which appears there after substitution contains characters outside the ASCII |
| 1674 | range, that's fine -- it will be encoded using UTF-8. |
Vinay Sajip | b00e8f1 | 2012-04-16 15:28:50 +0100 | [diff] [blame] | 1675 | |
Vinay Sajip | 59b9a79 | 2012-04-16 15:46:18 +0100 | [diff] [blame] | 1676 | The formatted message *will* be encoded using UTF-8 encoding by |
| 1677 | ``SysLogHandler``. If you follow the above rules, you should be able to produce |
Vinay Sajip | b00e8f1 | 2012-04-16 15:28:50 +0100 | [diff] [blame] | 1678 | RFC 5424-compliant messages. If you don't, logging may not complain, but your |
| 1679 | messages will not be RFC 5424-compliant, and your syslog daemon may complain. |
| 1680 | |
Vinay Sajip | 4b88d6c | 2013-01-22 15:57:39 +0000 | [diff] [blame] | 1681 | |
| 1682 | Implementing structured logging |
| 1683 | ------------------------------- |
| 1684 | |
| 1685 | Although most logging messages are intended for reading by humans, and thus not |
| 1686 | readily machine-parseable, there might be cirumstances where you want to output |
| 1687 | messages in a structured format which *is* capable of being parsed by a program |
Vinay Sajip | 3d9e972 | 2013-01-23 09:31:19 +0000 | [diff] [blame] | 1688 | (without needing complex regular expressions to parse the log message). This is |
Vinay Sajip | 4b88d6c | 2013-01-22 15:57:39 +0000 | [diff] [blame] | 1689 | straightforward to achieve using the logging package. There are a number of |
| 1690 | ways in which this could be achieved, but the following is a simple approach |
| 1691 | which uses JSON to serialise the event in a machine-parseable manner:: |
| 1692 | |
| 1693 | import json |
| 1694 | import logging |
| 1695 | |
| 1696 | class StructuredMessage(object): |
| 1697 | def __init__(self, message, **kwargs): |
| 1698 | self.message = message |
| 1699 | self.kwargs = kwargs |
| 1700 | |
| 1701 | def __str__(self): |
| 1702 | return '%s >>> %s' % (self.message, json.dumps(self.kwargs)) |
| 1703 | |
| 1704 | _ = StructuredMessage # optional, to improve readability |
| 1705 | |
| 1706 | logging.basicConfig(level=logging.INFO, format='%(message)s') |
| 1707 | logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456)) |
| 1708 | |
| 1709 | If the above script is run, it prints:: |
| 1710 | |
| 1711 | message 1 >>> {"fnum": 123.456, "num": 123, "bar": "baz", "foo": "bar"} |
| 1712 | |
Vinay Sajip | 3d9e972 | 2013-01-23 09:31:19 +0000 | [diff] [blame] | 1713 | Note that the order of items might be different according to the version of |
| 1714 | Python used. |
| 1715 | |
Vinay Sajip | 4b88d6c | 2013-01-22 15:57:39 +0000 | [diff] [blame] | 1716 | If you need more specialised processing, you can use a custom JSON encoder, |
| 1717 | as in the following complete example:: |
| 1718 | |
| 1719 | from __future__ import unicode_literals |
| 1720 | |
| 1721 | import json |
| 1722 | import logging |
| 1723 | |
Vinay Sajip | 3d9e972 | 2013-01-23 09:31:19 +0000 | [diff] [blame] | 1724 | # This next bit is to ensure the script runs unchanged on 2.x and 3.x |
Vinay Sajip | 4b88d6c | 2013-01-22 15:57:39 +0000 | [diff] [blame] | 1725 | try: |
| 1726 | unicode |
| 1727 | except NameError: |
| 1728 | unicode = str |
| 1729 | |
| 1730 | class Encoder(json.JSONEncoder): |
| 1731 | def default(self, o): |
| 1732 | if isinstance(o, set): |
| 1733 | return tuple(o) |
| 1734 | elif isinstance(o, unicode): |
| 1735 | return o.encode('unicode_escape').decode('ascii') |
| 1736 | return super(Encoder, self).default(o) |
| 1737 | |
| 1738 | class StructuredMessage(object): |
| 1739 | def __init__(self, message, **kwargs): |
| 1740 | self.message = message |
| 1741 | self.kwargs = kwargs |
| 1742 | |
| 1743 | def __str__(self): |
| 1744 | s = Encoder().encode(self.kwargs) |
| 1745 | return '%s >>> %s' % (self.message, s) |
| 1746 | |
Vinay Sajip | 3d9e972 | 2013-01-23 09:31:19 +0000 | [diff] [blame] | 1747 | _ = StructuredMessage # optional, to improve readability |
Vinay Sajip | 4b88d6c | 2013-01-22 15:57:39 +0000 | [diff] [blame] | 1748 | |
| 1749 | def main(): |
| 1750 | logging.basicConfig(level=logging.INFO, format='%(message)s') |
Raymond Hettinger | df1b699 | 2014-11-09 15:56:33 -0800 | [diff] [blame] | 1751 | logging.info(_('message 1', set_value={1, 2, 3}, snowman='\u2603')) |
Vinay Sajip | 4b88d6c | 2013-01-22 15:57:39 +0000 | [diff] [blame] | 1752 | |
| 1753 | if __name__ == '__main__': |
| 1754 | main() |
| 1755 | |
| 1756 | When the above script is run, it prints:: |
| 1757 | |
| 1758 | message 1 >>> {"snowman": "\u2603", "set_value": [1, 2, 3]} |
| 1759 | |
Vinay Sajip | 3d9e972 | 2013-01-23 09:31:19 +0000 | [diff] [blame] | 1760 | Note that the order of items might be different according to the version of |
| 1761 | Python used. |
| 1762 | |
Vinay Sajip | 554f22f | 2014-02-03 11:51:45 +0000 | [diff] [blame] | 1763 | |
| 1764 | .. _custom-handlers: |
| 1765 | |
Vinay Sajip | 2c1adcb | 2013-11-05 10:02:21 +0000 | [diff] [blame] | 1766 | .. currentmodule:: logging.config |
| 1767 | |
Vinay Sajip | 9c10d6b | 2013-11-15 20:58:13 +0000 | [diff] [blame] | 1768 | Customizing handlers with :func:`dictConfig` |
Vinay Sajip | 2c1adcb | 2013-11-05 10:02:21 +0000 | [diff] [blame] | 1769 | -------------------------------------------- |
| 1770 | |
Vinay Sajip | 9c10d6b | 2013-11-15 20:58:13 +0000 | [diff] [blame] | 1771 | There are times when you want to customize logging handlers in particular ways, |
Vinay Sajip | 2c1adcb | 2013-11-05 10:02:21 +0000 | [diff] [blame] | 1772 | and if you use :func:`dictConfig` you may be able to do this without |
| 1773 | subclassing. As an example, consider that you may want to set the ownership of a |
| 1774 | log file. On POSIX, this is easily done using :func:`shutil.chown`, but the file |
Vinay Sajip | 9c10d6b | 2013-11-15 20:58:13 +0000 | [diff] [blame] | 1775 | handlers in the stdlib don't offer built-in support. You can customize handler |
Vinay Sajip | 2c1adcb | 2013-11-05 10:02:21 +0000 | [diff] [blame] | 1776 | creation using a plain function such as:: |
| 1777 | |
| 1778 | def owned_file_handler(filename, mode='a', encoding=None, owner=None): |
| 1779 | if owner: |
| 1780 | if not os.path.exists(filename): |
| 1781 | open(filename, 'a').close() |
| 1782 | shutil.chown(filename, *owner) |
| 1783 | return logging.FileHandler(filename, mode, encoding) |
| 1784 | |
| 1785 | You can then specify, in a logging configuration passed to :func:`dictConfig`, |
| 1786 | that a logging handler be created by calling this function:: |
| 1787 | |
| 1788 | LOGGING = { |
| 1789 | 'version': 1, |
| 1790 | 'disable_existing_loggers': False, |
| 1791 | 'formatters': { |
| 1792 | 'default': { |
| 1793 | 'format': '%(asctime)s %(levelname)s %(name)s %(message)s' |
| 1794 | }, |
| 1795 | }, |
| 1796 | 'handlers': { |
| 1797 | 'file':{ |
| 1798 | # The values below are popped from this dictionary and |
| 1799 | # used to create the handler, set the handler's level and |
| 1800 | # its formatter. |
| 1801 | '()': owned_file_handler, |
| 1802 | 'level':'DEBUG', |
| 1803 | 'formatter': 'default', |
| 1804 | # The values below are passed to the handler creator callable |
| 1805 | # as keyword arguments. |
| 1806 | 'owner': ['pulse', 'pulse'], |
| 1807 | 'filename': 'chowntest.log', |
| 1808 | 'mode': 'w', |
| 1809 | 'encoding': 'utf-8', |
| 1810 | }, |
| 1811 | }, |
| 1812 | 'root': { |
| 1813 | 'handlers': ['file'], |
| 1814 | 'level': 'DEBUG', |
| 1815 | }, |
| 1816 | } |
| 1817 | |
| 1818 | In this example I am setting the ownership using the ``pulse`` user and group, |
| 1819 | just for the purposes of illustration. Putting it together into a working |
| 1820 | script, ``chowntest.py``:: |
| 1821 | |
| 1822 | import logging, logging.config, os, shutil |
| 1823 | |
| 1824 | def owned_file_handler(filename, mode='a', encoding=None, owner=None): |
| 1825 | if owner: |
| 1826 | if not os.path.exists(filename): |
| 1827 | open(filename, 'a').close() |
| 1828 | shutil.chown(filename, *owner) |
| 1829 | return logging.FileHandler(filename, mode, encoding) |
| 1830 | |
| 1831 | LOGGING = { |
| 1832 | 'version': 1, |
| 1833 | 'disable_existing_loggers': False, |
| 1834 | 'formatters': { |
| 1835 | 'default': { |
| 1836 | 'format': '%(asctime)s %(levelname)s %(name)s %(message)s' |
| 1837 | }, |
| 1838 | }, |
| 1839 | 'handlers': { |
| 1840 | 'file':{ |
| 1841 | # The values below are popped from this dictionary and |
| 1842 | # used to create the handler, set the handler's level and |
| 1843 | # its formatter. |
| 1844 | '()': owned_file_handler, |
| 1845 | 'level':'DEBUG', |
| 1846 | 'formatter': 'default', |
| 1847 | # The values below are passed to the handler creator callable |
| 1848 | # as keyword arguments. |
| 1849 | 'owner': ['pulse', 'pulse'], |
| 1850 | 'filename': 'chowntest.log', |
| 1851 | 'mode': 'w', |
| 1852 | 'encoding': 'utf-8', |
| 1853 | }, |
| 1854 | }, |
| 1855 | 'root': { |
| 1856 | 'handlers': ['file'], |
| 1857 | 'level': 'DEBUG', |
| 1858 | }, |
| 1859 | } |
| 1860 | |
| 1861 | logging.config.dictConfig(LOGGING) |
| 1862 | logger = logging.getLogger('mylogger') |
| 1863 | logger.debug('A debug message') |
| 1864 | |
Martin Panter | 1050d2d | 2016-07-26 11:18:21 +0200 | [diff] [blame] | 1865 | To run this, you will probably need to run as ``root``: |
| 1866 | |
| 1867 | .. code-block:: shell-session |
Vinay Sajip | 2c1adcb | 2013-11-05 10:02:21 +0000 | [diff] [blame] | 1868 | |
| 1869 | $ sudo python3.3 chowntest.py |
| 1870 | $ cat chowntest.log |
| 1871 | 2013-11-05 09:34:51,128 DEBUG mylogger A debug message |
| 1872 | $ ls -l chowntest.log |
| 1873 | -rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log |
| 1874 | |
| 1875 | Note that this example uses Python 3.3 because that's where :func:`shutil.chown` |
| 1876 | makes an appearance. This approach should work with any Python version that |
| 1877 | supports :func:`dictConfig` - namely, Python 2.7, 3.2 or later. With pre-3.3 |
| 1878 | versions, you would need to implement the actual ownership change using e.g. |
| 1879 | :func:`os.chown`. |
| 1880 | |
| 1881 | In practice, the handler-creating function may be in a utility module somewhere |
| 1882 | in your project. Instead of the line in the configuration:: |
| 1883 | |
| 1884 | '()': owned_file_handler, |
| 1885 | |
| 1886 | you could use e.g.:: |
| 1887 | |
| 1888 | '()': 'ext://project.util.owned_file_handler', |
| 1889 | |
| 1890 | where ``project.util`` can be replaced with the actual name of the package |
| 1891 | where the function resides. In the above working script, using |
| 1892 | ``'ext://__main__.owned_file_handler'`` should work. Here, the actual callable |
| 1893 | is resolved by :func:`dictConfig` from the ``ext://`` specification. |
| 1894 | |
| 1895 | This example hopefully also points the way to how you could implement other |
| 1896 | types of file change - e.g. setting specific POSIX permission bits - in the |
| 1897 | same way, using :func:`os.chmod`. |
| 1898 | |
| 1899 | Of course, the approach could also be extended to types of handler other than a |
| 1900 | :class:`~logging.FileHandler` - for example, one of the rotating file handlers, |
| 1901 | or a different type of handler altogether. |
| 1902 | |
Vinay Sajip | cbefe3b | 2014-01-15 15:09:05 +0000 | [diff] [blame] | 1903 | |
| 1904 | .. currentmodule:: logging |
| 1905 | |
| 1906 | .. _formatting-styles: |
| 1907 | |
| 1908 | Using particular formatting styles throughout your application |
| 1909 | -------------------------------------------------------------- |
| 1910 | |
| 1911 | In Python 3.2, the :class:`~logging.Formatter` gained a ``style`` keyword |
| 1912 | parameter which, while defaulting to ``%`` for backward compatibility, allowed |
| 1913 | the specification of ``{`` or ``$`` to support the formatting approaches |
| 1914 | supported by :meth:`str.format` and :class:`string.Template`. Note that this |
| 1915 | governs the formatting of logging messages for final output to logs, and is |
| 1916 | completely orthogonal to how an individual logging message is constructed. |
| 1917 | |
| 1918 | Logging calls (:meth:`~Logger.debug`, :meth:`~Logger.info` etc.) only take |
| 1919 | positional parameters for the actual logging message itself, with keyword |
| 1920 | parameters used only for determining options for how to handle the logging call |
| 1921 | (e.g. the ``exc_info`` keyword parameter to indicate that traceback information |
| 1922 | should be logged, or the ``extra`` keyword parameter to indicate additional |
| 1923 | contextual information to be added to the log). So you cannot directly make |
| 1924 | logging calls using :meth:`str.format` or :class:`string.Template` syntax, |
| 1925 | because internally the logging package uses %-formatting to merge the format |
| 1926 | string and the variable arguments. There would no changing this while preserving |
| 1927 | backward compatibility, since all logging calls which are out there in existing |
| 1928 | code will be using %-format strings. |
| 1929 | |
| 1930 | There have been suggestions to associate format styles with specific loggers, |
| 1931 | but that approach also runs into backward compatibility problems because any |
| 1932 | existing code could be using a given logger name and using %-formatting. |
| 1933 | |
| 1934 | For logging to work interoperably between any third-party libraries and your |
| 1935 | code, decisions about formatting need to be made at the level of the |
| 1936 | individual logging call. This opens up a couple of ways in which alternative |
| 1937 | formatting styles can be accommodated. |
| 1938 | |
| 1939 | |
| 1940 | Using LogRecord factories |
| 1941 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1942 | |
| 1943 | In Python 3.2, along with the :class:`~logging.Formatter` changes mentioned |
| 1944 | above, the logging package gained the ability to allow users to set their own |
| 1945 | :class:`LogRecord` subclasses, using the :func:`setLogRecordFactory` function. |
| 1946 | You can use this to set your own subclass of :class:`LogRecord`, which does the |
| 1947 | Right Thing by overriding the :meth:`~LogRecord.getMessage` method. The base |
| 1948 | class implementation of this method is where the ``msg % args`` formatting |
| 1949 | happens, and where you can substitute your alternate formatting; however, you |
| 1950 | should be careful to support all formatting styles and allow %-formatting as |
| 1951 | the default, to ensure interoperability with other code. Care should also be |
| 1952 | taken to call ``str(self.msg)``, just as the base implementation does. |
| 1953 | |
| 1954 | Refer to the reference documentation on :func:`setLogRecordFactory` and |
| 1955 | :class:`LogRecord` for more information. |
| 1956 | |
| 1957 | |
| 1958 | Using custom message objects |
| 1959 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1960 | |
| 1961 | There is another, perhaps simpler way that you can use {}- and $- formatting to |
| 1962 | construct your individual log messages. You may recall (from |
| 1963 | :ref:`arbitrary-object-messages`) that when logging you can use an arbitrary |
| 1964 | object as a message format string, and that the logging package will call |
| 1965 | :func:`str` on that object to get the actual format string. Consider the |
| 1966 | following two classes:: |
| 1967 | |
| 1968 | class BraceMessage(object): |
| 1969 | def __init__(self, fmt, *args, **kwargs): |
| 1970 | self.fmt = fmt |
| 1971 | self.args = args |
| 1972 | self.kwargs = kwargs |
| 1973 | |
| 1974 | def __str__(self): |
| 1975 | return self.fmt.format(*self.args, **self.kwargs) |
| 1976 | |
| 1977 | class DollarMessage(object): |
| 1978 | def __init__(self, fmt, **kwargs): |
| 1979 | self.fmt = fmt |
| 1980 | self.kwargs = kwargs |
| 1981 | |
| 1982 | def __str__(self): |
| 1983 | from string import Template |
| 1984 | return Template(self.fmt).substitute(**self.kwargs) |
| 1985 | |
| 1986 | Either of these can be used in place of a format string, to allow {}- or |
| 1987 | $-formatting to be used to build the actual "message" part which appears in the |
| 1988 | formatted log output in place of “%(message)s” or “{message}” or “$message”. |
| 1989 | If you find it a little unwieldy to use the class names whenever you want to log |
| 1990 | something, you can make it more palatable if you use an alias such as ``M`` or |
| 1991 | ``_`` for the message (or perhaps ``__``, if you are using ``_`` for |
| 1992 | localization). |
| 1993 | |
Vinay Sajip | eb14dec | 2014-01-17 18:36:02 +0000 | [diff] [blame] | 1994 | Examples of this approach are given below. Firstly, formatting with |
| 1995 | :meth:`str.format`:: |
| 1996 | |
| 1997 | >>> __ = BraceMessage |
| 1998 | >>> print(__('Message with {0} {1}', 2, 'placeholders')) |
| 1999 | Message with 2 placeholders |
| 2000 | >>> class Point: pass |
| 2001 | ... |
| 2002 | >>> p = Point() |
| 2003 | >>> p.x = 0.5 |
| 2004 | >>> p.y = 0.5 |
| 2005 | >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', point=p)) |
| 2006 | Message with coordinates: (0.50, 0.50) |
| 2007 | |
| 2008 | Secondly, formatting with :class:`string.Template`:: |
| 2009 | |
| 2010 | >>> __ = DollarMessage |
| 2011 | >>> print(__('Message with $num $what', num=2, what='placeholders')) |
| 2012 | Message with 2 placeholders |
| 2013 | >>> |
| 2014 | |
| 2015 | One thing to note is that you pay no significant performance penalty with this |
| 2016 | approach: the actual formatting happens not when you make the logging call, but |
| 2017 | when (and if) the logged message is actually about to be output to a log by a |
| 2018 | handler. So the only slightly unusual thing which might trip you up is that the |
| 2019 | parentheses go around the format string and the arguments, not just the format |
| 2020 | string. That’s because the __ notation is just syntax sugar for a constructor |
| 2021 | call to one of the ``XXXMessage`` classes shown above. |
Vinay Sajip | 554f22f | 2014-02-03 11:51:45 +0000 | [diff] [blame] | 2022 | |
| 2023 | |
| 2024 | .. _filters-dictconfig: |
| 2025 | |
| 2026 | .. currentmodule:: logging.config |
| 2027 | |
| 2028 | Configuring filters with :func:`dictConfig` |
| 2029 | ------------------------------------------- |
| 2030 | |
| 2031 | You *can* configure filters using :func:`~logging.config.dictConfig`, though it |
| 2032 | might not be obvious at first glance how to do it (hence this recipe). Since |
| 2033 | :class:`~logging.Filter` is the only filter class included in the standard |
| 2034 | library, and it is unlikely to cater to many requirements (it's only there as a |
| 2035 | base class), you will typically need to define your own :class:`~logging.Filter` |
| 2036 | subclass with an overridden :meth:`~logging.Filter.filter` method. To do this, |
| 2037 | specify the ``()`` key in the configuration dictionary for the filter, |
| 2038 | specifying a callable which will be used to create the filter (a class is the |
| 2039 | most obvious, but you can provide any callable which returns a |
| 2040 | :class:`~logging.Filter` instance). Here is a complete example:: |
| 2041 | |
| 2042 | import logging |
| 2043 | import logging.config |
| 2044 | import sys |
| 2045 | |
| 2046 | class MyFilter(logging.Filter): |
| 2047 | def __init__(self, param=None): |
| 2048 | self.param = param |
| 2049 | |
| 2050 | def filter(self, record): |
| 2051 | if self.param is None: |
| 2052 | allow = True |
| 2053 | else: |
| 2054 | allow = self.param not in record.msg |
| 2055 | if allow: |
| 2056 | record.msg = 'changed: ' + record.msg |
| 2057 | return allow |
| 2058 | |
| 2059 | LOGGING = { |
| 2060 | 'version': 1, |
| 2061 | 'filters': { |
| 2062 | 'myfilter': { |
| 2063 | '()': MyFilter, |
| 2064 | 'param': 'noshow', |
| 2065 | } |
| 2066 | }, |
| 2067 | 'handlers': { |
| 2068 | 'console': { |
| 2069 | 'class': 'logging.StreamHandler', |
| 2070 | 'filters': ['myfilter'] |
| 2071 | } |
| 2072 | }, |
| 2073 | 'root': { |
| 2074 | 'level': 'DEBUG', |
| 2075 | 'handlers': ['console'] |
| 2076 | }, |
| 2077 | } |
| 2078 | |
| 2079 | if __name__ == '__main__': |
| 2080 | logging.config.dictConfig(LOGGING) |
| 2081 | logging.debug('hello') |
| 2082 | logging.debug('hello - noshow') |
| 2083 | |
| 2084 | This example shows how you can pass configuration data to the callable which |
| 2085 | constructs the instance, in the form of keyword parameters. When run, the above |
| 2086 | script will print:: |
| 2087 | |
| 2088 | changed: hello |
| 2089 | |
| 2090 | which shows that the filter is working as configured. |
| 2091 | |
| 2092 | A couple of extra points to note: |
| 2093 | |
| 2094 | * If you can't refer to the callable directly in the configuration (e.g. if it |
| 2095 | lives in a different module, and you can't import it directly where the |
| 2096 | configuration dictionary is), you can use the form ``ext://...`` as described |
| 2097 | in :ref:`logging-config-dict-externalobj`. For example, you could have used |
| 2098 | the text ``'ext://__main__.MyFilter'`` instead of ``MyFilter`` in the above |
| 2099 | example. |
| 2100 | |
| 2101 | * As well as for filters, this technique can also be used to configure custom |
| 2102 | handlers and formatters. See :ref:`logging-config-dict-userdef` for more |
| 2103 | information on how logging supports using user-defined objects in its |
| 2104 | configuration, and see the other cookbook recipe :ref:`custom-handlers` above. |
| 2105 | |
Vinay Sajip | db07164 | 2015-01-28 07:32:38 +0000 | [diff] [blame] | 2106 | |
| 2107 | .. _custom-format-exception: |
| 2108 | |
| 2109 | Customized exception formatting |
| 2110 | ------------------------------- |
| 2111 | |
| 2112 | There might be times when you want to do customized exception formatting - for |
| 2113 | argument's sake, let's say you want exactly one line per logged event, even |
| 2114 | when exception information is present. You can do this with a custom formatter |
| 2115 | class, as shown in the following example:: |
| 2116 | |
| 2117 | import logging |
| 2118 | |
| 2119 | class OneLineExceptionFormatter(logging.Formatter): |
| 2120 | def formatException(self, exc_info): |
| 2121 | """ |
| 2122 | Format an exception so that it prints on a single line. |
| 2123 | """ |
| 2124 | result = super(OneLineExceptionFormatter, self).formatException(exc_info) |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 2125 | return repr(result) # or format into one line however you want to |
Vinay Sajip | db07164 | 2015-01-28 07:32:38 +0000 | [diff] [blame] | 2126 | |
| 2127 | def format(self, record): |
| 2128 | s = super(OneLineExceptionFormatter, self).format(record) |
| 2129 | if record.exc_text: |
| 2130 | s = s.replace('\n', '') + '|' |
| 2131 | return s |
| 2132 | |
| 2133 | def configure_logging(): |
| 2134 | fh = logging.FileHandler('output.txt', 'w') |
| 2135 | f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|', |
| 2136 | '%d/%m/%Y %H:%M:%S') |
| 2137 | fh.setFormatter(f) |
| 2138 | root = logging.getLogger() |
| 2139 | root.setLevel(logging.DEBUG) |
| 2140 | root.addHandler(fh) |
| 2141 | |
| 2142 | def main(): |
| 2143 | configure_logging() |
| 2144 | logging.info('Sample message') |
| 2145 | try: |
| 2146 | x = 1 / 0 |
| 2147 | except ZeroDivisionError as e: |
| 2148 | logging.exception('ZeroDivisionError: %s', e) |
| 2149 | |
| 2150 | if __name__ == '__main__': |
| 2151 | main() |
| 2152 | |
| 2153 | When run, this produces a file with exactly two lines:: |
| 2154 | |
| 2155 | 28/01/2015 07:21:23|INFO|Sample message| |
| 2156 | 28/01/2015 07:21:23|ERROR|ZeroDivisionError: integer division or modulo by zero|'Traceback (most recent call last):\n File "logtest7.py", line 30, in main\n x = 1 / 0\nZeroDivisionError: integer division or modulo by zero'| |
| 2157 | |
| 2158 | While the above treatment is simplistic, it points the way to how exception |
| 2159 | information can be formatted to your liking. The :mod:`traceback` module may be |
| 2160 | helpful for more specialized needs. |
Vinay Sajip | f046dfe | 2015-02-01 15:17:34 +0000 | [diff] [blame] | 2161 | |
| 2162 | .. _spoken-messages: |
| 2163 | |
| 2164 | Speaking logging messages |
| 2165 | ------------------------- |
| 2166 | |
| 2167 | There might be situations when it is desirable to have logging messages rendered |
Martin Panter | 8f13783 | 2017-01-14 08:24:20 +0000 | [diff] [blame] | 2168 | in an audible rather than a visible format. This is easy to do if you have |
| 2169 | text-to-speech (TTS) functionality available in your system, even if it doesn't have |
Vinay Sajip | f046dfe | 2015-02-01 15:17:34 +0000 | [diff] [blame] | 2170 | a Python binding. Most TTS systems have a command line program you can run, and |
| 2171 | this can be invoked from a handler using :mod:`subprocess`. It's assumed here |
| 2172 | that TTS command line programs won't expect to interact with users or take a |
| 2173 | long time to complete, and that the frequency of logged messages will be not so |
| 2174 | high as to swamp the user with messages, and that it's acceptable to have the |
| 2175 | messages spoken one at a time rather than concurrently, The example implementation |
| 2176 | below waits for one message to be spoken before the next is processed, and this |
| 2177 | might cause other handlers to be kept waiting. Here is a short example showing |
| 2178 | the approach, which assumes that the ``espeak`` TTS package is available:: |
| 2179 | |
| 2180 | import logging |
| 2181 | import subprocess |
| 2182 | import sys |
| 2183 | |
| 2184 | class TTSHandler(logging.Handler): |
| 2185 | def emit(self, record): |
| 2186 | msg = self.format(record) |
| 2187 | # Speak slowly in a female English voice |
| 2188 | cmd = ['espeak', '-s150', '-ven+f3', msg] |
| 2189 | p = subprocess.Popen(cmd, stdout=subprocess.PIPE, |
| 2190 | stderr=subprocess.STDOUT) |
| 2191 | # wait for the program to finish |
| 2192 | p.communicate() |
| 2193 | |
| 2194 | def configure_logging(): |
| 2195 | h = TTSHandler() |
| 2196 | root = logging.getLogger() |
| 2197 | root.addHandler(h) |
| 2198 | # the default formatter just returns the message |
| 2199 | root.setLevel(logging.DEBUG) |
| 2200 | |
| 2201 | def main(): |
| 2202 | logging.info('Hello') |
| 2203 | logging.debug('Goodbye') |
| 2204 | |
| 2205 | if __name__ == '__main__': |
| 2206 | configure_logging() |
| 2207 | sys.exit(main()) |
| 2208 | |
| 2209 | When run, this script should say "Hello" and then "Goodbye" in a female voice. |
| 2210 | |
| 2211 | The above approach can, of course, be adapted to other TTS systems and even |
| 2212 | other systems altogether which can process messages via external programs run |
| 2213 | from a command line. |
| 2214 | |
Vinay Sajip | ff1f3d9 | 2015-10-10 00:52:35 +0100 | [diff] [blame] | 2215 | |
| 2216 | .. _buffered-logging: |
| 2217 | |
| 2218 | Buffering logging messages and outputting them conditionally |
| 2219 | ------------------------------------------------------------ |
| 2220 | |
| 2221 | There might be situations where you want to log messages in a temporary area |
| 2222 | and only output them if a certain condition occurs. For example, you may want to |
| 2223 | start logging debug events in a function, and if the function completes without |
| 2224 | errors, you don't want to clutter the log with the collected debug information, |
| 2225 | but if there is an error, you want all the debug information to be output as well |
| 2226 | as the error. |
| 2227 | |
| 2228 | Here is an example which shows how you could do this using a decorator for your |
| 2229 | functions where you want logging to behave this way. It makes use of the |
| 2230 | :class:`logging.handlers.MemoryHandler`, which allows buffering of logged events |
| 2231 | until some condition occurs, at which point the buffered events are ``flushed`` |
| 2232 | - passed to another handler (the ``target`` handler) for processing. By default, |
| 2233 | the ``MemoryHandler`` flushed when its buffer gets filled up or an event whose |
| 2234 | level is greater than or equal to a specified threshold is seen. You can use this |
| 2235 | recipe with a more specialised subclass of ``MemoryHandler`` if you want custom |
| 2236 | flushing behavior. |
| 2237 | |
| 2238 | The example script has a simple function, ``foo``, which just cycles through |
| 2239 | all the logging levels, writing to ``sys.stderr`` to say what level it's about |
Martin Panter | f0564164 | 2016-05-08 13:48:10 +0000 | [diff] [blame] | 2240 | to log at, and then actually logging a message at that level. You can pass a |
Vinay Sajip | ff1f3d9 | 2015-10-10 00:52:35 +0100 | [diff] [blame] | 2241 | parameter to ``foo`` which, if true, will log at ERROR and CRITICAL levels - |
| 2242 | otherwise, it only logs at DEBUG, INFO and WARNING levels. |
| 2243 | |
| 2244 | The script just arranges to decorate ``foo`` with a decorator which will do the |
| 2245 | conditional logging that's required. The decorator takes a logger as a parameter |
| 2246 | and attaches a memory handler for the duration of the call to the decorated |
| 2247 | function. The decorator can be additionally parameterised using a target handler, |
| 2248 | a level at which flushing should occur, and a capacity for the buffer. These |
| 2249 | default to a :class:`~logging.StreamHandler` which writes to ``sys.stderr``, |
| 2250 | ``logging.ERROR`` and ``100`` respectively. |
| 2251 | |
| 2252 | Here's the script:: |
| 2253 | |
| 2254 | import logging |
| 2255 | from logging.handlers import MemoryHandler |
| 2256 | import sys |
| 2257 | |
| 2258 | logger = logging.getLogger(__name__) |
| 2259 | logger.addHandler(logging.NullHandler()) |
| 2260 | |
| 2261 | def log_if_errors(logger, target_handler=None, flush_level=None, capacity=None): |
| 2262 | if target_handler is None: |
| 2263 | target_handler = logging.StreamHandler() |
| 2264 | if flush_level is None: |
| 2265 | flush_level = logging.ERROR |
| 2266 | if capacity is None: |
| 2267 | capacity = 100 |
| 2268 | handler = MemoryHandler(capacity, flushLevel=flush_level, target=target_handler) |
| 2269 | |
| 2270 | def decorator(fn): |
| 2271 | def wrapper(*args, **kwargs): |
| 2272 | logger.addHandler(handler) |
| 2273 | try: |
| 2274 | return fn(*args, **kwargs) |
| 2275 | except Exception: |
| 2276 | logger.exception('call failed') |
| 2277 | raise |
| 2278 | finally: |
| 2279 | super(MemoryHandler, handler).flush() |
| 2280 | logger.removeHandler(handler) |
| 2281 | return wrapper |
| 2282 | |
| 2283 | return decorator |
| 2284 | |
| 2285 | def write_line(s): |
| 2286 | sys.stderr.write('%s\n' % s) |
| 2287 | |
| 2288 | def foo(fail=False): |
| 2289 | write_line('about to log at DEBUG ...') |
| 2290 | logger.debug('Actually logged at DEBUG') |
| 2291 | write_line('about to log at INFO ...') |
| 2292 | logger.info('Actually logged at INFO') |
| 2293 | write_line('about to log at WARNING ...') |
| 2294 | logger.warning('Actually logged at WARNING') |
| 2295 | if fail: |
| 2296 | write_line('about to log at ERROR ...') |
| 2297 | logger.error('Actually logged at ERROR') |
| 2298 | write_line('about to log at CRITICAL ...') |
| 2299 | logger.critical('Actually logged at CRITICAL') |
| 2300 | return fail |
| 2301 | |
| 2302 | decorated_foo = log_if_errors(logger)(foo) |
| 2303 | |
| 2304 | if __name__ == '__main__': |
| 2305 | logger.setLevel(logging.DEBUG) |
| 2306 | write_line('Calling undecorated foo with False') |
| 2307 | assert not foo(False) |
| 2308 | write_line('Calling undecorated foo with True') |
| 2309 | assert foo(True) |
| 2310 | write_line('Calling decorated foo with False') |
| 2311 | assert not decorated_foo(False) |
| 2312 | write_line('Calling decorated foo with True') |
| 2313 | assert decorated_foo(True) |
| 2314 | |
| 2315 | When this script is run, the following output should be observed:: |
| 2316 | |
| 2317 | Calling undecorated foo with False |
| 2318 | about to log at DEBUG ... |
| 2319 | about to log at INFO ... |
| 2320 | about to log at WARNING ... |
| 2321 | Calling undecorated foo with True |
| 2322 | about to log at DEBUG ... |
| 2323 | about to log at INFO ... |
| 2324 | about to log at WARNING ... |
| 2325 | about to log at ERROR ... |
| 2326 | about to log at CRITICAL ... |
| 2327 | Calling decorated foo with False |
| 2328 | about to log at DEBUG ... |
| 2329 | about to log at INFO ... |
| 2330 | about to log at WARNING ... |
| 2331 | Calling decorated foo with True |
| 2332 | about to log at DEBUG ... |
| 2333 | about to log at INFO ... |
| 2334 | about to log at WARNING ... |
| 2335 | about to log at ERROR ... |
| 2336 | Actually logged at DEBUG |
| 2337 | Actually logged at INFO |
| 2338 | Actually logged at WARNING |
| 2339 | Actually logged at ERROR |
| 2340 | about to log at CRITICAL ... |
| 2341 | Actually logged at CRITICAL |
| 2342 | |
| 2343 | As you can see, actual logging output only occurs when an event is logged whose |
| 2344 | severity is ERROR or greater, but in that case, any previous events at lower |
| 2345 | severities are also logged. |
| 2346 | |
| 2347 | You can of course use the conventional means of decoration:: |
| 2348 | |
| 2349 | @log_if_errors(logger) |
| 2350 | def foo(fail=False): |
| 2351 | ... |
Vinay Sajip | 4de9dae | 2015-10-17 13:58:19 +0100 | [diff] [blame] | 2352 | |
| 2353 | |
| 2354 | .. _utc-formatting: |
| 2355 | |
| 2356 | Formatting times using UTC (GMT) via configuration |
| 2357 | -------------------------------------------------- |
| 2358 | |
| 2359 | Sometimes you want to format times using UTC, which can be done using a class |
| 2360 | such as `UTCFormatter`, shown below:: |
| 2361 | |
| 2362 | import logging |
| 2363 | import time |
| 2364 | |
| 2365 | class UTCFormatter(logging.Formatter): |
| 2366 | converter = time.gmtime |
| 2367 | |
Berker Peksag | f84499a | 2015-10-20 03:41:38 +0300 | [diff] [blame] | 2368 | and you can then use the ``UTCFormatter`` in your code instead of |
Vinay Sajip | 4de9dae | 2015-10-17 13:58:19 +0100 | [diff] [blame] | 2369 | :class:`~logging.Formatter`. If you want to do that via configuration, you can |
| 2370 | use the :func:`~logging.config.dictConfig` API with an approach illustrated by |
| 2371 | the following complete example:: |
| 2372 | |
| 2373 | import logging |
| 2374 | import logging.config |
| 2375 | import time |
| 2376 | |
| 2377 | class UTCFormatter(logging.Formatter): |
| 2378 | converter = time.gmtime |
| 2379 | |
| 2380 | LOGGING = { |
| 2381 | 'version': 1, |
| 2382 | 'disable_existing_loggers': False, |
| 2383 | 'formatters': { |
| 2384 | 'utc': { |
| 2385 | '()': UTCFormatter, |
| 2386 | 'format': '%(asctime)s %(message)s', |
| 2387 | }, |
| 2388 | 'local': { |
| 2389 | 'format': '%(asctime)s %(message)s', |
| 2390 | } |
| 2391 | }, |
| 2392 | 'handlers': { |
| 2393 | 'console1': { |
| 2394 | 'class': 'logging.StreamHandler', |
| 2395 | 'formatter': 'utc', |
| 2396 | }, |
| 2397 | 'console2': { |
| 2398 | 'class': 'logging.StreamHandler', |
| 2399 | 'formatter': 'local', |
| 2400 | }, |
| 2401 | }, |
| 2402 | 'root': { |
| 2403 | 'handlers': ['console1', 'console2'], |
| 2404 | } |
| 2405 | } |
| 2406 | |
| 2407 | if __name__ == '__main__': |
| 2408 | logging.config.dictConfig(LOGGING) |
| 2409 | logging.warning('The local time is %s', time.asctime()) |
| 2410 | |
| 2411 | When this script is run, it should print something like:: |
| 2412 | |
| 2413 | 2015-10-17 12:53:29,501 The local time is Sat Oct 17 13:53:29 2015 |
| 2414 | 2015-10-17 13:53:29,501 The local time is Sat Oct 17 13:53:29 2015 |
| 2415 | |
| 2416 | showing how the time is formatted both as local time and UTC, one for each |
| 2417 | handler. |
Vinay Sajip | d93a601 | 2016-04-01 23:13:01 +0100 | [diff] [blame] | 2418 | |
| 2419 | |
| 2420 | .. _context-manager: |
| 2421 | |
| 2422 | Using a context manager for selective logging |
| 2423 | --------------------------------------------- |
| 2424 | |
| 2425 | There are times when it would be useful to temporarily change the logging |
| 2426 | configuration and revert it back after doing something. For this, a context |
| 2427 | manager is the most obvious way of saving and restoring the logging context. |
| 2428 | Here is a simple example of such a context manager, which allows you to |
| 2429 | optionally change the logging level and add a logging handler purely in the |
| 2430 | scope of the context manager:: |
| 2431 | |
| 2432 | import logging |
| 2433 | import sys |
| 2434 | |
| 2435 | class LoggingContext(object): |
| 2436 | def __init__(self, logger, level=None, handler=None, close=True): |
| 2437 | self.logger = logger |
| 2438 | self.level = level |
| 2439 | self.handler = handler |
| 2440 | self.close = close |
| 2441 | |
| 2442 | def __enter__(self): |
| 2443 | if self.level is not None: |
| 2444 | self.old_level = self.logger.level |
| 2445 | self.logger.setLevel(self.level) |
| 2446 | if self.handler: |
| 2447 | self.logger.addHandler(self.handler) |
| 2448 | |
| 2449 | def __exit__(self, et, ev, tb): |
| 2450 | if self.level is not None: |
| 2451 | self.logger.setLevel(self.old_level) |
| 2452 | if self.handler: |
| 2453 | self.logger.removeHandler(self.handler) |
| 2454 | if self.handler and self.close: |
| 2455 | self.handler.close() |
| 2456 | # implicit return of None => don't swallow exceptions |
| 2457 | |
| 2458 | If you specify a level value, the logger's level is set to that value in the |
| 2459 | scope of the with block covered by the context manager. If you specify a |
| 2460 | handler, it is added to the logger on entry to the block and removed on exit |
| 2461 | from the block. You can also ask the manager to close the handler for you on |
| 2462 | block exit - you could do this if you don't need the handler any more. |
| 2463 | |
| 2464 | To illustrate how it works, we can add the following block of code to the |
| 2465 | above:: |
| 2466 | |
| 2467 | if __name__ == '__main__': |
| 2468 | logger = logging.getLogger('foo') |
| 2469 | logger.addHandler(logging.StreamHandler()) |
| 2470 | logger.setLevel(logging.INFO) |
| 2471 | logger.info('1. This should appear just once on stderr.') |
| 2472 | logger.debug('2. This should not appear.') |
| 2473 | with LoggingContext(logger, level=logging.DEBUG): |
| 2474 | logger.debug('3. This should appear once on stderr.') |
| 2475 | logger.debug('4. This should not appear.') |
| 2476 | h = logging.StreamHandler(sys.stdout) |
| 2477 | with LoggingContext(logger, level=logging.DEBUG, handler=h, close=True): |
| 2478 | logger.debug('5. This should appear twice - once on stderr and once on stdout.') |
| 2479 | logger.info('6. This should appear just once on stderr.') |
| 2480 | logger.debug('7. This should not appear.') |
| 2481 | |
| 2482 | We initially set the logger's level to ``INFO``, so message #1 appears and |
| 2483 | message #2 doesn't. We then change the level to ``DEBUG`` temporarily in the |
| 2484 | following ``with`` block, and so message #3 appears. After the block exits, the |
| 2485 | logger's level is restored to ``INFO`` and so message #4 doesn't appear. In the |
| 2486 | next ``with`` block, we set the level to ``DEBUG`` again but also add a handler |
| 2487 | writing to ``sys.stdout``. Thus, message #5 appears twice on the console (once |
| 2488 | via ``stderr`` and once via ``stdout``). After the ``with`` statement's |
| 2489 | completion, the status is as it was before so message #6 appears (like message |
| 2490 | #1) whereas message #7 doesn't (just like message #2). |
| 2491 | |
Martin Panter | 1050d2d | 2016-07-26 11:18:21 +0200 | [diff] [blame] | 2492 | If we run the resulting script, the result is as follows: |
| 2493 | |
| 2494 | .. code-block:: shell-session |
Vinay Sajip | d93a601 | 2016-04-01 23:13:01 +0100 | [diff] [blame] | 2495 | |
| 2496 | $ python logctx.py |
| 2497 | 1. This should appear just once on stderr. |
| 2498 | 3. This should appear once on stderr. |
| 2499 | 5. This should appear twice - once on stderr and once on stdout. |
| 2500 | 5. This should appear twice - once on stderr and once on stdout. |
| 2501 | 6. This should appear just once on stderr. |
| 2502 | |
| 2503 | If we run it again, but pipe ``stderr`` to ``/dev/null``, we see the following, |
Martin Panter | 1050d2d | 2016-07-26 11:18:21 +0200 | [diff] [blame] | 2504 | which is the only message written to ``stdout``: |
| 2505 | |
| 2506 | .. code-block:: shell-session |
Vinay Sajip | d93a601 | 2016-04-01 23:13:01 +0100 | [diff] [blame] | 2507 | |
| 2508 | $ python logctx.py 2>/dev/null |
| 2509 | 5. This should appear twice - once on stderr and once on stdout. |
| 2510 | |
Martin Panter | 1050d2d | 2016-07-26 11:18:21 +0200 | [diff] [blame] | 2511 | Once again, but piping ``stdout`` to ``/dev/null``, we get: |
| 2512 | |
| 2513 | .. code-block:: shell-session |
Vinay Sajip | d93a601 | 2016-04-01 23:13:01 +0100 | [diff] [blame] | 2514 | |
| 2515 | $ python logctx.py >/dev/null |
| 2516 | 1. This should appear just once on stderr. |
| 2517 | 3. This should appear once on stderr. |
| 2518 | 5. This should appear twice - once on stderr and once on stdout. |
| 2519 | 6. This should appear just once on stderr. |
| 2520 | |
| 2521 | In this case, the message #5 printed to ``stdout`` doesn't appear, as expected. |
| 2522 | |
| 2523 | Of course, the approach described here can be generalised, for example to attach |
| 2524 | logging filters temporarily. Note that the above code works in Python 2 as well |
| 2525 | as Python 3. |