Python logging: Set handlers for all loggers of used modules

logging, python

Solution

The reason you're getting no output is most likely that you haven't set a level on the logger, so it will default to `WARNING`. Try doing `logger.setLevel(logging.DEBUG)` and see if that causes output to be produced. I know you said that log levels are correct, but I can't see any other reason why no output would be produced. You can try posting a small self-contained script that demonstrates the problem, if you like.

`NullHandler` only needs to be added for library modules to cater for their use in an application that doesn't configure logging. It is not needed in modules of an application that configures logging.

In general, you can add a handler to the root logger and it will be used by loggers in all modules.

Update: The comment to Kobi K's answer indicates that a level has been set on the handler - this is not enough, as you need to set a level on the logger, whose level is checked first. Only if the event is allowed through by the logger's level will the handlers (and their levels) come into play.

Problem

I have my main script that interprets cli commands with argparse and then starts the application by calling the according stuff form an other module (made by myself). My question now is how I can attach a handler to the logger from that module. The logger is retrieved with ``` logger = logging.getLogger(__name__) ``` I hence put following in my main script: ``` consoleHandler = logging.StreamHandler() logger = logging.getLogger('MyModule') logger.addHandler(consoleHandler) ``` However there is 0 logging output from 'MyModule'. Log levels are correct, eg there should be an output. In `MyModule` I have the following: ``` logging.getLogger(__name__).addHandler(logging.NullHandler()) ``` However removing that makes no difference. So how can I correctly attach a handler to the logger of `MyModule`?

Original source