Create an Exception Logging Decorator in Python Last Updated : 08 May, 2020 Comments Improve Suggest changes Like Article Like Report 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. Python3 1== 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: Comment More infoAdvertise with us Next Article Create an Exception Logging Decorator in Python K krishna krish Follow Improve Article Tags : Python Python Decorators Practice Tags : python Similar Reads Concrete Exceptions in Python In Python, exceptions are a way of handling errors that occur during the execution of the program. When an error occurs Python raises an exception that can be caught and handled by the programmer to prevent the program from crashing. In this article, we will see about concrete exceptions in Python i 3 min read EnvironmentError Exception in Python EnvironmentError is the base class for errors that come from outside of Python (the operating system, file system, etc.). It is the parent class for IOError and OSError exceptions. exception IOError - It is raised when an I/O operation (when a method of a file object ) fails. e.g "File not found" or 1 min read Difference between Logging and Print in Python In Python, print and logging can be used for displaying information, but they serve different purposes. In this article, we will learn what is python logging with some examples and differences between logging and print in Python. Logging in Python Logging in Python is a technique to display useful m 3 min read Decorator to print Function call details in Python Decorators in Python are the design pattern that allows the users to add new functionalities to an existing object without the need to modify its structure. Decorators are generally called before defining a function the user wants to decorate. Example: Python3 # defining a decorator def hello_decora 3 min read Python | Catching and Creating Exceptions Catching all exceptions is sometimes used as a crutch by programmers who canât remember all of the possible exceptions that might occur in complicated operations. As such, it is also a very good way to write undebuggable code. Because of this, if one catches all exceptions, it is absolutely critical 2 min read Closures And Decorators In Python Closures and decorators are powerful features in Python that allow for more advanced and flexible code patterns. Understanding these concepts can greatly enhance your ability to write clean, efficient, and reusable code.Why Python decorators rather than closures?Python decorators are preferred over 3 min read Python | Raising an Exception to Another Exception Let's consider a situation where we want to raise an exception in response to catching a different exception but want to include information about both exceptions in the traceback. To chain exceptions, use the raise from statement instead of a simple raise statement. This will give you information a 2 min read Python - Catch All Exceptions In this article, we will discuss how to catch all exceptions in Python using try, except statements with the help of proper examples. But before let's see different types of errors in Python. There are generally two types of errors in Python i.e. Syntax error and Exceptions. Let's see the difference 3 min read call() decorator in Python Python Decorators are important features of the language that allow a programmer to modify the behavior of a class. These features are added functionally to the existing code. This is a type of metaprogramming when the program is modified at compile time. The decorators can be used to inject modifie 3 min read How to log a Python exception? To log an exception in Python we can use a logging module and through that, we can log the error. The logging module provides a set of functions for simple logging and the following purposes DEBUGINFOWARNINGERRORCRITICALLog a Python Exception Examples Example 1:Logging an exception in Python with an 2 min read Like