I want to add some helpful logging to a Python codebase.
I'm looking to add logging roughly of the form:
[2022-01-06 10:00:01] function foo called with args x=1, y=22, z=3
[2022-01-06 10:00:05] function foo returned 1416
[2022-01-06 10:00:13] function bar called with args w=1416
[2022-01-06 10:00:16] function bar returned None
I could do this by wrapping all functions in the codebase with a decorator, but is there a better way? At least to indicate the timestamp and order in which functions are being called.
I could implement the decorator:
def logthis(func):
def inner(*args, **kwargs):
logger.info(f'Calling {func.__name__} with args={args} and kwargs={kwargs}')
ans = func(*args, **kwargs)
logger.info(f'Function {func.__name__} returned {ans}')
return ans
return inner
@logthis
def foo(x, y, z):
return x+y+z
@logthis
def bar(w):
return None
This works reasonably well; provided I'm happy to add it across my whole codebase.