logging - how to use in a library?

Vinay Sajip vinay_sajip at yahoo.co.uk
Wed Aug 27 05:15:00 EDT 2008


On Aug 26, 8:05 pm, Thomas Heller <thel... at python.net> wrote:
> I'm using theloggingmodule in my comtypes library to log
> 'interesting' things that happen.  In other words, the idea
> is if the user of the library is interested in the details that
> happen in the package internally, he (she?) would configure
> alogginglevel and handlers that write the log messages where it
> is convenient.
>
> This works great, with one exception:
> If the script using the library does NOT configurelogging, and somewhere the library calls
> logger.error(...) or logger.critical(...) then he gets a message on stderr saying:
>
>   No handlers could be found for logger "foo"
>
> Of course this can be avoided by configuring a NULL-Handler, or raising the
> loglevel to a very high value - but why is this necessary?
> I would assume that if no handlers are configured than simply thelogging
> package should not output anything...
>
> Why doeslogginginsist on a default level of ERROR even if unconfigured, and
> why does it insist to output something even if no handler is defined?
>
> I assume it would not be a good idea to configureloggingin the library itself,
> possibly overwriting explicit configuration that the user has done...  I don't get it.
>
> Thomas

Suppose a user of logging configures it wrongly by mistake, so that
there are no handlers configured. In this case, if the logging system
were not to output anything at all, then you would have no information
at all about why - leading to a longer time to diagnose the problem.
That's the only reason why the message is there, and it's output when
there are no handlers found for an event, and logging.raiseExceptions
is 1/True (=> a non-production environment), and
Logger.manager.emittedNoHandlerWarning is 0/False (to avoid printing
the message multiple times). As Ben Finney has said, an application's
logging requirements are the determining factor; and I agree that it's
not a good idea to do logging configuration in the library, which
could conflict with what an application developer expects. So
documenting your logging assumpstions is a good approach.

The default level for logging is WARNING, not ERROR - this was judged
to be a good default level, since under most circumstances we're
particularly interested in warnings and errors. (A level of WARNING
catches ERROR and CRITICAL events, too, of course.)

Best Regards,


Vinay Sajip



More information about the Python-list mailing list