From the logging
howto for Python 2.7 (my emphasis):
A good convention to use when naming loggers is to use a module-level
logger, in each module which uses logging, named as follows:
logger = logging.getLogger(__name__)
This means that logger names track the package/module hierarchy, and it’s intuitively obvious where events are logged just from the logger name.
Sounds like good advice.
Now, the logging
cookbook provides an example for multiple modules, which uses hard-coded logger names instead of the __name__
constant. In the "main module" from the example we find
logger = logging.getLogger('spam_application')
and in the "auxiliary module" we find
module_logger = logging.getLogger('spam_application.auxiliary')
I copied this example verbatim into a package folder with the following structure:
cookbook-example
|- __init__.py
|- main_module.py
|- auxiliary_module.py
This runs without issue, producing the expected logging output from both the main module and the auxiliary module, but here's the thing:
If I now replace the hard-coded logger names by the __name__
constant, as recommended by the logging
howto, the cookbook example breaks down: I only get logging messages from the main module, but nothing from the auxiliary module.
I must be missing something obvious. Any ideas what I am doing wrong?
Note:
There are a lot of very similar questions and related answers, e.g.: 1, 2, 3, 4, 5, 6, and many more.
However, none of those appear to address this specific question.
--Edit--
Here's a minimal example based on the cookbook example, with the explicit name strings replaced by __name__
.
main_module.py
import logging
import auxiliary_module
# create and configure main logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# create console handler with a higher log level
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
# create formatter and add it to the handler
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
# add the handler to the logger
logger.addHandler(handler)
logger.info('message from main module')
auxiliary_module.some_function()
auxiliary_module.py
import logging
# create logger
module_logger = logging.getLogger(__name__)
def some_function():
module_logger.info('message from auxiliary module')
See Question&Answers more detail:
os