Consider this snippet of code, which I'm running under Python 2.7.6:
import logging, sys
assert (__name__ not in logging.Logger.manager.loggerDict)
logger = logging.getLogger(__name__)
stdout_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(stdout_handler)
logger.error("You'll see this once")
logging.debug("Imagine logging now happens in some other module, maybe via an import")
logger.error("You'll see this twice")
logger.propagate = False
logger.error("BUT this you'll only see once")
It gives this output:
You'll see this once
You'll see this twice
ERROR:__main__:You'll see this twice
BUT this you'll only see once
The problem seems to be that logging.debug calls logging.basicConfig:
The above module-level convenience functions, which delegate to the root logger, call basicConfig() to ensure that at least one handler is available (source).
I'd like to simply take away from this the rule "Do not use the module-level convenience functions" but the scary thing is that any module that uses these functions (or calls logging.basicConfig) will break the rest of my logging. So instead the lesson could be "always use propagate=False for loggers whose parent is the root logger," but that doesn't feel right--propagate must default to True for a reason. Is there a better way?