[Python-Dev] Problems with regrtest and with logging

Vinay Sajip vinay_sajip at yahoo.co.uk
Mon May 9 19:40:03 CEST 2011

Éric Araujo <merwok <at> netwok.org> writes:

>  Yep, probably dead code.  I think that an handler should be defined 
>  only once, in the “if __name__ == '__main__'” block.  Am I right?  Just 
>  like you don’t call sys.exit from library code (hello optparse!), you 
>  don’t set logging handlers in library code, only in the outmost layer of 
>  the script.

That's right, though it's OK to provide a documented convenience API for adding
>  The problem is that Dispatcher or Distribution get the quiet or verbose 
>  options from the command-line deep in the library code, and want to use 
>  it to configure the log level on the handler, which I’ve just said 
>  should be set up at a much higher level.  To solve this, I’m going to 
>  add a *logginghandler* argument to Dispatcher/Distribution; that way, 
>  the creation of the handler will happen only once and at a high level, 
>  but the command-line parsing code will be able to set the log handler 
>  from the command-line arguments. :)

You don't necessarily need to set the level on the handler - why can you not
just set it on the logger? The effect would often be the same: the logger's
level is checked first, and then the handler's level. Generally you set levels
on handlers when you want specific behaviour, such as all ERROR and above to a
particular file, all CRITICAL to an email handler etc.

For command-line scripts outputting to the console and nowhere else, usually you
could just add a StreamHandler (with no level set on it), and set the level on
the logger. Where the functionality may be used in an API, you should perhaps
check logger.hasHandlers() and avoid adding handlers if there are already some
added by a using library or application.


Vinay Sajip

More information about the Python-Dev mailing list