It is a good idea to store all the error messages raised by a program into a file.The file which stores the messages, especially of errors or exceptions is called a 'log' file and this technique is called 'logging'. When we store the messages into a log file, we can open the file and read it or take a print out of the file later.This helps the programmers to understand how many errors are there, the names of those errors and where they are occurring in the program. This information will enable them to pin point the errors and also rectify them easily.So, logging helps in debugging the programs.
Python provides a module 'logging' that is useful to create a log file that can store all error messages that may occur while executing a program.
There may be different levels of error messages. For example, an error that crashes the system should be given more importance than an error that merely displays a warning message. So, depending on the seriousness of the error, they are classified into 6 levels in 'logging' module, as shown in Table.
|CRITICAL||50||Represents a very serious error that needs high attention.|
|ERROR||40||Represents a serious error|
|WARNING||30||Represents a warning message,some caution is needed.|
|INFO||20||Represents a message with some important information.|
|DEBUG||10||Represents a message with debugging information.|
|NOTSET||0||Represents that the level is not set.|
As we know, by default, the error messages that occur at the time of executing a program are displayed on the user's monitor.Only the messages which are equal to or above the level of a WARNING are displayed.That means WARNINGS, ERRORS and CRITICAL ERRORS are displayed.It is possible that we can set this default behavior as we need.
To understand different levels of logging messages, we are going to write a Python program. In this program, first we have to create a file for logging (storing) the messages. This is done using basicConfig() method of logging module as:
Here, the log file name is given as mylog.txt'.The level is set to ERROR. Hence the messages whose level will be at ERROR or above, (i.e. ERROR or CRITICAL) will only be stored into the log file. Once, this is done, we can add the messages to the 'mylog.txt' file as:
The methodnames can be critical(), error(), warning(), info() and debug(). For example, we want to add a critical message, we should use critical() method as:
logging.critical('System crash - Immediate attention required')
Now, this error message is stored into the log file, i.e. 'mylog.txt'.