Search⌘ K

Creating a Simple Logger

Explore how to create a simple logger in Python using the logging module. Understand logging levels, configuration options, and how to log messages and exceptions. This lesson helps you write logs to files or console and manage multiple loggers for clearer debugging and error tracking.

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:

Python 3.5
import logging
# add filemode="w" to overwrite
logging.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 file
with 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, ...