I am trying to setup generic logging in my Python library modules so that they use the logger configured in the calling module without having to hard code a logger name. I've seen plenty of examples using logging.basicConfig() in the calling module and calling logging.debug() in the library module, but it doesn't work when I configure my own StreamHandler. What am I doing wrong?
This is my calling module:
import logging, logging.handlers
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
consolehandler = logging.StreamHandler()
consoleformatter = logging.Formatter('[%(name)s] %(levelname)s %(message)s')
consolehandler.setFormatter(consoleformatter)
logger.addHandler(consolehandler)
import libmodule
def run():
logger.info("message from calling module")
libmodule.say("message from library module")
I've tried this in libmodule.py:
import logging
def say(msg):
logging.info(msg)
and this:
import logging
logger = logging.getLogger()
def say(msg):
logger.info(msg)
But in both cases when I call run(), I get this output:
[callingmodule] INFO message from calling module
but was expecting this:
[callingmodule] INFO message from calling module
[callingmodule] INFO message from library module