Last active
July 31, 2023 13:57
-
-
Save aod7br/330e37f64dcd891f796dd2e11074b4ea to your computer and use it in GitHub Desktop.
combine debug, logging and exception handling in one @decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a simple decorator, but for better results, you should add log.debug and exception handling within your function