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

标签 python python-2.7 string-formatting

我使用 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/

相关文章:

python - 在 python 中格式化 nan float

python - Django在同一数据表的多个字段中搜索查询

python - 如何在 Linux 终端上进行按键检测,python 中的低级样式

python - 在 Python 2.7 和 OpenCV 3.3 中使用 triangulatePoints 每次输出 3D 点都会发生变化

python - fnmatch 不适用于变量,但适用于静态字符串

python - 练习 14 艰难地学习 Python

python - Pandas :read_csv 忽略空行后的行

python - 为什么这个字符串不会转换为浮点型?

python - 如何根据列名删除列python pandas

c++ - 如何在非托管 C++ 代码中检查字符串是否具有有效的文件路径或目录路径格式?