How to Use Decorators to Print Log in Python
- creat a decorator:
def logDecorator(func):
def wrapper(*args, **kwargs):
print(f"Call function {func.__name__} with args {args} and kwargs {kwargs}")
result = func(*args, **kwargs)
print(f"Function {func.__name__} returned {result}")
return result
return wrapper
- use this decorator
@logDecorator
def add(x, y):
return x + y
full code:
def logDecorator(func):
def wrapper(*args, **kwargs):
print(f"Call function {func.__name__} with args {args} and kwargs {kwargs}")
result = func(*args, **kwargs)
print(f"Function {func.__name__} returned {result}")
return result
return wrapper
@logDecorator
def add(x, y):
return x + y
console print log:
Call function add with args (3, 5) and kwargs {}
Function add returned 8
8