gpt4 book ai didi

python - 使用新格式字符串记录变量数据

转载 作者:IT老高 更新时间:2023-10-28 21:33:58 25 4
gpt4 key购买 nike

我使用 python 2.7.3 的日志记录工具。 Documentation for this Python version say :

the logging package pre-dates newer formatting options such as str.format() and string.Template. These newer formatting options are supported...

我喜欢带有花括号的"new"格式。所以我正在尝试做类似的事情:

 log = logging.getLogger("some.logger")
log.debug("format this message {0}", 1)

并得到错误:

TypeError: not all arguments converted during string formatting

我在这里想念什么?

附:我不想使用

log.debug("format this message {0}".format(1))

因为在这种情况下,无论记录器级别如何,消息总是被格式化。

最佳答案

编辑:看看StyleAdapter approach in @Dunes' answer不像这个答案;它允许在调用记录器的方法(debug()、info()、error() 等)时使用其他格式样式而无需样板。


来自文档 — Use of alternative formatting styles :

Logging calls (logger.debug(), logger.info() etc.) only take positional parameters for the actual logging message itself, with keyword parameters used only for determining options for how to handle the actual logging call (e.g. the exc_info keyword parameter to indicate that traceback information should be logged, or the extra keyword parameter to indicate additional contextual information to be added to the log). So you cannot directly make logging calls using str.format() or string.Template syntax, because internally the logging package uses %-formatting to merge the format string and the variable arguments. There would no changing this while preserving backward compatibility, since all logging calls which are out there in existing code will be using %-format strings.

还有:

There is, however, a way that you can use {}- and $- formatting to construct your individual log messages. Recall that for a message you can use an arbitrary object as a message format string, and that the logging package will call str() on that object to get the actual format string.

将此复制粘贴到 wherever 模块:

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)

然后:

from wherever import BraceMessage as __

log.debug(__('Message with {0} {name}', 2, name='placeholders'))

注意:实际格式化会延迟到需要时,例如,如果未记录 DEBUG 消息,则根本不执行格式化。

关于python - 使用新格式字符串记录变量数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13131400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com