How to prevent logging warning?

Trent Mick trentm at ActiveState.com
Wed Oct 5 13:05:27 EDT 2005


[Thomas Heller wrote]
> I'm about to add some logging calls to a library I have.  How can I
> prevent that the script that uses the library prints
> 'No handlers could be found for logger "comtypes.client"' when the
> script runs?
> 
> I would like to setup the logging so that there is no logging when
> nothing is configured, and no warning messages are printed.

This is probably a gross hack, but then I think one could argue that the
one-time "No handlers could be found for" warning is a misfeature -- at
least without a clean way to suppress it. I don't know the history of
that warning though:


    -------------- mylib.py -----------------------
    import logging
    log = logging.getLogger("mylib")
    def func():
        log.warn("don't go near the river")
        log.error("I'm drowning!")
    --------------------------------------------------


    -------------- myscript.py -----------------------
    import sys
    import logging
    import mylib

    if __name__ == "__main__":
        if "-v" in sys.argv:
            logging.basicConfig()
        else:
            logging.Logger.manager.emittedNoHandlerWarning = True
        mylib.func()
    --------------------------------------------------


    $ python myscript.py

    $ python myscript.py -v
    WARNING:mylib:don't go near the river
    ERROR:mylib:I'm drowning!


hackily yours,
Trent

-- 
Trent Mick
TrentM at ActiveState.com



More information about the Python-list mailing list