使用新格式字符串记录变量数据 [英] Logging variable data with new format string

查看:51
本文介绍了使用新格式字符串记录变量数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 python 2.7.3 的日志记录工具.此 Python 版本的文档说:

I use logging facility for python 2.7.3. Documentation for this Python version say:

日志包预先确定了新的格式选项,例如 str.format() 和 string.Template.支持这些较新的格式选项...

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

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

I like 'new' format with curly braces. So i'm trying to do something like:

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

并得到错误:

TypeError: 在字符串格式化期间并非所有参数都被转换

TypeError: not all arguments converted during string formatting

我在这里想念什么?

附言我不想使用

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

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

because in this case the message is always being formatted regardless of logger level.

推荐答案

看看 StyleAdapter @Dunes 答案中的方法 与此答案不同;它允许在调用记录器的方法(debug()、info()、error() 等)时使用没有样板的替代格式样式.

take a look at the StyleAdapter approach in @Dunes' answer unlike this answer; it allows to use alternative formatting styles without the boilerplate while calling logger's methods (debug(), info(), error(), etc).

来自文档 — 使用替代格式样式:

记录调用(logger.debug(), logger.info() 等)只需要实际日志消息本身的位置参数,与关键字参数仅用于确定如何处理的选项实际的日志调用(例如 exc_info 关键字参数表示应该记录回溯信息,或者额外的关键字参数来指示要添加的附加上下文信息添加到日志中).所以你不能直接使用str.format() 或 string.Template 语法,因为在内部记录包使用 %-formatting 合并格式字符串和变量论据.在保留向后的同时不会改变这一点兼容性,因为现有的所有日志调用代码将使用 % 格式的字符串.

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.

还有:

但是,有一种方法可以使用 {}- 和 $- 格式来构建您的个人日志消息.回想一下,对于您的消息可以使用任意对象作为消息格式字符串,并且logging 包将对该对象调用 str() 以获取实际格式字符串.

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.

复制粘贴到where模块:

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 消息,则根本不会执行格式化.

Note: actual formatting is delayed until it is necessary e.g., if DEBUG messages are not logged then the formatting is not performed at all.

这篇关于使用新格式字符串记录变量数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆