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

后端 未结 1 1451
渐次进展
渐次进展 2021-01-04 11:46

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 apprecia

1条回答
  •  走了就别回头了
    2021-01-04 12:28

    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.

    0 讨论(0)
提交回复
热议问题