Skip to content

Instantly share code, notes, and snippets.

@magickatt
Last active October 30, 2019 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magickatt/a07d7f182ba2f63842cca15bfa8fb629 to your computer and use it in GitHub Desktop.
Save magickatt/a07d7f182ba2f63842cca15bfa8fb629 to your computer and use it in GitHub Desktop.
Get class, filename and line number from Python Exception
import os, sys, logging
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
try:
number = 1 / 0
except ZeroDivisionError as exception:
exception_message = str(exception)
exception_type, exception_object, exception_traceback = sys.exc_info()
filename = os.path.split(exception_traceback.tb_frame.f_code.co_filename)[1]
log = logging.getLogger("logger")
log.info(f"{exception_message} {exception_type} {filename}, Line {exception_traceback.tb_lineno}")
# INFO:logger:division by zero <class 'ZeroDivisionError'> test_e.py, Line 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment