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

时间:2012-11-21 19:38:42

标签: python logging

Python logging tutorial表示永远不会格式化的方法超出了本教程的范围,没有提到在哪里学习它。

我很感激任何允许我在.format()debug()等日志记录中使用info()样式邮件格式的示例/文档。

1 个答案:

答案 0 :(得分:4)

最近,我也在寻找。我想我已经在SO上找到了解决方案,但我手边还有最后的网址。这就是我的工作:

# 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

可以像这样使用:

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

格式化只会在评估消息的那一刻发生,因此如果禁用日志级别,则不会丢失大量性能。上述代码段的作者将此(以及其他一些实用程序)作为包提供:logutils

相关问题