Log exceptions in Python

Log Exceptions in Python

In any support or development project in the IT companies, the developers and the support engineers depend a lot on the log files to find the root causes of the issues. Log files are usually stored in servers containing the error details of the issues. The process of adding errors in the log file is called logging. Developers can also log exceptions in Python using a module called ‘logging’.

This logging module in Python can help you create the log file, which can save all the error messages that occur while the program is under execution. Though we can log all the error messages, only a few can be critical and might need attention because you don’t want to investigate an error message that is merely a warning.

To help you identify the different levels of error messages, the logging module offers you six levels, as listed in the table below.

LevelNumeric ValueDescription
CRITICAL50Refers to the very crucial error that requires immediate attention.
ERROR40Refers to a serious error
WARNING30Refers to a warning message
INFO20Refers to an important message
DEBUG10Refers to debugging information
NOTSET0It says that the level has not been set

If you have been executing Python programs, you must have seen specific errors in the console. The messages above the level of WARNING are likely to have been seen by you in such cases. It also means that WARNINGS, ERRORS, and CRITICAL errors are the ones that need more attention than the other error messages. However, we can set the default behaviour as per our requirements.

Let us now look at a program that deals with the logging of error messages.

#Python program to illustrate the concept of logging
import logging #importing the logging module

logging.basicConfig(filename='logfile.txt',level=logging.ERROR)
#saves messages which are of level ERROR and above
#into the file 'logfile.txt'

logging.error("Hello, error is occurring in the program.")
logging.critical("It is critical and server might go down soon.")
#these messages which are of level ERROR and above gets saved
#into the logfile.txt file

logging.warning("This is just a warning")
logging.info("This is just FYI")
logging.debug("This is debugging information.")
#the above three error messages warning, info, and debug
#will not be stored into the file as we set the level
#from ERROR level.
Output from the logfile.txt file:

ERROR:root:Hello, error is occurring in the program.
CRITICAL:root:It is critical and server might go down soon.

In the above program, we imported the logging module. After importing the logging module, we called basicConfig() method from the logging module to create the file ‘logfile.txt’ and set the level to ERROR. Setting the level to ERROR means that this program will store only the error messages of type ERROR and above. Since there is only one type above the ERROR level, this program will store the error messages only from the ERROR and CRITICAL levels.

You can notice in the output that the file did not save the error messages of the level types – warning, info, and debug.

Just as how you can log these error messages, you can also log the exceptions into the log file using the logging.exception() method. Let us look at a program to understand how we can save the messages from exceptions into the log file.

How to log exceptions in Python program?

#Python program to log exceptions into log file
import logging #import the logging module

#store logging messages into logexceptions.txt file
logging.basicConfig(filename='logexceptions.txt',level=logging.ERROR)

try:
  num1 = int(input("Enter first number: "))
  num2 = int(input("Enter second number: "))
  num3 = num1/num2
except Exception as msg:
  logging.exception(msg)
else:
  print("The result of division is: ",num3)
Output from the logexceptions.txt file:

ERROR:root:division by zero
Traceback (most recent call last):
  File "C:\Users\Aatmann\Documents\iSapna\Python\Exceptions\logexceptions.py", line 10, in <module>
    num3 = num1/num2
ZeroDivisionError: division by zero

In the program above, we created a file ‘logexceptions.txt’ and set it to log error messages of type ERROR and above. We then added code in the try block to accept two numbers from the keyboard and divide them.

The program raised an exception when we entered the second number as zero, and you can see that the ZeroDivisionError exception is saved in the logexceptions.txt file, as shown in the output above.

We hope you have understood the concept of logging errors and exceptions in Python.

Scroll to Top