liveBook · Manning

FileHandler

As explained in Python How-To

FileHandler is a Python logging handler class that writes log records to a file.

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

How Python How-To covers it

How deep it goes
Demonstrates construction, logger attachment, severity filtering, duplicate-handler hazards, and handler removal without examining handler internals.
Examples
Uses taskier.log, task removal warnings, severity-specific log files, and a helper that reads log contents.
What it assumes
Assumes basic logger retrieval and text-file reading while demonstrating handler setup from the logging configuration context.
What you can do after
Operate/configure Python logging to save records, separate files by severity, and avoid duplicate handler output.
How it connects
Connects FileHandler with loggers, logging levels, LogRecord objects, stream handlers, and log formatting.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.