我正在使用Python 3.8.10。我正在尝试使用格式化程序下documentation的日志记录样式“{”
它声明如下
If the style is ‘%’, the message format string uses %()s styled string substitution; the possible keys are documented in LogRecord attributes. If the style is ‘{‘, the message format string is assumed to be compatible with str.format() (using keyword arguments), while if the style is ‘$’ then the message format string should conform to what is expected by string.Template.substitute().
我在让style='{'正常工作时遇到问题。特别是在每个文档中传递它所需的关键字参数
import logging
logger = logging.getLogger(__name__)
formatter = logging.Formatter('{asctime} - {name} - {levelname} - {message}',style='{')
scrnhandler = logging.StreamHandler()
scrnhandler.setLevel(logging.INFO)
scrnhandler.setFormatter(formatter)
logger.addHandler(scrnhandler)
logger.level = logging.INFO
logger.info("plain message as base case") #<-- Works, no args passed
mystr = "Input args: {0:f}".format(10) #<-- This is supposed to be str.format this is to be followed
logger.info("Input args: {0:f}", 10) #<-- Does not work, I assume it wants a 'named argument'
logger.info("Input args: {args[0]:f}", 10) #<-- Does not work,
# I know the data goes into the LogRecord args attribute so tried that
logger.info("Input args: {a:f}", a=10) #<-- Does not work, is looking for more args to parse
我还没有找到一个例子来说明如何使用这种风格的日志记录,有人能帮我吗 找出我在使用这种日志风格时遗漏的细微差别
我刚才去过那里,也很困惑。至少还有几个开发人员也有同样的感受,因为有bpo14031
摘要
摘要在Use of alternative formatting styles的Python文档中提供(来自BPO)
将其翻译成Python就是这样
② 和③ 是可配置的(还有
string.Template
选项),① 不是,而all it is是:当然,因为Python 3.2日志记录工厂可以通过^{} 进行配置,如Customizing LogRecord中所述。但是对它进行子分类,覆盖
getMessage
并用msg = msg.format(self.args)
*替换msg = msg % self.args
将使用logging
和传递参数(可能以微妙的方式取决于日志记录级别)破坏所有现有代码解决方案
我在考虑如何重写
getMessage
,使其向后兼容%
样式,支持{
样式,并且不会变得太慢。这就是我的目的它可以像这样使用:
在所有4种情况下,它都会生成格式正确的输出。但是,仍然存在一些边缘中断或格式不正确的情况(除了
str.format
模板包含printf样式占位符的情况之外,但是它是否相关取决于您)相关问题 更多 >
编程相关推荐