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():
logger = logging.getLogger( 'exc_logger' )
logger.setLevel(logging.INFO)
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()
print (logger)
def exception(logger):
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
if __name__ = = '__main__' :
divideStrByInt()
|
Output:
Last Updated :
08 May, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...