设置日志记录的格式样式 - 新样式、旧样式、百分比、括号或 f 字符串)[关闭]

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

Python 有多种参数字符串格式样式。

旧式/百分比/

%
"The first number is %s" % (1,)

新款/支架/

{
"The first number is {}".format(1)

F弦:

one = 1; f"the first number is {one}"

如何配置日志记录模块/格式化程序/处理程序以使用我想要的样式?

python string logging format string-formatting
1个回答
1
投票

这里有一个新样式格式的例子:

import logging

class NewstyleRecord(logging.LogRecord):
    def getMessage(self):
        msg = str(self.msg)
        if self.args:
            msg = msg.format(*self.args)
        return msg

logging.setLogRecordFactory(NewstyleRecord)
logging.basicConfig()
logging.error("The first number is {}", 1) # new-style 

这至少需要 python 3.2.


不要被

Formatter
style论点误导。它仅用于格式化格式字符串本身,对个别消息不起作用:

formatter = logging.Formatter(style='{', fmt="{levelname}:{name}:{message}")

有用的参考资料:

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