Last active
August 22, 2025 01:54
-
-
Save fleetingbytes/94b5e4c6ff9bfdfcbe7ace949d72d94a to your computer and use it in GitHub Desktop.
Python logging decorator
This file contains hidden or 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
| from functools import wraps | |
| from logging import getLogger, DEBUG | |
| logger = getLogger(__name__) | |
| def log_io(level: int=DEBUG, enter: bool=False, exit: bool=False): | |
| """ | |
| Decorator factory that logs function input arguments and return values | |
| at the specified logging level. | |
| Usage: | |
| debug = @log_io(logging.DEBUG, enter=True, exit=True) | |
| @debug | |
| def my_func(...): | |
| ... | |
| """ | |
| def decorator(func): | |
| @wraps(func) | |
| def wrapper(*args, **kwargs): | |
| if enter: | |
| logger.log(level, "Calling %s with args=%s, kwargs=%s", func.__name__, args, kwargs, stacklevel=2) | |
| result = func(*args, **kwargs) | |
| if exit: | |
| logger.log(level, "%s returned %r", func.__name__, result, stacklevel=2) | |
| return result | |
| return wrapper | |
| return decorator | |
| debug = log_io(DEBUG, enter=True, exit=True) | |
| debug_in = log_io(DEBUG, enter=True) | |
| debug_out = log_io(DEBUG, exit=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment