Sub topic 5
Handlers: where records go
A logger creates records. A handler decides where each record goes. This chapter assumes you can create a logger with logging.getLogger, you know the five log levels, and you are comfortable subclassing a class in Python. Formatters and the logger hierarchy get their own chapters, so they appear here only where needed.
What a handler does
A handler is an object that takes a LogRecord and delivers it to one destination. The destination can be a stream, a file, a socket, an email address, or a queue. A logger can have any number of handlers, and a handler can be attached to any number of loggers.
When you call logger.info(...), this sequence runs:
- The logger checks its effective level. If
INFOis below that level, the record is dropped. - Otherwise the logger creates a
LogRecordand passes it to each of its handlers. - Each handler checks the record against its own level. If the record passes, the handler formats it and emits it.
The two checks are independent. A handler can only narrow what the logger lets through. If the logger's level is WARNING, a handler set to DEBUG still never sees a DEBUG record, because the logger dropped it first.
Two handlers with different levels
The most common reason to attach more than one handler is to send different amounts of detail to different places. The console gets a quiet summary, and the file keeps everything.
import logging
logger = logging.getLogger("myapp")
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
file_handler = logging.FileHandler("app.log", encoding="utf-8")
file_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s %(levelname)-8s %(name)s: %(message)s")
console.setFormatter(formatter)
file_handler.setFormatter(formatter)
logger.addHandler(console)
logger.addHandler(file_handler)
logger.debug("Written to the file only")
logger.info("Written to the file and the console")Notice that the logger level is DEBUG, the lowest level you want any handler to see. Each handler then raises the bar for its own destination. This is the usual pattern: set the logger to the most verbose level needed, and filter per handler.
A handler with no level set has level NOTSET (0), which means it accepts every record that reaches it.
Handlers you will use most
Handlers live in two modules. StreamHandler, FileHandler, and NullHandler are in logging. The rest are in logging.handlers.
| Handler | Destination | Notes |
|---|---|---|
| `StreamHandler` | Any file-like object | Defaults to `sys.stderr` |
| `FileHandler` | A file on disk | Opens in append mode by default |
| `NullHandler` | Nowhere | Used by libraries |
| `RotatingFileHandler` | Files, rotated by size | Covered in a later chapter |
| `TimedRotatingFileHandler` | Files, rotated by time | Daily or hourly logs |
| `WatchedFileHandler` | A file | Reopens the file if an external tool such as logrotate moves it (Unix) |
| `SysLogHandler` | A syslog daemon | Local socket or UDP |
| `SMTPHandler` | Best limited to `ERROR` and above | |
| `HTTPHandler` | A web server | GET or POST |
| `QueueHandler` | A queue | Used for non-blocking logging |
| `MemoryHandler` | A buffer, then another handler | Flushes on a trigger level |
StreamHandler
StreamHandler() writes to sys.stderr. To write to standard output instead, pass the stream explicitly with logging.StreamHandler(sys.stdout). The handler does not close the stream, because it does not own it.
FileHandler
FileHandler(filename, mode="a", encoding=None, delay=False) opens the file when the handler is created. Three details matter in practice:
- Always pass
encoding. Without it, Python uses the platform's default encoding, and a non-ASCII message can fail or produce different bytes on different machines. - With
delay=True, the file is not opened until the first record is emitted. This avoids creating empty log files. - The handler keeps the file open for its lifetime. Call
handler.close()when you remove it, or letlogging.shutdown()do it at interpreter exit.
Managing handlers on a logger
Handlers are added and removed with addHandler and removeHandler. The list is available as logger.handlers. Adding the same handler object twice has no effect, because addHandler ignores a handler already in the list. Adding two separate handler objects that write to the same place, however, produces two copies of every line.
The duplicate-lines pitfall
This bug appears when setup code runs more than once, for example inside a function called per request or per test:
import logging
def get_logger():
logger = logging.getLogger("myapp")
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler()) # new handler on every call
return logger
get_logger()
get_logger().info("Hello") # printed twiceEach call to get_logger() creates a new StreamHandler and attaches it to the same logger object, because getLogger("myapp") always returns the same instance. After two calls there are two handlers, so the message prints twice. The fix is to configure logging once, at program startup, and have every other module call only logging.getLogger(__name__). If you must guard the setup, check if not logger.handlers: first.
A second cause of duplicates is propagation. A record handled by a logger's own handlers also travels up to its ancestors' handlers. If you attach a console handler to myapp and also call basicConfig (which adds one to the root logger), each record prints twice. The next chapters on the hierarchy cover how to control this.
What happens with no handlers
If a record is emitted and no handler is found anywhere in the logger's ancestry, Python falls back to logging.lastResort. This is a stderr handler with level WARNING. It explains two behaviors that surprise people:
logging.getLogger("x").warning("hi")with no configuration printshion stderr, with no timestamp or level.logging.getLogger("x").info("hi")with no configuration prints nothing.
Once any handler exists on the logger or an ancestor, lastResort is no longer used.
Writing your own handler
To send records somewhere unusual, subclass logging.Handler and override emit. Use self.format(record) to apply the handler's formatter. The base class's handle method acquires the handler's lock before calling emit, so your emit does not need its own locking for thread safety.
import logging
class ListHandler(logging.Handler):
"""Collects formatted messages in memory."""
def __init__(self, level=logging.NOTSET):
super().__init__(level)
self.messages = []
def emit(self, record):
try:
self.messages.append(self.format(record))
except Exception:
self.handleError(record)
handler = ListHandler(logging.WARNING)
handler.setFormatter(logging.Formatter("%(levelname)s:%(message)s"))
logger = logging.getLogger("demo")
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
logger.info("ignored by the handler")
logger.warning("kept")
print(handler.messages) # ['WARNING:kept']The try/except with handleError follows the standard library's convention. If formatting or delivery fails, handleError prints the traceback to stderr when logging.raiseExceptions is true (the default) and does not raise into your application code. A logging failure should not crash the program it is reporting on.
Failure modes and edge cases
- Slow handlers block the caller.
emitruns in the thread that calledlogger.info. A handler that sends email or makes an HTTP request stalls your code until it finishes. A later chapter shows howQueueHandlermoves this work to another thread. - Handlers on a closed stream. If a
StreamHandlerwrites to a stream that has been closed, such as a captured stdout in a test,emitfails andhandleErrorprints a "Logging error" message. - Concurrent processes.
FileHandleris thread-safe but not safe for several processes writing the same file. Interleaved or lost lines can result. Use aSocketHandler, aQueueHandlerwith a single writer process, or one file per process. - Level confusion. If a message is missing, check both levels: the logger's effective level and the handler's level.
Summary of the working model
A logger decides whether a record exists. Its handlers decide where the record goes, and each handler applies its own level and formatter. Configure handlers once at startup, set the logger to the most verbose level any handler needs, and let each handler narrow it.
Exercise
A logger named "shop" has its level set to WARNING. It has one FileHandler whose level is set to DEBUG. You call logger.info("order placed"). Is the message written to the file? Explain which checks run.
Show answer
No. The logger checks its effective level first, and INFO is below WARNING, so the record is dropped before any handler sees it. The handler's DEBUG level never comes into play. To get the message in the file, lower the logger's level to INFO or DEBUG and keep the handler at DEBUG or INFO.
Exercise
A script calls a function setup() at the start of every request handler. Each call runs logging.getLogger("api").addHandler(logging.StreamHandler()). After 3 requests, each log message prints 3 times. Why, and how do you fix it?
Show answer
getLogger("api") returns the same logger object every time, and each setup() call attaches a new StreamHandler to it, so after 3 calls the logger has 3 handlers. Fix it by configuring logging once at program startup (for example in main) and having request code only call logging.getLogger. A guard such as "if not logger.handlers:" also works but is a workaround.