How to log a Python exception?
Last Updated :
12 Feb, 2024
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
- DEBUG
- INFO
- WARNING
- ERROR
- CRITICAL
Log a Python Exception Examples
Example 1:
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.
Python3
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
try :
printf( "GeeksforGeeks" )
except Exception as Argument:
f = open ( "demofile2.txt" , "a" )
f.write( str (Argument))
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...