According to Dynamically changing log level without restarting the application I can temporarily change logging level:
logger_level = my_logger.level
my_logger.setLevel(logging.DEBUG)
a = do_something_with_higher_logging1()
b,c = do_something_with_higher_logging2()
d = do_something_with_higher_logging3()
my_logger.setLevel(logger_level)
The problem is that if do_something_with_higher_logging[123] raise an exception (which is caught outside this, so my program is not terminated), the level of my_logger is not reset back and stays at DEBUG.
I can do
def call_with_loglevel(logger, level, f, **kwargs):
"Call f with logger at a different level"
saved_logger_level = logger.level
logger.setLevel(level)
try:
return f(**kwargs)
finally:
logger.setLevel(saved_logger_level)
but this requires me to define f out of the do_something_with_higher_logging[123]...
What I want is something like
with my_logger.setLevel(logging.DEBUG):
a = do_something_with_higher_logging1()
b,c = do_something_with_higher_logging2()
d = do_something_with_higher_logging3()
Making
Logger.setLevelreturn a context manager seems like a backwards-compatible change (should I create an RFE?) but for now it looks like I can do