Python:记录类型错误:字符串格式化期间并非所有参数都转换

标签 python logging string-formatting

这就是我正在做的事情

>>> import logging
>>> logging.getLogger().setLevel(logging.INFO)
>>> from datetime import date
>>> date = date.today()
>>> logging.info('date={}', date)
Traceback (most recent call last):
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 846, in emit
    msg = self.format(record)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 723, in format
    return fmt.format(record)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 464, in format
    record.message = record.getMessage()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 328, in getMessage
    msg = msg % self.args
TypeError: not all arguments converted during string formatting
Logged from file <stdin>, line 1
>>> 

我的python版本是

$ python --version
Python 2.7.3

如何让它发挥作用?

最佳答案

使用日志模块时不能使用新式格式;使用 %s 而不是 {}

logging.info('date=%s', date)

日志模块使用旧式 % 运算符来格式化日志字符串。见 debug method了解更多详情。

如果您真的想使用 str.format() 字符串格式,请考虑在实际转换为字符串时使用应用格式“延迟”的自定义对象:

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)

__ = BraceMessage

logging.info(__('date={}', date))

这是一种方法 Python 3 logging module documentation proposes ,而且它恰好也适用于 Python 2。

关于Python:记录类型错误:字符串格式化期间并非所有参数都转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12843099/

相关文章:

python - 计算R中圆半径的倒数

python - 如何使用 gunicorn 在 heroku 上提供 django 静态文件

tomcat - tomcat 是否有能力覆盖 log4j 日志记录级别?

wpf - 如何使用样式/模板格式化 wpf 中的小数位数?

ios - swift 3 Xcode : How to display battery levels as an integer?

python - 如何在 Pandas 中标记具有多个条件的列?

python - 如何更改 matplotlib 中所有文本的默认字体颜色?

objective-c - 在 mac 文件夹中从 ios 模拟器创建一个文件

node.js - SailsJS 中的自定义记录器

java - 将 JTextArea 格式化为表格格式