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