Python › Logging
How do RotatingFileHandler and TimedRotatingFileHandler prevent log files from growing unbounded?
AdvancedAnswer
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.