How to use modern string formatting options with Python's logging module?

Question:

The Python logging tutorial says that the newer ways of formatting are beyond the scope of the tutorial, without mentioning where to learn about it.

I would appreciate any examples or link to documentation that allow me to use .format() style message formatting in logging calls such as debug(), info(), etc.

Asked By: Terrence Brannon

||

Answers:

Recently, I was looking for that too. I think I got pointed to the solution here on SO, but I only have the final url at hand. This is what I do:

# http://plumberjack.blogspot.de/2010/10/supporting-alternative-formatting.html
class BraceMessage(object):
    def __init__(self, fmt, *args, **kwargs):
        self.fmt = fmt
        self.args = args
        self.kwargs = kwargs

    def __str__(self):
        return self.fmt.format(*self.args, **self.kwargs)

_F = BraceMessage

Can be used like this:

logger.debug(_F("foo {0} {quux}", bar, quux=baz))

The formatting will only take place in the very moment the message is evaluated, so you don’t lose lots of performance if a log level is disabled. The author of that snippet above made this (and some other utilities) available as a package: logutils.

Answered By: Jonas Schäfer

You can use the following code to enable using format style in python 3.2+

import logging

class BracketStyleRecord(logging.LogRecord):
    def getMessage(self):
        msg = str(self.msg) # see logging cookbook
        if self.args:
            try:
                msg = msg % self.args # retro-compability for 3rd party code
            except TypeError: # not all arguments converted during formatting
                msg = msg.format(*self.args)
        return msg

logging.setLogRecordFactory(BracketStyleRecord)
logging.basicConfig()
logging.error("The first number is %s", 1) # old-style
logging.error("The first number is {}", 1) # new-style

For details, caveats and references see this answer.

Answered By: loopbackbee
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.