×

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

Python email utils

Python is a popular programming language in this growing world. There are many resources to learn python online without spending a single penny. In this article, we will talk about a...

4 minutes read.

How to Install Pandas in Python?

Pandas is a library created in Python for handling and analyzing data. Pandas provides a variety of procedures and data structures for manipulating time series and numerical data.  Pandas is...

3 minutes read.

Python PPTX

Python-pptx is a python library that enables the user to create and update PowerPoint (.pptx) presentations. It is used to create modified PowerPoint presentations from the db content that can...

10 minutes read.

Syntax of Map function in Python

In this tutorial, we will understand what the map function in Python is meant. Further, we will see the syntax to be used for the same in python language. We...

3 minutes read.

Removing the First Character from the String in Python

String The string is the collection of characters. The strings in python are “immutable”; we cannot change a string once they are created. In python, whatever data we take as input...

4 minutes read.

The Calendar Module of Python

The calendar module provides calendar features, including printing functions for a specific month or year. Default is the first day of the week on Monday and the last day on Sunday...

3 minutes read.

Python Project Ideas Based On Django

Introduction If you have learned Python and you are an expert in Django, then your practical skills should be excellent in this field. If you want to check your practical skills,...

9 minutes read.

Exponentiation in Python

What is an Exponent in Python? Exponent is a fundamental mathematical concept that is used in many different areas, such as engineering, physics, and finance. In mathematics, an exponent is a...

4 minutes read.

Uint8 Python

Python: 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 is said...

3 minutes read.

Python Deep Copy and Shallow Copy

Assignment statements in Python create bindings between a target and an object, not copies of them. The = operator only makes a new variable that shares the reference to the...

3 minutes read.

Isreal() 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...

4 minutes read.

wxPython Panel class

wxPython Panel class The Widgets which is shown in the frame of GUI window such as text box, buttons, static text etc. are put inside the panel class of the wxpython...

2 minutes read.

Python Infinity

Introduction We will discover how to define an infinite number in Python in this tutorial. Infinity, as we all know, is a value that cannot be defined and can either be...

5 minutes read.

Crash Course on Python by Google

There is a new, free Python programming course offered by Google on Coursera. No programming experience is necessary. There are numerous Python courses available, but when you learn that Google is...

5 minutes read.

Best app for python

What is python? Python is a prevalent, general-purpose, and high-level programming language. Python Programming Language is appropriate for experienced programmers and also for beginners. Python programming language is being utilized by...

19 minutes read.

Python for Data Analysis

Data analysis uses various techniques to read, illustrate, manipulate and evaluate a particular data. You can have access to the data and keep the data updated regularly. You can append...

4 minutes read.

Python Set difference_update() method

Python Set difference_update() method The set.difference_update() method in Python removes the items that exist in both sets. Syntax set.difference_update(set1) Parameter set- This argument represents a set (minuend) set1- This arguments represents a set(subtrahend) Return None Example 1 # Python program explaining # the set.difference_update()...

2 minutes read.

Artificial intelligence mini projects ideas in python

Artificial intelligence "The human race started from the invention of the wheel", and today we are about to advance to the Industrial level 4.0, where machines can work, talk, think and...

6 minutes read.

Append key Value to Dictionary in Python

The Python dictionary is one of the built-in data types. Elements of dictionaries are key-value pairs. In Python, there are numerous ways to add dictionaries. Let's examine some of the...

9 minutes read.

Python Break Statement

In Python, loops are used to automate and repeat processes in an effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration,...

2 minutes read.