Python logging exceptions
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.
Logging Error Level and their Predefined Numeric Values
|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'.
Example to Log Error
#understanding logging of error messages. import logging logging.basicConfig(filename='mylog.txt', level=logging.ERROR) #these messages are stored into the file. logging.error("There is an error in the program.") logging.critical("There is a problem in the design.") #but these are not stored. logging.warning("The project is going slow.") logging.info("You are a junior programmer.") logging.debug("Line no. 10 contains syntax error.")
Example to Log Exceptions into a File
import logging #store logging messages into log.txt file logging.basicConfig(filename='log.txt', level=logging.ERROR) try: a = int(input('Enter a number:')) b = int(input('Enter another number:')) c = a/b except Exception as e: logging.exception(e) else: print('The result of division:', c)
Points to Remember
- An exception is an error that can be handled by a programmer. If the programmer cannot handle it, then it will not be an exception, it will become an error.
- All exceptions occur only at runtime.
- The errors that occur at compilation time are not called exceptions. Also logical errors cannot come into exceptions category.
- When an exception occurs, the program terminates abruptly. Due to this, the important data in the files or databases may be lost or the program may be corrupted.
- All exceptions in Python are represented as classes.
- All exceptions are sub classes of 'BaseException' class.
- All errors (exceptions) are defined as sub classes of 'StandardError' class.
- All warnings are derived as sub classes from 'Warning' class.
- All user-defined exceptions should be derived from 'Exception' class.
- All exceptions in a Python program should be handled to make it robust.
- Exception handling is done using try-except-finally-else blocks.
- Try block contains the statements where there is a possibility for exceptions.
- Except block handles the exceptions that are raised in the try block.
- Finally block is always executed irrespective of whether there is an exception or not.
- When there is an exception in the try block, PVM jumps into relevant except block where the exception is handled.
- When there is no exception, then PVM does not execute except block, rather it will execute else block.
- To handle multiple exceptions, we can use multiple except blocks.
- To handle multiple exceptions, we can use single except block with all exception class names in a tuple.
- The 'assert' statement is useful to ensure that a given condition is True, otherwise to raise AssertionError.
- The exceptions which are already available in Python are called built-in exceptions. Similar to these exceptions, the programmer can also build his own exceptions, called user - defined exceptions.
- The 'raise' statement is useful to raise user-defined exceptions.
- The 'logging' module is useful to store exception or error messages into a log file. Logging is useful to debug the programs.