Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Errors and Exceptions in Python
Next article icon

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.




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



Next Article
Errors and Exceptions in Python

K

krishna krish
Improve
Article Tags :
  • Python
  • Python Decorators
Practice Tags :
  • python

Similar Reads

  • Errors and Exceptions in Python
    Errors are problems in a program that causes the program to stop its execution. On the other hand, exceptions are raised when some internal events change the program's normal flow. Syntax Errors in PythonSyntax error occurs when the code doesn't follow Python's rules, like using incorrect grammar in
    3 min read
  • 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
  • Handling EOFError Exception in Python
    In Python, an EOFError is raised when one of the built-in functions, such as input() or raw_input() reaches the end-of-file (EOF) condition without reading any data. This commonly occurs in online IDEs or when reading from a file where there is no more data left to read. Example: [GFGTABS] Python n
    4 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: # defining a decorator def hello_decorator(func
    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences