Skip debug instructions (and their content) if logging is set to INFO
<p>I have a program in which I wrote logs both as info and debug.</p>

<p>Since the debug contains also calls to slow functions, my program is running slow even if I set debugging to INFO.</p>

<p>Is it possible to completely skip those line from computation?</p>

<p>in the next example 10 seconds have to pass before the info log is executed.</p>

<pre><code>import logging.handlers
import sys
import time

logger = logging.getLogger()
logger.setLevel(logging.INFO)
logging_stream_handler = logging.StreamHandler(sys.stdout)
logging_stream_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s --- %(message)s'))
logger.addHandler(logging_stream_handler)

logger.debug("aaa", time.sleep(10))
logger.debug("bbb")
logger.info("ccc")
</code></pre>

<p>You could check if the logger is enabled for such a level with the <a href="https://docs.python.org/2/library/logging.html#logging.Logger.isEnabledFor" rel="nofollow"><code>isEnabledFor</code></a> method:</p>

<pre><code>if logger.isEnabledFor(logging.DEBUG):
    logger.debug("aaa", time.sleep(10))
    logger.debug("bbb")
</code></pre>

python logging