Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jakelevi1996/ee45c8637f535ffa04e865f9bc982d30 to your computer and use it in GitHub Desktop.
Save jakelevi1996/ee45c8637f535ffa04e865f9bc982d30 to your computer and use it in GitHub Desktop.
Print timestamped exception information to a text file in Python

Print timestamped exception information to a text file in Python

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!!!

Lightweight alternative

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment