Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to log a Python exception?

  • Last Updated : 29 Sep, 2021

To log an exception in Python we can use logging module and through that we can log the error.

Logging module provides a set of functions for simple logging and for following purposes

 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. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

  • DEBUG
  • INFO
  • WARNING
  • ERROR
  • CRITICAL

Logging an exception in python with an error can be done in the logging.exception() method. This function logs a message with level ERROR on this logger. The arguments are interpreted as for debug(). Exception info is added to the logging message. This method should only be called from an exception handler.



See the following code for more clarity:

Example 1 :

Python3




# importing the module
import logging
 
try:
    printf("GeeksforGeeks")
except Exception as Argument:
    logging.exception("Error occurred while printing GeeksforGeeks")

Output :

ERROR:root:Error occurred while printing GeeksforGeeks
Traceback (most recent call last):
  File "/home/gfg.py", line 3, in 
    printf("GeeksforGeeks")
NameError: name 'printf' is not defined

Example 2: We can also log the error message into a different file without showing error in the console by the following method:

Python3




# importing the module
import logging
 
try:
    printf("GeeksforGeeks")
except Exception as Argument:
 
     # creating/opening a file
     f = open("demofile2.txt", "a")
 
     # writing in the file
     f.write(str(Argument))
      
     # closing the file
     f.close()

Error message will be stored in file name demofille2.txt in same directory as code.

Output :

Traceback (most recent call last):
  File "/home/gfg.py", line 5, in 
    printf("GeeksforGeeks")
NameError: name 'printf' is not defined



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!