Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.