如何在Python的日志记录模块中使用现代字符串格式设置选项?

Ter*_*non 4 python logging

Python记录教程说,格式化的方式从未超出了本文的范围,就不能不提这里学习一下吧。

我将不胜感激任何例子/文档,让我用.format()风格的消息在日志调用,如格式化debug()info()等等。

Jon*_*fer 5

最近,我也在寻找那个。我想我已经指出了SO上的解决方案,但是我手头只有最终的URL。这是我的工作:

# 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
Run Code Online (Sandbox Code Playgroud)

可以这样使用:

logger.debug(_F("foo {0} {quux}", bar, quux=baz))
Run Code Online (Sandbox Code Playgroud)

格式化仅在评估邮件的那一刻进行,因此,如果禁用了日志级别,则不会损失很多性能。上面那个代码片段的作者将此软件包(以及其他一些实用程序)作为软件包提供了:logutils

  • 为什么不直接称其为“F”或“L”?当一个字符就足够时,不需要使用两个字符。前导下划线应该表示私有属性。 (2认同)