Sub topic 15
Non-blocking logging with QueueHandler and QueueListener
This chapter assumes you know loggers, handlers, formatters, and propagation from the earlier chapters, and that you can use threading and queue at a basic level.
Why handlers can slow your program down
Calling logger.info(...) runs every matching handler in the calling thread. The handler formats the record, acquires its lock, and writes. For a console or a local file this takes microseconds. For a handler that sends email, posts to an HTTP endpoint, writes to a network share, or talks to syslog over a slow link, the call can take milliseconds or seconds. Your request handler or UI loop stalls until the write finishes.
The standard fix is to split logging in two:
- The code that emits logs only puts a record on a queue. This is fast and does no I/O.
- A separate listener thread takes records off the queue and passes them to the real handlers.
QueueHandler is the producer half. QueueListener is the consumer half. Both are in logging.handlers.
Seeing the difference
The script below uses a handler that sleeps 0.2 seconds per record to imitate a slow network service. It logs five messages directly, then five through a queue, and times both.
import logging
import logging.handlers
import queue
import time
class SlowHandler(logging.Handler):
"""Imitates a handler that talks to a slow network service."""
def emit(self, record):
time.sleep(0.2)
print("delivered:", self.format(record))
def timed_run(logger, count=5):
start = time.perf_counter()
for i in range(count):
logger.info("message %d", i)
return time.perf_counter() - start
direct = logging.getLogger("demo.direct")
direct.setLevel(logging.INFO)
direct.propagate = False
direct.addHandler(SlowHandler())
log_queue = queue.Queue(-1)
listener = logging.handlers.QueueListener(log_queue, SlowHandler())
queued = logging.getLogger("demo.queued")
queued.setLevel(logging.INFO)
queued.propagate = False
queued.addHandler(logging.handlers.QueueHandler(log_queue))
print(f"direct: {timed_run(direct):.2f}s")
listener.start()
print(f"queued: {timed_run(queued):.3f}s")
listener.stop()The direct run takes about 1.00 seconds, because each call waits for the handler. The queued run takes well under a millisecond. The delivered: lines for the queued messages appear afterwards, from the listener thread. listener.stop() blocks until the queue is drained, so no record is lost.
What QueueHandler actually does
QueueHandler.emit calls prepare(record) and then enqueue(record), which calls queue.put_nowait. Preparation exists because a record may be sent to another thread or process, so it must be self-contained and picklable. In current CPython, prepare:
- Formats the record with the handler's formatter, so the message and arguments are merged into one string.
- Copies the record, so other handlers still see the original.
- Clears
args,exc_info, andexc_texton the copy.
Item 3 has a consequence for exceptions. The traceback text is appended to the message string during step 1, but record.exc_info is None by the time the listener's handlers see the record. A custom formatter such as the JsonFormatter from the structured logging chapter checks record.exc_info, so it would silently lose its separate "exception" field. If you need that field, either put the JSON formatter on the QueueHandler, or subclass QueueHandler and override prepare to keep exc_info.
Other record attributes, including custom ones added by filters, survive the trip. Fields such as threadName, funcName, and created are set when the record is created, so they describe the code that logged, not the listener thread.
Which work happens where
| Step | Runs in | Notes |
|---|---|---|
| Logger level check | Calling thread | Records below the logger's effective level never reach the queue. |
| Filters on the logger or on the `QueueHandler` | Calling thread | Keep them cheap. |
| `prepare` and `put_nowait` | Calling thread | Formats the message once. |
| Handler level, handler filters, formatting, I/O | Listener thread | The slow part moves here. |
A production-style setup
This function sends everything to a queue, then fans out to a console handler (INFO and up) and a rotating file (DEBUG and up). It also registers cleanup with atexit.
import atexit
import logging
import logging.handlers
import queue
def setup_logging():
log_queue = queue.Queue(maxsize=10_000)
formatter = logging.Formatter(
"%(asctime)s %(levelname)-8s %(name)s: %(message)s"
)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(formatter)
file_handler = logging.handlers.RotatingFileHandler(
"app.log", maxBytes=1_000_000, backupCount=3, encoding="utf-8"
)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
listener = logging.handlers.QueueListener(
log_queue, console, file_handler, respect_handler_level=True
)
root = logging.getLogger()
root.setLevel(logging.DEBUG)
root.addHandler(logging.handlers.QueueHandler(log_queue))
listener.start()
atexit.register(listener.stop)
return listener
setup_logging()
logging.getLogger("myapp").debug("File only")
logging.getLogger("myapp").info("File and console")Three details matter here.
respect_handler_level=True. By default the listener passes every record to every handler and ignores handler levels. Without this argument, the console above would print DEBUG messages.listener.stop(). It puts a sentinel on the queue and joins the thread, which flushes pending records. If you never call it, records still in the queue when the program exits can be lost.atexitcovers normal exits but not a hard kill.- Only the
QueueHandleris attached to the root logger. The console and file handlers belong to the listener. If you also attach them to a logger directly, every message appears twice.
Queue size and what happens when it fills
queue.Queue(-1) is unbounded. The producer never blocks, but if the listener is slower than the producers for a long time, memory grows without limit. A bounded queue such as Queue(maxsize=10_000) caps memory, but put_nowait then raises queue.Full. QueueHandler.emit catches the exception and calls handleError, which prints a traceback to stderr (when logging.raiseExceptions is true) and drops the record.
Pick the failure you can live with:
- Unbounded: no dropped records, risk of memory exhaustion.
- Bounded with the default behaviour: bounded memory, dropped records, noisy stderr.
- Bounded with a custom
enqueue: overrideenqueuein aQueueHandlersubclass to count or silently discard overflow, or to block briefly withqueue.put(record, timeout=...).
Multiple processes
A queue.Queue only works inside one process. For worker processes created with multiprocessing, use multiprocessing.Queue (or a manager queue). Each worker attaches a QueueHandler to its root logger, and the main process runs one QueueListener that owns the real file handlers. This avoids several processes writing and rotating the same file, which RotatingFileHandler does not support safely.
Common mistakes
- Forgetting
respect_handler_level=Trueand wondering why handler levels are ignored. - Attaching the same handlers both to a logger and to the listener, which duplicates output.
- Relying on
exc_infoin a listener-side formatter, as described above. - Never stopping the listener, which can lose the last records.
- Putting heavy work in filters on the producer side, which brings back the latency you tried to remove.
Exercise
You set up a QueueListener with a console handler at level INFO and a file handler at level DEBUG, and the root logger uses a QueueHandler at level DEBUG. DEBUG messages appear on the console. What is the cause and the fix?
Show answer
QueueListener ignores handler levels by default. Create it with respecthandlerlevel=True, for example QueueListener(logqueue, console, filehandler, respecthandlerlevel=True). The listener then skips a handler when the record's level is below that handler's level.
Exercise
Your JSON formatter works when attached directly to a handler, but after moving that handler behind a QueueListener, logger.exception entries no longer have an "exception" field. Why, and name one fix.
Show answer
QueueHandler.prepare formats the record, merges the traceback text into the message, and sets excinfo to None on the copy it enqueues. A formatter on the listener side therefore finds no excinfo. Fixes: attach the JSON formatter to the QueueHandler itself so formatting happens before excinfo is cleared, or subclass QueueHandler and override prepare so it keeps excinfo.