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

Level Numeric value Description
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:

logging.basicConfig(filename='mylog.txt', level=logging.ERROR)

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

CopiedCopy Code

#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.")"You are a junior programmer.") 
logging.debug("Line no. 10 contains syntax error.")

Example to Log Exceptions into a File

CopiedCopy Code
import logging 
#store logging messages into log.txt file 
logging.basicConfig(filename='log.txt', level=logging.ERROR) 
   a = int(input('Enter a number:')) 
   b = int(input('Enter another number:')) 
   c = a/b 
except Exception as e: 
else: print('The result of division:', c)

Points to Remember

  1. 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.
  2. All exceptions occur only at runtime.
  3. The errors that occur at compilation time are not called exceptions. Also logical errors cannot come into exceptions category.
  4. 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.
  5. All exceptions in Python are represented as classes.
  6. All exceptions are sub classes of 'BaseException' class.
  7. All errors (exceptions) are defined as sub classes of 'StandardError' class.
  8. All warnings are derived as sub classes from 'Warning' class.
  9. All user-defined exceptions should be derived from 'Exception' class.
  10. All exceptions in a Python program should be handled to make it robust.
  11. Exception handling is done using try-except-finally-else blocks.
  12. Try block contains the statements where there is a possibility for exceptions.
  13. Except block handles the exceptions that are raised in the try block.
  14. Finally block is always executed irrespective of whether there is an exception or not.
  15. When there is an exception in the try block, PVM jumps into relevant except block where the exception is handled.
  16. When there is no exception, then PVM does not execute except block, rather it will execute else block.
  17. To handle multiple exceptions, we can use multiple except blocks.
  18. To handle multiple exceptions, we can use single except block with all exception class names in a tuple.
  19. The 'assert' statement is useful to ensure that a given condition is True, otherwise to raise AssertionError.
  20. 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.
  21. The 'raise' statement is useful to raise user-defined exceptions.
  22. The 'logging' module is useful to store exception or error messages into a log file. Logging is useful to debug the programs.