5

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...

1
  • 2
    Have you tried benchmarking your two options? Commented Jun 19, 2010 at 10:44

1 Answer 1

15

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

Sign up to request clarification or add additional context in comments.

1 Comment

This assumes you have the current or root logger in logger. If you just use logging.debug(...) you need to check as follows: if logging.getLogger().isEnabledFor(logging.DEBUG): ....

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.