I have a function foo that logs some information during execution:
import logging
logging.basicConfig()
def foo(x):
for i in range(10):
logging.info(f"This is iteration number {i}.")
x += i
return x
Is it possible to create a decorator log_or_not so that I can call my decorated function foo with an added argument like this:
foo(x=x, level=logging.INFO)
For now all I have is this, a decorator that sets the logging level to INFO, executes the function then returns the logging level to the original level:
def log_or_not(func):
def wrap_function(*args, **kwargs):
original_level = logging.root.level
print(original_level)
logging.getLogger().setLevel(logging.INFO)
y = func(*args, **kwargs)
logging.getLogger().setLevel(original_level)
return y
return wrap_function
@log_or_not
def foo(x):
for i in range(10):
logging.info(f"This is iteration number {i}.")
x += i
return x