Skip to content

Instantly share code, notes, and snippets.

@zonca
Last active December 22, 2021 16:36
Show Gist options
  • Save zonca/6782980 to your computer and use it in GitHub Desktop.
Save zonca/6782980 to your computer and use it in GitHub Desktop.
Example of catching exceptions, log them, and continue execution
import sys
import traceback
import logging
def setup_logging_to_file(filename):
logging.basicConfig( filename=filename,
filemode='w',
level=logging.DEBUG,
format= '%(asctime)s - %(levelname)s - %(message)s',
)
def extract_function_name():
"""Extracts failing function name from Traceback
by Alex Martelli
http://stackoverflow.com/questions/2380073/\
how-to-identify-what-function-call-raise-an-exception-in-python
"""
tb = sys.exc_info()[-1]
stk = traceback.extract_tb(tb, 1)
fname = stk[0][3]
return fname
def log_exception(e):
logging.error(
"Function {function_name} raised {exception_class} ({exception_docstring}): {exception_message}".format(
function_name = extract_function_name(), #this is optional
exception_class = e.__class__,
exception_docstring = e.__doc__,
exception_message = e.message))
import exceptions
import sys, os
from logging_utils import setup_logging_to_file, log_exception
from my_module import my_function_1, my_function_2
if __name__ == "__main__":
setup_logging_to_file("main.log")
try:
my_function_1()
except exceptions.Exception as e:
# we do not want to stop execution, just log and continue
log_exception(e)
try:
my_function_2()
except exceptions.Exception as e:
log_exception(e)
def my_function_1_wrapper():
my_function_1()
# in this case the log message is logging the wrapper as function name
try:
my_function_1_wrapper()
except exceptions.Exception as e:
log_exception(e)
import exceptions
class MyException(exceptions.Exception):
"""This is my own Exception"""
def my_function_1():
raise exceptions.IndexError("Some indexing error")
def my_function_2():
e = MyException("Something went quite wrong")
raise e
@zonca
Copy link
Author

zonca commented Oct 1, 2013

@TheBdouilleur
Copy link

TheBdouilleur commented Dec 2, 2019

Doesn't work.
I am getting the following error
Traceback (most recent call last): File "[path to my python file]", line 69, in <module> log_exception(e) File "[path to my parent directory]/logging_utils.py", line 29, in log_exception exception_message = e.message)) AttributeError: 'RequestError' object has no attribute 'message'

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