pythonlogging

python - Which is the better way to enable/disable logging?


Which is better way to enable/disable logging?

1) Changing log levels,

logging.disable(logging.CRITICAL)

2)

log = None

And logging messages this way,

if log:
    log.info("log message")

So that we can avoid unnecessary string constructions in case of logging disabled...


Solution

  • 1 is best, ideally via a configuration file or command line argument (--quiet)

    2 will just clutter up your code

    If you want to avoid expensive string construction (this is probably worthwhile about 0.001% of the time in my experience), use:

    if logger.isEnabledFor(logging.DEBUG):
        logger.debug("Message with %s, %s", expensive_func1(),
                                            expensive_func2())
    

    https://docs.python.org/3/howto/logging.html#optimization