[Python-Dev] New-style formatting in the logging module (was Re: cpython (3.2): Issue #14123: Explicitly mention that old style % string formatting has caveats)
Vinay Sajip
vinay_sajip at yahoo.co.uk
Mon Feb 27 10:24:46 CET 2012
Nick Coghlan <ncoghlan <at> gmail.com> writes:
> It's half the puzzle (since composing the event fields into the actual
> log output is a logger action, you know the style when you supply the
> format string). The other half is that logging's lazy formatting
> currently only supporting printf-style format strings - to use brace
> formatting you currently have to preformat the messages, so you incur
> the formatting cost even if the message gets filtered out by the
> logging configuration.
That isn't necessarily true. Lazy formatting can work for {} and $ formatting
types, not just %-formatting: see
http://plumberjack.blogspot.com/2010/10/supporting-alternative-formatting.html
Composing the event fields into the message is done by the LogRecord, which
calls str() on the object passed as the format string to get the actual format
string. This allows you to use any of the standard formatting schemes and still
take advantage of lazy formatting, as outlined in the above post.
Although style support for Formatters is new, that's really for merging the
logging event message into the overall log output (with time, severity etc.) -
the support for having your own way of formatting the event message has always
been there, even before str.format :-)
The Formatter style functionality is also available for 2.x through a separate
logutils project which I maintain and which contains features which were added
to logging in 3.2 such as QueueHandler/QueueListener:
http://pypi.python.org/pypi/logutils/
I will add a section in the logging cookbook about support for alternative
formatting styles. I thought I already had, but on inspection, it appears not to
be the case.
Regards,
Vinay Sajip
More information about the Python-Dev
mailing list