Skip to content

Instantly share code, notes, and snippets.

@aod7br
Last active July 31, 2023 13:57
Show Gist options
  • Save aod7br/330e37f64dcd891f796dd2e11074b4ea to your computer and use it in GitHub Desktop.
Save aod7br/330e37f64dcd891f796dd2e11074b4ea to your computer and use it in GitHub Desktop.
combine debug, logging and exception handling in one @decorator
import logging
logging.basicConfig(level=logging.DEBUG)
def debug(func):
'''
@debug
def f(a,b,c=0):
raise Exception("Crashing")
return a+b+c
f(1,2,c=3)
Output:
DEBUG:root:f called with args(1, 2) kwargs{'c': 3}
DEBUG:root:f **EXCEPTION** Crashing
DEBUG:root:f returned [None]
'''
log = logging.getLogger()
def wrapper(*args, **kwargs):
log.debug(f"{func.__qualname__} called with args{args} kwargs{kwargs}")
result = None
try:
result = func(*args, **kwargs)
except Exception as e:
log.debug(f"{func.__qualname__} **EXCEPTION** {e}")
finally:
log.debug(f"{func.__qualname__} returned [{result}]")
return result
return wrapper
@aod7br
Copy link
Author

aod7br commented Jul 17, 2023

This is a simple decorator, but for better results, you should add log.debug and exception handling within your function

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