OSPython.029: Logging to Files with FileHandler

Colored-pencil comic-book illustration of a Python application writing log messages to a file.

Python can send log messages to a file instead of leaving them only in the terminal. This lesson focuses on one job: saving useful application logs to disk with the standard logging module.

Start with OSPython.028: Python Logging Basics if you need a refresher on DEBUG, INFO, WARNING, ERROR, and CRITICAL.

Write Logs Directly To A File

The shortest path is logging.basicConfig() with a filename. Python then creates a file handler for you and writes messages that meet the configured severity threshold.

import logging
logging.basicConfig(filename="app.log", level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logging.info("Application started")
logging.warning("Disk space is getting low")

By default, the file is opened in append mode, so new log records are added to the end instead of erasing earlier entries. You can explicitly set filemode="w" when you intentionally want each run to replace the previous file.

Corey Schafer demonstrates Python logging to files, severity levels, and log formatting.

Use FileHandler When You Need Explicit Control

logging.FileHandler is useful when you want to create the file destination yourself and attach it to a named logger. A handler decides where a log record goes; a formatter decides how that record looks.

import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler("service.log")
formatter = logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.info("Service started")

This pattern separates the logger from its destination. Later lessons can add console output or rotating files without changing every logger.info() and logger.error() call in the program.

Corey Schafer explains named loggers, handlers, and formatters in Python.

Basic Troubleshooting

If the file stays empty, first check the severity threshold. An INFO message will not be written when the logger or handler is set to WARNING. Also verify that the process has permission to write to the chosen directory.

If you are inspecting the log with Python, the earlier file reading and writing lesson covers basic file access. Never place passwords, API keys, authentication tokens, or other secrets in routine logs.

Exercise

Create a script that writes INFO and ERROR messages to practice.log. Run it twice and confirm that the second run appends new entries. Then change the file mode to "w" and observe the difference.

Knowledge Check

  1. What does the filename argument in basicConfig() do?
  2. What is the default behavior of append mode?
  3. What does a FileHandler control?
  4. What does a formatter control?

Answers

  1. It sends logging output to the named file.
  2. It keeps existing content and adds new records at the end.
  3. It controls the log destination.
  4. It controls how log records are displayed.

Next Lesson

This lesson intentionally stops at ordinary file logging. Log rotation belongs in the next focused lesson rather than being mixed into this one.

References

Primary reference: Python Logging HOWTO. Python documents FileHandler as the standard handler for sending log records to disk files.

BitcoinVersus.Tech

Editor’s Note

We volunteer daily to help keep the information on this platform verifiably accurate. If you would like to support our independent research, please donate here: 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb

BitcoinVersus.tech is not a financial advisor. Content is provided for informational purposes.

One response to “OSPython.029: Logging to Files with FileHandler”

  1. […] lesson builds directly on OSPython.029: Logging to Files with FileHandler. If you need the logging levels first, review OSPython.028: Python Logging […]

    Like

Leave a comment