Below is the Python code which demonstrates how to print timestamped exception information to a text file, followed by the output text file debug.txt
. In order to append information to debug.txt
(and create the file if it doesn't already exist) instead of overwriting the text file every time, replace the line debug_file = open("debug.txt", "w")
with debug_file = open("debug.txt", "a")
.
import sys
from traceback import print_exception
from datetime import datetime
def do_something_bad():
raise ValueError("You just did something bad!!!")
debug_file = open("debug.txt", "w")
try:
do_something_bad()
except:
print("%s" % datetime.now(), file=debug_file)
print_exception(*sys.exc_info(), file=debug_file)
This produces the following file debug.txt
:
2020-10-29 14:33:24.413610
Traceback (most recent call last):
File "c:/Users/Jake/temp.py", line 10, in <module>
do_something_bad()
File "c:/Users/Jake/temp.py", line 6, in do_something_bad
raise ValueError("You just did something bad!!!")
ValueError: You just did something bad!!!
Instead of printing the full traceback, it is possible to just print the type and message of the exception (and also avoid importing extra modules) as follows:
def do_something_bad():
raise ValueError("You just did something bad!!!")
try:
do_something_bad()
except Exception as e:
print("Exception raised: %s: %s" % (type(e).__name__, e.args[0]))
Which produces the following output:
Exception raised: ValueError: You just did something bad!!!
This method works equally well for custom exceptions:
class CustomException(RuntimeError):
def __init__(self):
RuntimeError.__init__(self, "This is a custom exception")
try:
raise CustomException
except Exception as e:
print("Exception raised: %s: %s" % (type(e).__name__, e.args[0]))
Which produces the following output:
Exception raised: CustomException: This is a custom exception