Advertisement
Advanced Python, Logging

How do RotatingFileHandler and TimedRotatingFileHandler prevent log files from growing unbounded?

Short answer

RotatingFileHandler rotates the log file once it reaches a specified maxBytes, renaming old files with numeric suffixes and keeping up to backupCount old files. TimedRotatingFileHandler instead rotates on a time interval (e.g., daily, hourly).

Save Python mock interview
Advertisement
AModel answer
RotatingFileHandler rotates the log file once it reaches a specified maxBytes, renaming old files with numeric suffixes and keeping up to backupCount old files. TimedRotatingFileHandler instead rotates on a time interval (e.g., daily, hourly). Both prevent a single log file from consuming unlimited disk space over a long-running application's lifetime.
from logging.handlers import RotatingFileHandler

handler = RotatingFileHandler('app.log', maxBytes=10_000_000, backupCount=5)
logger = logging.getLogger('myapp')
logger.addHandler(handler)
Real-world example
A long-running background worker uses TimedRotatingFileHandler(when='midnight', backupCount=30) to keep exactly 30 days of daily log files and auto-delete older ones.
Likely follow-ups
  • What happens to the currently-open file handle during rotation?
  • How does this differ from external log rotation tools like logrotate?
Related topics