如何进行新型惰性格式化 python 日志记录[重复]

问题描述 投票:0回答:3

这涉及 pylint 和 python 日志记录。以下代码不起作用:

logging.basicConfig(level=logging.DEBUG, format='{message}', style='{')
log.debug('url {}', url)

它提出:

  File "/usr/lib/python3.9/logging/__init__.py", line 363, in getMessage
    msg = msg % self.args
TypeError: not all arguments converted during string formatting

如何使用 {} 样式而不是 %s 进行日志记录?

我在测试我的模块时使用了这个 basicConfig,但我的包中也可以有一个更高级的格式化程序。我开始探索这个的原因是因为当我使用 f-strings 时 pylint 会抱怨,但当我使用带有 (%s) 的旧格式时也是如此。

python logging pylint
3个回答
2
投票

logging
惰性格式仅包含
"%s"
占位符,然后在字符串后面并用逗号分隔,替换这些占位符的值。

在这种情况下:

logging.basicConfig(level=logging.DEBUG, format='%(message)s')
log.debug("url %s", url)

2
投票

您可以在

logging-format-style=new
中使用
pylintrc

pylint 2.2:

logging-format-style 是日志检查器的一个新选项,用于在调用记录器时使用 str.format() 样式格式字符串。

它接受两个选项:--logging-format-style=old 用于使用 % 样式格式,这是假定的默认值,--logging-format-style=new 用于使用 {} 样式格式。

还有fstring风格,看到这个很好的回答:https://stackoverflow.com/a/59027338/2519059


0
投票

您可以使用以下代码在 python 3.2+

 中使用
format

样式记录消息
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

有关详细信息、注意事项和参考资料,请参阅这个答案

© www.soinside.com 2019 - 2024. All rights reserved.