What is the relationship between Logger, Handler, Formatter, and Filter in the logging module?
Short answer
A Logger is the entry point your code calls (logger.info(...)); it passes log records to one or more Handlers, which decide where output goes (console, file, network).
Advertisement
AModel answer
A Logger is the entry point your code calls (logger.info(...)); it passes log records to one or more Handlers, which decide where output goes (console, file, network). Each Handler can have a Formatter controlling the output's text layout, and Filters can be attached to either Loggers or Handlers to allow/reject records based on custom logic beyond just level.
import logging
logger = logging.getLogger('myapp')
handler = logging.FileHandler('app.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.info('Started')Real-world example
A microservice attaches both a console Handler (for local dev) and a FileHandler (for persistent logs) to the same Logger, each with a different Formatter.
Likely follow-ups
- Can a single logger have multiple handlers with different levels?
- What is propagate and when would you disable it?
Related topics