How to enable logging at the initialization of the module in Python?
Question: I am having the following code:

    
    
    #! /usr/bin/python
    import logging
    import test_log
    
    def main():
        logging.error("hello")
    
    if __name__ == '__main__':
        logging.basicConfig()
    
        main()
    

where the `test_log` is defined as:

    
    
    import logging
    
    _logger = logging.getLogger(__name__)
    _logger.warn('initializing ' + __name__)
    

Executing the main script will led to output:

    
    
    No handlers could be found for logger "test_log"
    ERROR:root:hello
    

I believe it is because the `import test_log` statement will execute the
`_logger = logging.getLogger(__name__); _logger.warn('initializing ' +
__name__)`, while at this time `logging.basicConfig` is not executed. Is there
a way of solving this?


Answer: If you can't avoid logging at import time, add a
[`NullHandler`](http://docs.python.org/2/library/logging.handlers.html#nullhandler)
instance to the logger in `test_log`. That will prevent the "No handlers ..."
message.

Also, you have two calls to `basicConfig()`. Avoid this - have just one call
(in `if __name__ == '__main__'`).

