Building on Ian’s example, if you’re dealing with large logs, managing file sizes becomes important. You don’t want a single log file to grow endlessly. That’s where the RotatingFileHandler comes in handy:
import logging
from logging.handlers import RotatingFileHandler
# Create a logger
logger = logging.getLogger()
# Set the logging level
logger.setLevel(logging.INFO)
# Set up a RotatingFileHandler
handler = RotatingFileHandler('app.log', maxBytes=2000, backupCount=5)
# Format the logs
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
# Attach the handler to the logger
logger.addHandler(handler)
# Log some messages
logger.info('This is an info message')
logger.error('This is an error message')
This setup creates a RotatingFileHandler that limits each log file to 2000 bytes and keeps up to 5 backup files. It’s super useful when you need to maintain python log to file functionality efficiently without bloating your storage.