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/40600711/

相关文章:

Python 错误 : PyThreadState_Get: no current thread after compiling an extension

python - 如何在没有输入的情况下使用 raw_input

Python Tkinter - 当我尝试在新窗口上使用输入表单时,它们不起作用

Python3线程池: apply function to task generator

python - 在 Python 中规范化小概率

python - 什么是 C++ 中 "new"的 python 等价物

objective-c - 重新格式化表示日期的 NSString

c++ - 如何创建可变参数模板字符串格式化程序

c++ - 如何使用现代 C++ 在控制台中打印 "justified"文本

Python 3 : How to use subprocess. 以管理员身份运行()(Windows 10)