How To Log Python Exception and Error?

Exceptions are rare and unexpected situations where a Python script or tool may throw in daily usage. An exception is also called errors because it generally stops the execution of the program. In order to prevent the future occurrence of the exceptions, we can inspect them and solve them accordingly. In order to inspect and solve exceptions, the exceptions should be logged or saved into a file.

Python Exception and Error

Python errors or exceptions can occure in different situations. One of them is division by zero exception which is very popular in programming. If a non-zero number is divided into zero this operation results and exception or error named “division by zero“.

try:
    1/0
except ZeroDivisionError as e:
    logging.error(e)

logging Module

Logging is a module that can be used for logging operations. The exception() method of the logging module can be used to output an exception to the standard error.

import logging

try:
    1/0
except ZeroDivisionError as e:
    logging.exception(e)

Log Into A File

A Python exception or error can be logged into a file too. We will just put some code inside the exception part ot the try-exception mechanism. The exception part is executed when an exception occurs in try.

try:
    1/0
except Exception as e:
    f = open("error.log","a")
    f.write(str(e))
    f.close()

Leave a Comment