Skip to content

Instantly share code, notes, and snippets.

@SimonLammer
Created March 23, 2022 11:11
Show Gist options
  • Save SimonLammer/4dca4c30c887f27cb5298315eacb5fc1 to your computer and use it in GitHub Desktop.
Save SimonLammer/4dca4c30c887f27cb5298315eacb5fc1 to your computer and use it in GitHub Desktop.
Python decorator to change loglevel within a function.
import logging
LOG = logging.getLogger(__name__)
logging.basicConfig(format="[%(levelname)8s] %(message)s (%(funcName)s@%(filename)s:%(lineno)s)")
LOG.setLevel(logging.DEBUG)
LOGLEVEL_FUNCS = {} # autoreload workaround https://github.com/ipython/ipython/issues/11099#issuecomment-382029692
def loglevel(level):
def outer(func):
LOG.debug(f"loglevel {level} for function {func.__qualname__}")
LOGLEVEL_FUNCS[func.__qualname__] = (level, func)
@wraps(func)
def inner(*args, **kwargs):
level, f = LOGLEVEL_FUNCS[func.__qualname__]
oldlevel = LOG.getEffectiveLevel()
#print(f">LOGLEVEL {level}")
LOG.setLevel(level)
try:
res = f(*args, **kwargs)
if isinstance(res, Iterator):
return loglevel_iterator(level, res)
else:
return res
finally:
LOG.setLevel(oldlevel)
#print(f"<LOGLEVEL {oldlevel}")
return inner
return outer
def loglevel_iterator(level, iterator):
try:
oldlevel = LOG.getEffectiveLevel()
LOG.setLevel(level)
for i in iterator:
LOG.setLevel(oldlevel)
yield i
oldlevel = LOG.getEffectiveLevel()
LOG.setLevel(level)
finally:
LOG.setLevel(oldlevel)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment