Author underrun
Recipients underrun
Date 2013-08-08.20:15:37
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1375992937.35.0.58426954587.issue18689@psf.upfronthosting.co.za>
In-reply-to
Content
It is common when setting up a logger to create both a handler and a formatter. Nice format strings make logging better. Like this:

>>> fmt_string = "%(asctime)s [%(levelname)-9s] %(name)s: %(message)s"

We would use it like so: 

>>> from logging import getLogger, StreamHandler, Formatter
>>> logger = getLogger('mypackage.mymodule')
>>> handler = StreamHandler()
>>> formatter = Formatter(fmt_string)
>>> handler.setFormatter(formatter)
>>> logger.addHandler(handler)
>>> logger.warning('she called out a warning...')

But its nice to separate adding handlers from using loggers. so in mymodule I might do:

>>> logger = getLogger('mypackage.mymodule')
>>> logger.warning('do not pass go...')

and in whatever entry point cares about logging from mypackage (like a cli or another module importing my package that wants log data) I would do:

>>> base_logger = getLogger('mypackage')
>>> handler = StreamHandler()
>>> formatter = Formatter(fmt_string)
>>> handler.setFormatter(formatter)
>>> base_logger.addHandler(handler)

but usually, at this point, i don't care about this base_logger at all and i've got a bunch of refs to things i don't need anymore - the only purpose of all this code is to handle any logging that may be done elsewhere in the package.

If handlers allowed passing in a formatter into __init__, then we could reduce the above to something like this:

>>> getLogger('mypackage').addHandler(StreamHandler(
        fmt=Formatter(fmt_string)))

Using a kwarg would make it so we don't need to worry about existing argument order so that should be completely backward compatible.

It'd be extra friendly if Handler could introspect fmt and see if it is an instance str and if so create a Formatter in itself ... that way we could do:

>>> getLogger('mypackage').addHandler(StreamHandler(fmt=fmt_string))

This would reduce the barrier to entry to customizing logging functionality and might go a long way toward increasing effective use of the same.
History
Date User Action Args
2013-08-08 20:15:37underrunsetrecipients: + underrun
2013-08-08 20:15:37underrunsetmessageid: <1375992937.35.0.58426954587.issue18689@psf.upfronthosting.co.za>
2013-08-08 20:15:37underrunlinkissue18689 messages
2013-08-08 20:15:37underruncreate