« Back to Index

[Python Generic Exception Logging]

View original Gist on GitHub

Tags: #python #exceptions #error #logging

Python Generic Exception Logging.py

def get_function_name():
    """
    0: get_function_name()
    1: log_exception()
    2: whatever called log_exception()
    """
    return inspect.stack()[2].function

  
def log_exception(exc, msg='exception caught', **kwargs):
    logger.error(msg,
                 exc_class=type(exc),
                 exc_type=exc.__class__.__name__,
                 exc_msg=str(exc),
                 fn=get_function_name(),  # foo
                 **kwargs)

def foo():
  try:
    raise Exception()
  except Exception as exc:
    log_exception(exc, 'something happened')