Skip to content

Instantly share code, notes, and snippets.

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"))
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")"{exception_message} {exception_type} {filename}, Line {exception_traceback.tb_lineno}")
# INFO:logger:division by zero <class 'ZeroDivisionError'>, Line 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment