Short Definition:
A Handler in Python’s logging framework is an object responsible for dispatching log records (LogRecord) to their destination—such as files, terminals, emails, or network locations. Loggers generate the log records; Handlers receive these records and write or send them elsewhere. ![]()
Key Points
- Separation of Responsibilities: Loggers produce messages; Handlers are responsible for sending/storing them.
- Common Types:
FileHandler,StreamHandler,RotatingFileHandler,SMTPHandler, etc. - Configurable: Each Handler has its own level (for filtering logs) and formatter (for formatting the log text).
- Multiple Handlers: You can attach multiple Handlers to a single Logger, enabling the same log message to be sent to multiple destinations. Be cautious about duplicate output or resource leaks (e.g., unclosed file handles).
Example
import logging
logger = logging.getLogger("multi_ocr_sdk")
fh = logging.FileHandler("/path/to/logfile.log")
fh.setLevel(logging.INFO)
fh.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
logger.addHandler(fh)
logger.info("This is a log message")
Tip: When replacing a log file, remember to first call
close()andremoveHandler()on the old file handler to avoid file descriptor leaks and ensure logs are written to the latest file.