Let's consider, for debugging purposes, we would like to log the result of costly_metric():
logger.info("some function")
logger.debug(f"result of costly metric: {costly_metric()}"
We only ever need this result for debugging and due to the computing resource costs involved in calculating costly_metric() it should not be executed if we set log level > debug.
However, logging, of course will execute the statement and then just hide the result. Minimal example:
l = logging.getLogger("logger")
l.setLevel(logging.INFO)
def foo():
l.debug(f"costly metric: {costly_metric()}")
l.info("test")
def costly_metric():
l.warning("costly metric executed")
return 42
If we call foo() now, this will result in:
> WARNING:logger:costly metric executed
> INFO:logger:test
Thus, costly metric: 42 is just hidden in the logger's output but the method costly_metric() still is getting executed.
In order to prevent this behavior, we could check for the level with an if statement:
def foo():
if l.level <= logging.DEBUG:
l.debug(f"costly metric: {costly_metric()}")
l.info("test")
What would be the most pythonic way to resolve this issue?