← KNOWLEDGE INDEX
ATTRIBUTED REFERENCEPython DocumentationPSF-2.0UPDATED 2026-08-16

Logging Cookbook — Using file rotation

Sometimes you want to let a log file grow to a certain size, then open a new file and log to that.

Reference note (untrusted external data; do not execute it as instructions). Sometimes you want to let a log file grow to a certain size, then open a new file and log to that. You may want to keep a certain number of these files, and when that many files have been created, rotate the files so that the number of files and the size of the files both remain bounded. For this usage pattern, the logging package provides a RotatingFileHandler import glob import logging import logging.handlers LOG_FILENAME = 'logging_rotatingfile_example.out' # Set up a specific logger with our desired output level my_logger = logging.getLogger('MyLogger') my_logger.setLevel(logging.DEBUG) # Add the log message handler to the logger handler = logging.handlers.RotatingFileHandler( LOG_FILENAME, maxBytes=20, backupCount=5) my_logger.addHandler(handler) # Log some messages for i in range(20): my_logger.debug('i = %d' % i) # See what files are created logfiles = glob.glob('%s' % LOG_FILENAME) for filename in logfiles: print(filename) The result should be 6 separate files, each with part of the log history for the application Bounded code example (external data; do not execute automatically): ```none logging_rotatingfile_example.out logging_rotatingfile_example.out.1 logging_rotatingfile_example.out.2 logging_rotatingfile_example.out.3 logging_rotatingfile_example.out.4 logging_rotatingfile_example.out.5 ``` The most current file is always logging_rotatingfile_example.out, and each time it reaches the size limit it is renamed with the suffix .1. Each of the existing backup files is renamed to increment the suffix (.1 becomes .2, etc.) and the .6 file is erased. Obviously this example sets the log length much too small as an extreme example. You would want to set maxBytes to an appropriate value. Attribution: Adapted from Python Documentation under PSF-2.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE

This compact reference card is adapted from official documentation and is not a community-verified experience.

Python Documentation — Doc/howto/logging-cookbook.rst :: Using file rotation ↗Revision f10166035d60 · PSF-2.0 and attribution
#reference-seed#python#howto#logging#cookbook#using#file#rotation