How to use Logs & work with the Logging Module in Python— Basics

Alexander Schlee
3 min readMar 31, 2021

This article should give you a simplified introduction how you can use Logs when you write your code in Python.

First, what are Logs and why do we need to use it when we build our Project, for example with Selenium?

In simple terms, Logs are used to record the steps which have been taken during a specific project.

Logging allows you to debug your code so you can remove the errors but it also gives you the possibility to analyze the performance of your application and retrace certain steps made by the user.

Let’s take a quick look how to set up a simple Logging- Scenario in Python. First, we have to import the Logging-Module, which is a standard library and which allows a developer to capture log messages:

This module has 5 different hierarchical levels of logs that a certain Logger can be configured to:

  1. DEBUG: Detailed information, typically used when diagnosing problems
  2. INFO: Confirmation that everything works as expected
  3. WARNING: An unexpected event happened but the program is still working as expected
  4. ERROR: The problem seems to be more serious and the software is not able to perform its function
  5. CRITICAL: A fatal error, the program can not continue running

Now let’s see how to set up the logging configurations:

logging configurations

Within the basicConfig method which comes along with the logging module you can set up the desired behaviour of your logger.

In the given example we want to create a log file and we provide the following filename for this document: ,,logs_example.log”.

In the format section we want to sort the messages using the timestamps in an ascending order, print the level name and the message itself.

The dateformat should contain the year, the month, the day, the hour, the minute and the second.

For simplicity reasons we just use the INFO-Level.

The filemode is set up as “w” (write), so that everytime we run our code, the previous logs are replaced with the new logs.

In our example project we will run a simple Selenium Script which will capture 4 different steps (Open the Browser, click on two different buttons and close the driver):

After the logfile was created, the following logs can be retrieved:

Logs

We can see that the logs match exactly our configurations in the last step.

If you are interested in the step by step tutorial of this project, check out the video version on Youtube:

--

--

Alexander Schlee

Python Enthusiast | IT- Consultant | Focussing on projects related to Data Science and Testautomation