Python: Logging TypeError: not all arguments converted during string formatting怎么办?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (1619)

这是我正在做的

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

我如何使它工作?

提问于
用户回答回答于

你可以自己格式化:

logging.info('date={}'.format(date))
用户回答回答于

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

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

日志记录模块使用旧式%运算符来格式化日志字符串。查看更多细节的debug方法

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

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模块文档提出的一种方法,它也适用于Python 2。

扫码关注云+社区

领取腾讯云代金券