Quantcast
Viewing all articles
Browse latest Browse all 14040

Inconsistent behaviour with Python loggings when creating a package (__init__.py and from . import module)

Here is a MRE:

my_package/__init__.py

import loggingfrom . import module, a_second_modulelogging.basicConfig(level=logging.INFO)

my_package/module.py

import loggingdef module():    logging.info("Doing something...")    logging.debug("This is a debug message and won't show up by default.")

my_package/a_second_module.py

import loggingfrom my_package_test_so_poetry.module import modulelogging.warning("Warning from a_second_module.py")def module2():    module()    print("Doing something else...")

The logging.basicConfig does not affect the logging behaviour of the second file (module.py).Since when I do (in the terminal)

python (to enter the Python console)from my_package.module import modulemodule()

I get

WARNING:root:Warning from a_second_module.py

But I'm lacking the

INFO:root:Doing something...

of the function module

I think the problem comes from the warning since the documentation says:

Log a message with severity 'WARNING' on the root logger. If thelogger has no handlers, call basicConfig() to add a console handlerwith a pre-defined format.

But I'm not sure I understand why, my logging.basicConfig(level=logging.INFO) (in the __init__.py file) should be called after the warning message and before I call module. I'm 99% sure the culprit is the warning message though because everything works as expected without it.

I'm using PyCharm 2023.3.3 (Professional Edition) (and I assume other IDEs would have the same behaviour) and Python 3.11.1.


Viewing all articles
Browse latest Browse all 14040

Trending Articles