Creating a Simple Logger
We'll cover the following...
Creating a log with the logging module is easy and straight-forward. It’s easiest to just look at a piece of code and then explain it, so here’s some code for you to read:
Press + to interact
import logging# add filemode="w" to overwritelogging.basicConfig(filename="sample.log", level=logging.INFO)logging.debug("This is a debug message")logging.info("Informational message")logging.error("An error has happened!")# Let's use our file reading knowledge to# read the log filewith open("sample.log") as file_handler:for line in file_handler:print(line)
As you might expect, to access the logging module you have to first import it. The easiest way to create a log is to use the logging module’s basicConfig function and pass it some keyword arguments. It accepts the following: filename, filemode, ...