Skip to content

Instantly share code, notes, and snippets.

@TJMac93
Last active June 18, 2024 12:08
Show Gist options
  • Save TJMac93/e062387393bcd54373efd9c613a4ed5f to your computer and use it in GitHub Desktop.
Save TJMac93/e062387393bcd54373efd9c613a4ed5f to your computer and use it in GitHub Desktop.
Decorator function to add logging to other functions.
# Logger gist available here:
# https://gist.github.com/TJMac93/cc17e0aa4546723cfba0d7165dbd9651
from logger import logger
from functools import wraps
def main():
def log_dec(func):
@wraps(func)
def wrapper(*args, **kwargs):
logger.debug(f"Running function: {func.__name__} with arguments: {args}")
try:
result = func(*args, **kwargs)
except Exception as e:
logger.error(
f"Failed to run function: {func.__name__}. Exception: {str(e)}"
)
else:
logger.debug(f"Successfully ran function: {func.__name__}")
return result
return wrapper
@log_dec
def add(x, y):
return x + y
add(2, 3)
add(4, 5)
add(2, "a")
print(add.__name__)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment