Python Cross Module Registration

I googled and looked at the default documentation, but I cannot understand why this does not create three lines of logging:

# main.py import logging import apple import banana log = logging.getLogger('main') log.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) log.addHandler(ch) log.info("I'm in main!") 
 # apple.py import logging log = logging.getLogger('main.apple') log.info("I'm here in apple!") 
 # banana.py import logging log = logging.getLogger('main.banana') log.info("I'm here in banana!") 
 # output 2011-09-03 16:40:54,062 - main - INFO - I'm in main! 

But the example in the logging documentation works fine.

Any ideas?

+6
source share
1 answer

The handler ( StreamHandler ) was not configured before import. Thus, the registration commands in the imported modules do not produce any output. Some processors print files, others over the network, and some on the console. It is not possible for the log instructions inside the imported modules to know what to do without adding handler (s) to the logger.

If the logging operators in the modules are inside the class or function, as in the example to which you are attached, the output can be seen, because by the time the class of the module or function appeared, the handler was added to the registrar.

+9
source

Source: https://habr.com/ru/post/896555/


All Articles