Python
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.
Exercise 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()).
Show example solution
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())
Test yourself
-
Which parameter does FileHandler take for the file path?
Show answer
filename — FileHandler takes the file path as its first parameter (filename).
-
Complete the FileHandler call
import logging
handler = logging.____("app.log")
Show answer
import logging
handler = logging.FileHandler("app.log")
-
Match the FileHandler concepts
- FileHandler
- Writes to a file
- addHandler
- Adds a handler
- setFormatter
- Sets the format
- StreamHandler
- Writes to the screen
Next lesson: dictConfig