FileHandler is a Python logging handler that writes log records to a file. Attach it to a logger with addHandler so application events remain available after the console closes. section 12.1.2
Listing 12.2 Adding a file handler to the logger
logger = logging.getLogger(__name__)
file_handler = logging.FileHandler("taskier.log") #1
logger.addHandler(file_handler) #2
Create a handler for taskier.log, then attach it to the module logger. section 12.1.2
Write a task event to a log file
task = Task("Laundry") if task.remove_from_db(): logger.warning(f"removed the task {task.title} from the database") # taskier.log removed the task Laundry from the database section 12.1.2
Use FileHandler deliberately in a logging configuration:
- Set the logger level broadly, then assign different levels to individual file handlers when separate files need different severity thresholds. section 12.2.2
- Prevent repeated setup from adding duplicate handlers, because multiple handlers targeting the same file produce duplicate records. section 12.1.5
- Use a stream handler for development console output and format records for readable timestamps, severity, module, and message information. section 12.6
