Mastering Logging in Python (Basics)
A great way to track all of the things your code is doing by looking into a log file. In the beginning print() can server the purpose but as the programs grow, things become overwhelming and hard to manage with print() only. That’s where logging comes into play.
Python provides a built-in module logging, so we don’t need to do anything.
Get Saleh Faize’s stories in your inbox
Join Medium for free to get updates from this writer.
In python there are five levels of logging —
By default, python only shows WARNING and above. Let’s dive into a simple program to get a better understanding.
import logging
def another_function():
logging.debug("This is a debug level log message")
logging.warning("This is a warning level log message")
logging.basicConfig(filename="output.log")
another_function()Above is simple program to use logging and our log will show in output.log file like-
However, only one message appears even though the function logs two messages.. The reason is one is DEBUG level. The log shows records of warning and higher. But we can easily modify that by configuring logging level in basicConfig function.
import logging
def another_function():
logging.debug("This is a warning level log message")
logging.warning("This is a warning level log message")
logging.basicConfig(filename="output.log",
level = logging.DEBUG)
another_function()Now, when we run the program, the log file will contain both messages.
We can format the message as well with custom text, timestamps, and other useful information. Here’s a simple example that adds a custom format and date style to the logs-
import logging
def another_function():
logging.debug("This is a warning level log message")
logging.warning("This is a warning level log message")
datestr = "%m/%d/%Y"
fmtstr = "customlog: %(asctime)s: %(message)s"
logging.basicConfig(filename="output.log",
level = logging.DEBUG,
format = fmtstr,
datefmt = datestr)
another_function()Our log file now looks like -
By default, log files append new messages instead of overwriting existing ones. This is the expected behavior unless configured otherwise.
I hope it gives a basic idea about how logging works in python with logging module. It’s just an intro for a powerful ability that is built-in and ready to use.





