django rotatingfilehandler

# Import necessary modules
import logging
from logging.handlers import RotatingFileHandler

# Configure logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# Configure RotatingFileHandler
log_file = "example.log"
handler = RotatingFileHandler(log_file, maxBytes=1000000, backupCount=5)

# Configure log format
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# Add handler to logger
logger.addHandler(handler)

# Log messages
logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")
logger.critical("This is a critical message")
  • Import the necessary modules from the logging package, including the RotatingFileHandler class.
  • Create a logger instance named logger using logging.getLogger(__name__).
  • Set the logging level for the logger using logger.setLevel(logging.DEBUG). You can choose different levels such as DEBUG, INFO, WARNING, ERROR, and CRITICAL.
  • Define the log file name (log_file) and create a RotatingFileHandler instance named handler. Set the maximum log file size to 1 MB (maxBytes=1000000) and the maximum number of backup log files to 5 (backupCount=5).
  • Define a log message format using logging.Formatter and create a formatter instance named formatter.
  • Set the formatter for the handler using handler.setFormatter(formatter).
  • Add the handler to the logger using logger.addHandler(handler). This associates the handler with the logger so that log messages are directed to the specified file.
  • Log various messages with different severity levels using methods like logger.debug, logger.info, logger.warning, logger.error, and logger.critical. These messages will be recorded in the specified log file with the configured format.