Sub topic 15
Non-blocking logging with QueueHandler and QueueListener
This chapter assumes you know loggers, handlers, and the logger hierarchy from earlier chapters, and that you can use basic threads conceptually.
The problem: slow handlers block the caller
A handler runs in the thread that calls logger.info(...). If the handler writes to a network socket, sends email, or writes to a slow disk, your application waits. In a web request or a latency-sensitive loop, that wait becomes visible.
The fix is to split the work. Application code only puts records on a queue, which is fast. A separate listener thread takes records off the queue and passes them to the real handlers.
A working setup
QueueHandler is attached to the logger and takes only a queue. QueueListener takes the same queue plus the handlers that do the real output.
import logging
import logging.handlers
import queue
log_queue = queue.Queue(-1)
listener = logging.handlers.QueueListener(log_queue, logging.StreamHandler())
root = logging.getLogger()
root.setLevel(logging.INFO)
root.addHandler(logging.handlers.QueueHandler(log_queue))
listener.start()
logging.getLogger("myapp").info("Handled by the listener thread")
listener.stop()queue.Queue(-1) means the queue has no size limit. listener.start() launches the background thread. listener.stop() waits until the queue is empty, then ends the thread.
What the listener does with levels
The listener calls each handler for every record it receives, without checking that handler's level. To make the listener honor each handler's level, pass respect_handler_level=True:
import logging
import logging.handlers
import queue
log_queue = queue.Queue(-1)
console = logging.StreamHandler()
console.setLevel(logging.WARNING)
listener = logging.handlers.QueueListener(
log_queue, console, respect_handler_level=True
)
logger = logging.getLogger("myapp")
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.handlers.QueueHandler(log_queue))
listener.start()
logger.info("Skipped by the console handler")
logger.warning("Printed by the console handler")
listener.stop()Without respect_handler_level=True, both messages would print.
Common errors
- Skipping
stop(). Records still in the queue at exit can be lost. Calllistener.stop()on shutdown, for example in afinallyblock or withatexit.register(listener.stop). - Duplicate output. If you attach the real handler to the logger and also give it to the listener, each record is emitted twice. The logger should have only the
QueueHandler. - Putting formatters in the wrong place.
QueueHandlerformats the message and exception text before queuing, and it drops the original traceback object. The real handlers still apply their own formatters. Fields such asrecord.argsare no longer available there. - Unbounded memory. An unlimited queue grows if the listener falls behind. With
queue.Queue(maxsize=1000), a full queue makesQueueHandlercallhandleError, which prints an error to stderr and drops that record. Choose which failure you prefer.
When to use it
Use a queue when a handler can be slow or can fail, such as SMTPHandler, HTTPHandler, or SocketHandler. For a plain console or local file handler, the extra thread adds complexity without much benefit.
Exercise
You attach a QueueHandler to the root logger and a StreamHandler to a QueueListener. You also call root.addHandler(stream_handler) with the same StreamHandler. What do you see for each log call, and how do you fix it?
Show answer
Each message is printed twice: once directly by the handler on the logger, and once by the listener thread. Fix it by removing the direct addHandler call, so that the logger has only the QueueHandler and the StreamHandler is passed only to QueueListener.