如何在Python的日志记录模块中使用现代字符串格式设置选项? [英] How to use modern string formatting options with Python's logging module?

查看:96
本文介绍了如何在Python的日志记录模块中使用现代字符串格式设置选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python日志记录教程说,从不格式化方法超出了本教程的范围,没有提及从何处学习.

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

对于任何允许我在记录调用(例如debug()info()等)中使用.format()样式的消息格式的示例/文档,我将不胜感激.

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

推荐答案

最近,我也在寻找它.我想我已经指出了SO上的解决方案,但是我手头只有最终的URL.这就是我要做的:

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

可以这样使用:

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

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

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.

这篇关于如何在Python的日志记录模块中使用现代字符串格式设置选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆