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 messages | Numerical Value of log message |
'NotSet' level log message | 0 |
'Debug' level log message | 10 |
'Info' level log message | 20 |
'Warning' level log message | 30 |
'Error' level log message | 40 |
'Critical' level log message | 50 |
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.
- 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.
- 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.
- 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.
- 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.