Mario Stefanutti
Mario Stefanutti

Reputation: 262

Skip debug instructions (and their content) if logging is set to INFO

I have a program in which I wrote logs both as info and debug.

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

Is it possible to completely skip those line from computation?

in the next example 10 seconds have to pass before the info log is executed.

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")

Upvotes: 2

Views: 850

Answers (2)

saq7
saq7

Reputation: 1808

You shouldn't have logging inside debug commands. If you must, then in order to skip it you must branch your 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)

if logger.isEnabledFor(logging.DEBUG):
    logger.debug("aaa", time.sleep(10))
    logger.debug("bbb")
logger.info("ccc")

Upvotes: 1

Mureinik
Mureinik

Reputation: 311903

You could check if the logger is enabled for such a level with the isEnabledFor method:

if logger.isEnabledFor(logging.DEBUG):
    logger.debug("aaa", time.sleep(10))
    logger.debug("bbb")

Upvotes: 3

Related Questions