In addition to logging to the console, you can also store log messages in files for later analysis or archiving. This is particularly useful for long-running applications or when you need to review historical logs.
Creating a File Handler
Import the FileHandler:
Python
import logging.handlers
Create a File Handler:
Python
file_handler = logging.handlers.RotatingFileHandler(‘app.log’, maxBytes=102400, backupCount=5)
This creates a file handler that writes logs to the app.log
file. When the file size exceeds 100 KB (102400 bytes), a new file is created and the old file is renamed to app.log.1
, app.log.2
, etc., up to 5 backup files.
Set the Formatter:
Python
formatter = logging.Formatter(‘%(asctime)s – %(name)s – %(levelname)s – %(message)s’)
file_handler.setFormatter(formatter)
Add the Handler to the Logger:
Python
logger.addHandler(file_handler)
Using a Rotating File Handler
Rotating file handlers are useful for managing log file size and preventing them from becoming too large. You can configure the maxBytes
and backupCount
parameters to control the maximum file size and the number of backup files.
Using a TimedRotatingFileHandler
For rotating logs based on time intervals (e.g., daily, weekly, monthly), use the TimedRotatingFileHandler
:
Python
file_handler = logging.handlers.TimedRotatingFileHandler('app.log', when='midnight', interval=1)