Sean
Sean

Reputation: 3385

Overriding a third-party module's logger?

I'm not sure how to explain the issue, but I think that a third-party module that I'm using is preventing me from using a logger the "normal" way.

I'm currently using a third-party module called Stanza. Whenever I load the module and the resources I believe a logger is initialized.

When I try to set up my own logger, it doesn't seem to work. Here's my code:

import logging 

import stanza


logger = logging.getLogger()


def main():
    stanza.download('en', package='craft')
    stanza_pipeline = stanza.Pipeline('en', package='craft')

    logging_msg_fmt = '[%(asctime)s - %(levelname)s - %(filename)s: %(lineno)d (%(funcName)s)] %(message)s'
    logging.basicConfig(format=logging_msg_fmt, level=logging.INFO, handlers=[logging.FileHandler(), \
        logging.StreamHandler()])

    logger.info("Logging message.")

This code outputs what I assume to be Stanza's own logger output and my own logger statements don't work. In fact, when I do print(logger) I get <RootLogger root (WARNING)>.

Is there any way that I can go around this?

Upvotes: 1

Views: 740

Answers (2)

Jbtf
Jbtf

Reputation: 121

I encountered a same issue, I had already declared in my main.py the basic configurations for logging:

logging.basicConfig(handlers=[logging.FileHandler("log.log", 'a+', 'utf-8'),logging.StreamHandler(sys.stdout)],
                        format="%(asctime)s-%(name)s-%(filename)s->%(funcName)s()->%(lineno)d: [%(levelname)s] - %(message)s",
                        level=logging.DEBUG, datefmt="%d-%b-%y %H:%M:%S")

and then when I imported a specific module X in my other python file, that specific module was setting the level logging to Error so only Error logs were being shown in my logs.

I discovered that basicConfig method has a parameter named force which overwrites the handlers already configured in the root logger if its value is True.

Using this it worked for me:

logging.basicConfig(handlers=[logging.FileHandler("log.log", 'a+', 'utf-8'),logging.StreamHandler(sys.stdout)],
                        format="%(asctime)s-%(name)s-%(filename)s->%(funcName)s()->%(lineno)d: [%(levelname)s] - %(message)s",
                        level=logging.DEBUG, datefmt="%d-%b-%y %H:%M:%S", force=True)

Upvotes: 1

Dan D.
Dan D.

Reputation: 74645

Move your basicConfig call to before stanza is imported.

Where stanza messes up

Upvotes: 2

Related Questions