Python 有多种参数字符串格式样式。
旧式/百分比/
%
:
"The first number is %s" % (1,)
新款/支架/
{
:
"The first number is {}".format(1)
F弦:
one = 1; f"the first number is {one}"
如何配置日志记录模块/格式化程序/处理程序以使用我想要的样式?
这里有一个新样式格式的例子:
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}")
有用的参考资料: