[New-bugs-announce] [issue18689] add argument for formatter to logging.Handler and subclasses in logging module

Derek Wilson report at bugs.python.org
Thu Aug 8 22:15:37 CEST 2013


New submission from Derek Wilson:

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.

----------
components: Library (Lib)
messages: 194706
nosy: underrun
priority: normal
severity: normal
status: open
title: add argument for formatter to logging.Handler and subclasses in logging module
type: enhancement
versions: Python 3.4

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue18689>
_______________________________________


More information about the New-bugs-announce mailing list