Sub topic 2
Handlers: Where Records Go
Assume you know basic Python modules, functions, classes, and try/except. This chapter focuses on how logging records are routed and formatted.
Handlers: Where Records Go
A handler sends a log record to a destination. Common destinations include:
StreamHandler, usually the terminalFileHandler, a fileRotatingFileHandler, a file with size-based rotationQueueHandler, a queue for later processing
A logger can have multiple handlers. For example, one handler can show warnings in the terminal while another stores debug records in a file.
Formatters: How Records Look
A formatter converts a LogRecord into text. It can use attributes such as %(levelname)s, %(name)s, and %(message)s.
import logging
class RequestIdFilter(logging.Filter):
def filter(self, record):
record.request_id = "req-123"
return True
logger = logging.getLogger("myapp.web")
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(logging.Formatter(
"%(asctime)s %(levelname)s %(name)s "
"[%(request_id)s]: %(message)s"
))
console.addFilter(RequestIdFilter())
logger.addHandler(console)
logger.debug("This is filtered by the handler")
logger.info("Request started")
try:
1 / 0
except ZeroDivisionError:
logger.exception("Request failed")The logger accepts DEBUG records, but the handler emits only INFO and higher. logger.exception() adds the current traceback and should normally be called inside an except block.
The Logger Hierarchy and Propagation
Logger names form a hierarchy separated by periods. myapp.web is a child of myapp. Unless configured otherwise, a child record propagates to its ancestors' handlers.
Set logger.propagate = False when a child should not be handled twice. A common mistake is adding a handler to both a child and the root logger, which produces duplicate output.
Filters and Adding Context
A filter decides whether a record passes and can add attributes to it. The example filter adds request_id, which the formatter then displays. Every record reaching that formatter must receive this attribute, or formatting raises an error.
Exercise
Why might one INFO record appear twice?
Show answer
It may be processed by a child handler and then propagated to an ancestor handler. Remove the duplicate handler or set propagate to False.