×

Python logging Module

Python logging Module Introduction

By logging word we understand the tracking of the events which happens when we run some software. Logging process is very important part for developing software, debugging it or running the software.

If we do not maintain the record of the logging process (by any means), then there is very little chance that we can track the root of the problem as the program crashes.

And even if we try to track down the root cause of the problem, it will going to takes lots of time. But if we maintain the records of the previous logging process for the particular software, we are leaving a train of breadcrumbs for us in the future. This is because if we have records of logging of a software, we can easily track down the root cause of the problem without wasting lots of time on it.

For example

 We can face a number of situations while working on some programs that we are expecting an integer in the result but we have been given a float value in the output. And if we have a cloud service APIs at the backend, we have to down the service for maintenance and track down the root cause for the problem.

This will lead us into a lot of trouble and we will be wasting our lot of time for it. And, in programming world such problems are hard to control properly, so we have to maintain a proper record of logging process to determine and control it.

In this tutorial, we are going to discuss about Python logging module and learn how we can do the logging process using the Python logging module.

How does logging module work?

In Python, we have a built-in logging module for the logging process. To use this Python logging module, we don't have to go through any installation process and we can directly import this module in our Python program from the Python library.

The Python logging module allow us to write the status messages to a program file & scripts or any other output streams used in the software. The file on which Python logging module will show the status messages can contain some useful information regarding the software like what problem is arisen while executing the code or/and the part of the code that is executed successfully.

Why using a print statement is not a good option?

Many software or even web developers use the print statement to check or validate if the concept or logic used by them in program statements are executed properly or some error has occurred in the concept. But using the print statement concept to check the validation of logic in the program statement is not a good practice to adapt by new developers. This is because, maybe this approach of print statement may solve the errors in simple logic statement but we can't determine the actual problem in complex scripts or statement using this print statement concept. This idea of using print statement for checking the validation of logic always fails in complex scripts, so we don't have to adapt this concept as being a developer.

Python Logging Messages level:

As we have learnt, the Python logging module is very helpful in writing the status messages to program scripts and file. Python logging module have many in-built levels of log messages which we can use while writing the status messages. Now, we will learn about these levels present in the Python logging module.

Level of messages in logging:

In Python logging module, we have the following built-in levels of the log messages in the Python library:

  • Debug log message: The debug log messages are used to give detailed information on the typically of particular interests when we are diagnosing the problem in the program script only.
  • Warning log message: The warning log messages given by Logging module are used to indicate that something unexpected happened to our software while we are running the program. We can also use the warning log message to indicate that some problems that can be faced in the near future.
  • Info log message: The info log messages in the logging module are used to provide the confirmation that the things, logic or program are working perfectly as expected.
  • Critical log message: The critical log message tells us that some serious error has been occurred while running the program. It also indicates that the program we are running itself is not able to continue successfully running.
  • Error log message: The error log message in the logging module tells us that a serious problem has been occurred in the program. And, it also indicates that due to some serious problem in the program, the software will not be able to perform some of its functions either completely or properly.

Other than all the above-mentioned levels of log messages, we have an option to create more levels for the log messages. As a developer, we can create more levels of log messages using the Python logging module if required. But most of the times, these above-given levels of log messages are sufficient for logging a software. The log messages levels that we have discussed above have assigned with their specified numerical value in the logging module. By this numerical value assigned to the built-in log messages, we can track down or call out these status messages during logging.

Level of log messagesNumerical Value of log message
'NotSet' level log message0
'Debug' level log message10
'Info' level log message20
'Warning' level log message30
'Error' level log message40
'Critical' level log message50

Features of logging module:

The Python logging module comes with a pack of many rich features which are very helpful during logging of a software. There are several rich features such as classes, constants and methods in it.

  • The items present in the module with all the caps are the constants of logging.
  • All the lowercase items present in the module are methods of logging.
  • All the uppercase items present in the module are classes of logging.

Objects in logging module:

As like classes, methods or constants, there are many several logger objects are present in the logging module. We can use this logger objects in the Python while logging a software using logging module. Following are the list of logger objects that are offered by the logging module to us:

  • Logger.log(lvl,msg): This logger object will return or show us the log messages i.e., msg with integer level i.e., lvl showing on this logger object.
  • Logger.setLevel(lvl): This logger object or function sets the threshold of the logger object to the given level i.e., lvl. It means that this logger object will ignore all the log messages below the log level we defined in it.
  • Logger.exception(msg): This logger object will show us the log message the Error level of log message on it.
  • Logger.info(msg): This logger object will show us the log message the Info level of log message on it.
  • Logger.critical(msg): This logger object will show us the log message the Critical level of log message on it.
  • Logger.warning(msg): This logger object will show us the log message the Warning level of log message on it.
  • Logger.error(msg): This logger object will show us the log message the Error level of log message on it.
  • Logger.filter(record): This logger object or method will apply the filter present in the record to the records of logging provided to us. And, this logger object returns true in the output only if logging record is yet to be processed otherwise it will show false.
  • Logger.addFilter(filt): This logger object or method will add the specific filter i.e., filt as we will specify in the logger object to this logger.
  • Logger.removeFilter(filt): This logger object or method will remove the specific filter i.e., filt as we will specify in the logger object to this logger.
  • Logger.hasHandlers(): This logger object or method will check that if there is any handler configured to the logger or not.
  • Logger.addHandler(hdlr): This logger object or method will add the specific Handler i.e., hdlr as we will specify in the logger object to this logger.
  • Logger.removeHandler(hdlr): This logger object or method will remove the specific Handler i.e., hdlr as we will specify in the logger object to this logger.

Now, we have learned all the logger objects present in logging module and why they are used in the logging process. So, let's move to the basics of logging and then we will import logging module and use it in a Python program.

Basics of logging

Here we will understand about all the basics for using the logging module in the Python program. We will learn that how simple it is for us to record all the events in a file that happens during the process of logging. To perform this task, we have to simply import the logging module in our Python program.

Syntax: We can import the logging module in our Python program using the following syntax in it:

 import logging

After using this syntax, we are able import and use all the features and functions of logging. With the help of it, we can start logging with the program.

  1. First, we have to create and configure the logger. The logger we creating can have several parameters. But most importantly, we have to pass the name of the file in which we want to record all the events that will happen during logging.
  2. Now here, we can also set the format of the logger. If we don't set, then by default the file we created will works in the append mode. But as we mentioned, we can change the format to write mode also if required.
  3. Also, we can set the levels of the logger that will act as the threshold for tracking down based on the numerical values, we have provided in each level. In this, there are several attributes that we can pass as parameters while setting the level of the logger.
  4. We can check out list of all these parameters in the Python library that has been given. Then, we can choose the attributes according to our requirements during logging.

Now, look at the following where we will create a logging object and use the various methods present in the logging module.

Example:

 # importing the logging module
 import logging
 # Create and configure the logger file for logging
 logging.basicConfig(filename="ANewFile.log",
      format='%(asctime)s %(message)s',
           filemode='w') # here we set the file format to write mode
 # Creating a logger object in the log file
 LoggerObject = logging.getLogger()
 # We are setting the threshold of logger to the DEBUG value
 LoggerObject.setLevel(logging.DEBUG)
 # Now we are using Test messages of different log levels
 LoggerObject.debug("This is a harmless log object debugged Message!")
 LoggerObject.info(" This is an info log level debug message!")
 LoggerObject.warning("This is a warning log level debug message!")
 LoggerObject.error("This is an error log level debug message!")
 LoggerObject.critical("This is a critical log level debug message!") 

Output of the program:

 After running the program, a log file with name ANewFile.log will be created in our disk. When we open the log file, we can see the following messages in it:
 2021-05-04 16:23:55,234 This is a harmless log object debugged Message!
 2021-05-04 16:23:55,234 This is an info log level debug message!
 2021-05-04 16:23:55,234 This is a warning log level debug message!
 2021-05-04 16:23:55,234 This is an error log level debug message!
 2021-05-04 16:23:55,234 This is a critical log level debug message! 

So, as we can see we can all the status log message into a record log file. The logging record file will be saved in our device's hard disk. The status log messages can set according to the level of log messages and the type of information it is displaying.

Now, we will learn some basic functions of logging process and the log file and use them in our Python program while importing the logging module.

1. Modifying the logging output:

We can change or modify the output or status messages of the logging process using our Python program. We can understand this through an example. The %(asctime) we used while created in the above example will give us date & time in the log file in the output. Now, in the following example program we will not use the %(asctime) and see the log file in the output of the program.

Example: Look at the following Python program:

 # importing the logging module
 import logging
 # Not using the %(asctime)s function in the file format
 logging.basicConfig(filename="ANewFile.log",
      format='%(process)d-%(levelname)s-%(message)s',
           filemode='w') # here we set the file format to write mode
 # Creating a logger object in the log file
 LoggerObject = logging.getLogger()
 # We are setting the threshold of logger to the DEBUG value
 LoggerObject.setLevel(logging.DEBUG)
 # Now we are using Test messages of different log levels
 LoggerObject.debug("This is a harmless log object debugged Message!")
 LoggerObject.info("This is an info log level debug message!")
 LoggerObject.warning("This is a warning log level debug message!")
 LoggerObject.error("This is an error log level debug message!")
 LoggerObject.critical("This is a critical log level debug message!") 

Output

 10364-DEBUG-This is a harmless log object debugged Message!
 10364-INFO- This is an info log level debug message!
 10364-WARNING-This is a warning log level debug message!
 10364-ERROR- This is an error log level debug message!
 10364-CRITICAL-This is a critical log level debug message! 

As we can see in the above output, there is no date & time is mentioned in the status messages given in log file. That's how we can modify the output status messages in log file while logging by giving the functions in the program according to our need.

2. Logging using the variable data:

We can show the log status messages not only by writing them in the logger objects but we can also use the variables for the logging process and can show the status messages with the variable data. Let's understand this through the following example:

Example:

 # importing the logging module
 import logging
 # Modifying the log file we are using
 logging.basicConfig(filename="ANewFile.log",
      format='%(asctime)s %(process)d %(levelname)s %(message)s',
           filemode='w') # here we set the file format to write mode
 # Creating a logger object in the log file
 LoggerObject = logging.getLogger()
 # We are setting the threshold of logger to the DEBUG value
 LoggerObject.setLevel(logging.DEBUG)
 # defining a variable for log file
 LogVariable = 'Robert Downey Junior'
 # using the variable data in the log status message
 logging.info('%s found an unique exception in the program', LogVariable) 

Output:

2021-05-06 03:52:40,381 8480 INFO Robert Downey Junior found a unique exception in the program

As we can see in the output, variable data is used in the log message. We can use the variable data in the log status message by this method.

3. Capturing the traces of error:

That's the most important part of the logging. We can track down error and leave the traces of error in the log file with error messages. We will learn only about the exc_info function here.

With the help of exc_info function, we can capture the traces of error and exception too. We will use the exception level log message here and see how this function can capture the exception in the log file.

Example:

 # importing the logging module
 import logging
 # Modifying the log file we are using
 logging.basicConfig(filename="ANewFile.log",
      format='%(asctime)s %(process)d %(levelname)s %(message)s',
           filemode='w') # here we set the file format to write mode
 # Creating a logger object in the log file
 LoggerObject = logging.getLogger()
 # We are setting the threshold of logger to the DEBUG value
 LoggerObject.setLevel(logging.DEBUG)
 # defining variables for capturing exception
 m = 26 
 n = 0
 o = 24
 # using try and catch method
 try:
     x = (m+o) / n
 except Exception as e:
     # capturing the exception in log file
     logging.error("Exception occurred", exc_info=True) 

Output of the program:

 2021-05-06 03:58:41,695 5868 ERROR Exception occurred
 Traceback (most recent call last):
   File "C:\Users\Manish\Downloads\code.py", line 21, in <module>
     x = (m+o) / n
 ZeroDivisionError: division by zero 

As we can see that, we have captured down the exception in the program. If we don’t set the exc_info parameter equals to true, it will not be able to capture any exception or error that occurs in the program or in the software.

That's how we can track down exception and error in the program. There are so many functions in the logging module that we can use in our Python program during logging of a software or a source code. With the help of logging module and its functions, we can capture the traces of all error in a log file and can save the file in the disk for future references. That's how we can use the Python logging module for an effective logging process.


Related Topics

How to declare array in python

How to declare array in python? Arrays are a great way of storing our numeric values into a variable in continuous locations. For declaring an array in C language, we used...

4 minutes read.

Python String center() method

Python String center() method The center() method will center align the string, using a specified character (space is default) as the fill character. Syntax string.center(width[, fillchar]) Parameter width This parameter represents the length of the returned string. fillchar...

1 minute read.

Gethostbyname() function in Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python SciPy Library

Introduction SciPy, a logical library for Python is an open-source, BSD-authorized library for arithmetic, science, and design. The SciPy library relies upon NumPy, which gives advantageous and quick N-dimensional exhibit control....

6 minutes read.

Event Key in Python

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Python datetime

Python provides a module named datetime to work with the date and time. Sometimes in the real life application development, we need to work with the date and time. The date is...

3 minutes read.

Attributes in python

In this article, we shall learn about attributes in python. Classes are a mix of data and functions, which in reality mean attributes and methods respectively. Typically, the body of a...

3 minutes read.

Python Dictionary Methods

Python Dictionary Methods Python has a set of built-in methods that dictionary objects can call. All the python dictionary methods are as follow: Methods Description clear() The dictionary.clear() method removes all the elements...

3 minutes read.

Python Kwargs Example

In this article, we'll talk about Python's kwargs notion. In Python, kwargs has two stars and passes a variable number of keyworded argument lists to the function, whereas args has...

5 minutes read.

Python Knapsack problem

Python Knapsack problem Before we dig down about Knapsack problems in Python, first let's have a look at what is actually a knapsack problem. What is a knapsack problem? A problem from the...

5 minutes read.

Python List reverse() method

 Python List reverse() method The list.reverse () method in Python reverses the elements of the list in place. Syntax list.reverse() Parameter NA Example 1 # Python program explaining # the list.reverse() method weekList = ['Sun','Thurs','Mon','Fri', 'Tues', 'Wed'] print("Actual week list: ",weekList) #...

1 minute read.

How to uninstall python

To un-install Python, we need to follow different procedures in different operating systems. In this article, we will discuss the un-installation process of Python in Windows, Mac, and Linux operating...

4 minutes read.

Python Hash Table

An Introduction to Hashing A technique which used to identify a particular object uniquely from a set of similar objects is known as Hashing. Some real-life examples of hashing implementations include: A...

9 minutes read.

Python Constructor

Introduction A constructor is defined as the special kind of function or method that is used for instance variables initialization during the creation of an object of a class. The constructor's task...

5 minutes read.

Slicing of a String in Python

In this tutorial, we will learn about slicing of a string in Python. First of all, let us know what String and Slicing is. String String is a group of characters that...

6 minutes read.

Python type() Function

Python type() Function The type() function in Python returns the type of an object. The return value is a type object and generally the same object as returned by object.__class__. Syntax class type(object)      ...

1 minute read.

Filter List in Python

Python: Python is one of the most used programming languages, as it is used widely in software and data analysis, web development, etc. It is said to be a user-friendly programming...

3 minutes read.

_dict_ in Python

An unordered collection of data values known as a dictionary can be used in Python to store data values similar to a map. Dictionaries can also store a key: value...

6 minutes read.

Decision Tree Classification in Python

In this article, we will learn the implementation of the decision tree in Sklearn, which is nothing but the Scikit Learn library of python. First, we should learn what classification...

12 minutes read.

How to make a firewall in Python?

Firewall: The firewall is a network which controls the incoming and outgoing network traffics of a monitor. It blocks the dataset based on the set of rules written in the security...

3 minutes read.