CodeBlanks Logo Icon CodeBlanks

FileHandler

Learn to write to a file with FileHandler.

FileHandler

logging.FileHandler writes logs to a file. The filename parameter takes a file path; it is added to the logger with addHandler.

import logging

handler = logging.FileHandler("app.log")
handler.setFormatter(logging.Formatter("%(levelname)s:%(message)s"))
logger = logging.getLogger("myapp")
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
logger.info("merhaba")  # written to app.log

You can give the file path relative to the app directory; logs accumulate in the file as the app runs.

Adding handlers

A handler is added to a logger with logger.addHandler(handler). A logger can have many handlers; for example, two handlers can write both to a file and the screen.

logger.addHandler(logging.FileHandler("app.log"))
logger.addHandler(logging.StreamHandler())

Handlers can have separate levels; this is useful to show only errors on the screen while writing all messages to the file. To remove a handler, call removeHandler.

Practice Write to a file with FileHandler and read it

Start with import logging. Define handler = logging.FileHandler("app.log"). Add handler.setFormatter(logging.Formatter("%(levelname)s:%(message)s")). Get logger = logging.getLogger("myapp"). Do logger.addHandler(handler) and logger.setLevel(logging.DEBUG). Write logger.info("merhaba"). Then read the file with open("app.log", "r", encoding="utf-8") and print its content with print(f.read().strip()).

Starter code

main.py
# import the logging module
# define a FileHandler to 'app.log'
# set a format on the handler (level:message)
# get the 'myapp' logger, add the handler and set level DEBUG
# write 'merhaba' at info level
# read the file and print its content

Sample solution

main.py
import logging

handler = logging.FileHandler("app.log")
handler.setFormatter(logging.Formatter("%(levelname)s:%(message)s"))
logger = logging.getLogger("myapp")
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
logger.info("merhaba")

with open("app.log", "r", encoding="utf-8") as f:
    print(f.read().strip())

Expected output

INFO:merhaba

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which parameter does FileHandler take for the file path?

  • output
  • path
  • file
  • filename Correct answer

Explanation: FileHandler takes the file path as its first parameter (filename).

2 Complete the FileHandler call

Question
import logging

handler = logging.____("app.log")
Answer
import logging

handler = logging.FileHandler("app.log")

Explanation: logging.FileHandler('app.log') creates a file handler.

3 Match the FileHandler concepts

Term Meaning
FileHandler Writes to a file
addHandler Adds a handler
setFormatter Sets the format
StreamHandler Writes to the screen

All lessons in Advanced