Create an Exception Logging Decorator in Python

Welcome to the blog. In this tutorial, we will learn how to Create an Exception Logging Decorator in Python.


Debugging a project can take countless hours of a developer’s time. But using logs can be a great help to the developer to understand what the code actually does. Logging provides the developer with the exact line at which the program failed. With logging, we can know if something goes wrong and also the cause of the problem. There is a built-in module in Python that allows writing allows writing status messages to any output streams.


Decorator is a very powerful tool in Python programming language. They allow the programmer to modify the behavior of functions and classes. They allow the programmer to wrap a function in another function in order to extend the behavior of the wrapped function without changing it.

Python program of Exception Logging Decorator

Below is the code implementation-

import logging 
from functools import wraps 
def Logger():  
    logger = logging.getLogger('exc_logger') 

    logfile = logging.FileHandler('exc_logger.log') 
    fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    formatter = logging.Formatter(fmt) 

    return logger 
logger = Logger() 
def exception(logger):
    def decorator(func): 
        def wrapper(*args, **kwargs):     
                return func(*args, **kwargs) 
                issue = "exception in "+func.__name__+"\n"
                issue = issue+"-\n" 
        return wrapper 
    return decorator 
def divideError(): 
    return "string"/7

if __name__ == '__main__': 

Output –

2020-05-23 15:19:18,408 - exc_logger - ERROR - exception in divideError
Traceback (most recent call last):
  File "/Users/Desktop/Programs/", line 25, in wrapper
    return func(*args, **kwargs)
  File "/Users/Desktop/Programs/", line 36, in divideError
    return "string"/7
TypeError: unsupported operand type(s) for /: 'str' and 'int'

Also read: How to make chain of function decorators in Python

Leave a Reply

Your email address will not be published. Required fields are marked *