Skip to content

Instantly share code, notes, and snippets.

@stringertheory
Created July 17, 2025 17:25
Show Gist options
  • Select an option

  • Save stringertheory/4b90fcd980d9b0e5c6cdc2f81b64e50b to your computer and use it in GitHub Desktop.

Select an option

Save stringertheory/4b90fcd980d9b0e5c6cdc2f81b64e50b to your computer and use it in GitHub Desktop.
A function to use to make sure that tracebacks are logged.
def excepthook(*exc_info):
"""Log the traceback if program throws an unhandled exception."""
exc_type, exc_value, exc_traceback = exc_info
exc_time = time.time()
msg = f"{exc_type.__name__} @ {exc_time}"
logging.critical(f"{msg}. Traceback ↓", exc_info=exc_info)
logging.critical(f"{msg}. Traceback ↑")
sys.excepthook = excepthook
@stringertheory
Copy link
Author

Creates output in logs like this:

2025-07-17 12:23:49,018 INFO yadda
2025-07-17 12:23:49,018 INFO yadda
2025-07-17 12:23:49,018 CRITICAL ValueError @ 1752773029.0184488. Traceback ↓
Traceback (most recent call last):
  File "/Users/stringertheory/Desktop/testing_excepthook.py", line 24, in <module>
    raise ValueError("nope")
ValueError: nope
2025-07-17 12:23:49,020 CRITICAL ValueError @ 1752773029.0184488. Traceback ↑

The timestamp is in the log message at the beginning and end of the traceback, so that it's easy to search for the beginning/end of the traceback when reading the logfile.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment