I want to be able to set python logging level to DEBUG
when I am debugging the application, without stopping it.
I wrote a signal handler which toggles the level. Is this a valid approach?
_debug_enabled = False
def _toggle_debug(signum, stack):
global _debug_enabled
if _debug_enabled:
logging.getLogger().setLevel(logging.INFO)
else:
logging.getLogger().setLevel(logging.DEBUG)
_debug_enabled = not _debug_enabled
signal.signal(signal.SIGUSR1, _toggle_debug)
I haven’t seen anyone using this approach. Is this a valid approach? Is there any pitfalls to this?
1
Using a signal handler is a perfectly valid solution! But as a general rule of thumb, please don’t use global variables as they give way too much room for error. I’d use an environment variable or something like that for this. For example:
from os import environ
import signal
def _toggle_debug(signum, stack):
_debug_enabled = environ['debug_enabled']
if _debug_enabled:
logging.getLogger().setLevel(logging.INFO)
else:
logging.getLogger().setLevel(logging.DEBUG)
environ['debug_enabled'] = not _debug_enabled
signal.signal(signal.SIGUSR1, _toggle_debug)
3