Skip to content

What is logging and How to make it from scratch in python

  • 4 min read
  • by
logging in python

With the help of python, we can build many projects of web scraping, data science, and more. When you are building a project, logging is also an essential part of that. There are many benefits of logging into the program. Here we will talk about what is logging in python and how to do it by the in-built library as well as by building it from scratch.

What is Logging?

Logging is used to record the activities being done during the program’s execution.

When you are building a project(especially a large project)then logging is the most crucial part. By logging, programmers can track and record the progress of the program. Like Which process is initiated? is it completed successfully or not? When was this piece of code executed? Etc.

Benefits of Logging in python:

Logging also helps in debugging. By looking at logs of the program, bug finding becomes easier.

Large industrial-level projects have so many program files and folders. In that projects sometimes one can not encounter an error if it occurs. With logging, by looking at the log file we can specify the area which causes an error.

When you log each error in the program with try and except block, it can make the debugging easier.

If you are working on a project with a team, logging helps each other to understand the process of the task easily.

As you saw, there are many benefits of logging in the projects(especially in large projects).

How to do Logging with an in-built library

In python, the in-built library named logging is available to do logging. Let’s check that out. Here I have written simple logging python code.

import logging

logging.basicConfig(filename="log.txt",filemode='a',format='%(asctime)s %(levelname)s-%(message)s',datefmt='%Y-%m-%d %H:%M:%S')

for i in range(0,15):
    if(i%2==0):
        logging.warning("Log warning")
    elif(i%3==0):
        logging.critical("Log Critical Message")
    else:
        logging.error("Log Error Message")

In logging library after importing it, you have to select the write basicConfig function. In which you have to specify some parameters. For the filename parameters, type the text file name where you want to store all logs. The a in filemode opens the specified text file in the append mode. The format parameter helps to generate logs as per the specified format. And last we can tell how the date should be displayed by the datefmt parameter.

There are three types of warnings in the logging library. Warning, critical, and error. So whichever type of error you want to log, just write logging.warning, logging.critical, or logging.error accordingly.

In the above example when we run the code, the log file will look like this:

Also Read: When to use Precision, Recall, or F1-score?

Do logging with the build from scratch python script

You can do logging with the in-built library as we have shown above. But if you don’t want to use that or if you want to gain knowledge by building it from scratch, Then here’s how you can do it.

from datetime import datetime

class App_Logger:
   def __init__(self):
       pass
   def log(self,file_object,log_message):
       self.now=datetime.now()
       self.date=self.now.date()
       self.current_time=self.now.strftime("%H:%M:%S")
       file_object.write(str(self.date)+ "/" + str(self.current_time) + "\t\t" + log_message +"\n")

Here created a  python file named logger.py. In that created a class named App_Logger. In that, we have defined one function called log. There is a simple line of code in that function that takes the current time and date and print it in the specified text file with the message.

Now, whenever you want to log any event in the project just import the class and open the text file and print the message as you can see below:

from logger import App_Logger

logger=App_Logger()

file=open("Example.txt",'a+')
message = "Sample Message"
logger.log(file,message)
file.close()
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *