[Python-Dev] Change to logging Formatters: support for alternative format styles

Vinay Sajip vinay_sajip at yahoo.co.uk
Mon Oct 25 16:28:49 CEST 2010


I've just checked in a change to logging into the py3k branch (r85835),
including doc changes and tests, for providing slightly more flexibility in
alternative format styles for logging.

Basically, Formatter.__init__ gets an extra optional keyword arg style=<one of
'%' (default), '{' or '$'>. This is then used to merge the format string with
the LogRecord: either fmt % record.__dict__, or fmt.format(**record.dict), or
string.Template(fmt).substitute(**record.dict). Backward compatibility is
maintained (unless I've missed something).

This does not cater for how you combine the logging message + its args when you
make a logging call, but should work with any existing library which uses
%-formatting in its logging calls.

We discussed this here around a year ago in the context of generally encouraging
a move from %-formatting to {}-formatting, but there seemed to be no obvious
easy path forward.

As of now, and even without this change I've just checked in, developers can use
{}- or $-formatting in their logging messages using e.g.

logger.debug(__('Message with {} {}', 2, 'place-holders'))

with a suitable class standing in for __. A bit ugly, I know, with extra
parentheses and what not, but hopefully for those who must have {} now it
shouldn't be too much of a price to pay and there's no major performance
implication, as actual rendering to string is done as late as possible, just as
it is now.

Comments welcome. Assuming there are no strong objections asking for reversion
of this change, I'll publicise to the wider community in a few days.

Regards,


Vinay Sajip



More information about the Python-Dev mailing list