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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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()   

chevron_right


Output:



logging-decorator-python

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.