Leto Atreides
Leto Atreides

Reputation: 27

Define the same logger level for two python modules

EDIT: This work perfectly. The problem was in other part of the code.

Y have two modules: test.py and dscc.py, the first one has the following code:

# test.py
from logging import getLogger, basicConfig

logger = getLogger(__name__)

def main(level='INFO') -> None:
    basicConfig(level=level)
    
    logger.info('This is a test')


if __name__ == '__main__':
    main('WARNING')

And the other one call this with the following code:

# dscc.py
from my_package import test


def main() -> None:
    """ Main function. """
    test.main('WARNING')


if __name__ == '__main__':
    main()

That means, the second script calls the first one. The question is that the log level is defined correctly when I execute test.py directly but basicConfig() does nothing when I execute dscc. Does someone know how to solve the problem?

Thanks!

Upvotes: 0

Views: 27

Answers (1)

matszwecja
matszwecja

Reputation: 7985

The whole point of if __name__ == '__main__': is to run the this code only when the script is run as a top-level. If you want to run some piece even on import, then don't put in inside such clause. As it is right now, basicConfig never happens when you import test.py

Upvotes: 1

Related Questions