Ask Your Question

Revision history [back]

One way to restrict the size of log files in Python is to use the RotatingFileHandler class from the logging module. This class allows you to specify a maximum size for each log file and automatically rotates to a new file once that size is reached.

Here's an example:

import logging
from logging.handlers import RotatingFileHandler

logger = logging.getLogger(__name__)
handler = RotatingFileHandler('logfile.log', maxBytes=1024, backupCount=3)
logger.addHandler(handler)

In this example, the RotatingFileHandler is created with a maximum size of 1024 bytes (1 KB) and a backup count of 3. Once the log file reaches this size, a new file will be created with a new number at the end (i.e. logfile.log.1, logfile.log.2, etc.) and the old log file will be rotated out.