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.
Logging
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.
Decorators
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') 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 = 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 divideError(): return "string"/7 if __name__ == '__main__': divideError()
Output –
2020-05-23 15:19:18,408 - exc_logger - ERROR - exception in divideError - Traceback (most recent call last): File "/Users/Desktop/Programs/Test.py", line 25, in wrapper return func(*args, **kwargs) File "/Users/Desktop/Programs/Test.py", 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