Saturday, November 16, 2024
Google search engine
HomeLanguagesCreate an Exception Logging Decorator in Python

Create an Exception Logging Decorator in Python

Prerequisites: Decorators in Python, Logging in Python

Logging helps you to keep track of the program/application you run. It stores the outputs/errors/messages/exceptions anything you want to store. Program executions can be debugged with the help of print statements during the runtime of code. But the code is not elegant and not a good practice. Logging is a standard process an application to follow to store the process in a log file that would help to analyze/debug in the future/unexpected situations.

Logging for exceptions

For a logger, we have different levels of logging a message. As the article is limited to exception logging, we will go with the ‘INFO’ level log message which helps us to check if the code is working as expected. If there is an exception, it will store exception into the log file using logger object logger.exception(“some exception raised”)

Below is the implementation.




import logging
from functools import wraps
   
  
def create_logger(): 
      
    #create a logger object
    logger = logging.getLogger('exc_logger')
    logger.setLevel(logging.INFO)
      
    #create a file to store all the 
    # logged exceptions
    logfile = logging.FileHandler('exc_logger.log')
      
    fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    formatter = logging.Formatter(fmt)
      
    logfile.setFormatter(formatter)
    logger.addHandler(logfile)
      
    return logger
   
  
logger = create_logger()
  
# you will find a log file
# created in a given path
print(logger)
   
  
def exception(logger):
      
    # logger is the logging object
    # exception is the decorator objects 
    # that logs every exception into log file
    def decorator(func):
          
        @wraps(func)
        def wrapper(*args, **kwargs):
              
            try:
                return func(*args, **kwargs)
              
            except:
                issue = "exception in "+func.__name__+"\n"
                issue = issue+"-------------------------\
                ------------------------------------------------\n"
                logger.exception(issue)
            raise
               
          
        return wrapper
    return decorator
   
  
@exception(logger)
def divideStrByInt():
    return "krishna"/7
  
# Driver Code
if __name__ == '__main__':
    divideStrByInt()   


Output:

logging-decorator-python

RELATED ARTICLES

Most Popular

Recent Comments