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

2024-04-24 01:11:12 发布

您现在位置:Python中文网/ 问答频道 /正文

这就是我要做的

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

我该怎么做?


Tags: inpyformatdateinitliblocallogging
3条回答

Martijn的回答是正确的,但是如果您喜欢在日志中使用新样式的格式,那么可以通过子类化Logger来实现。

import logging

class LogRecord(logging.LogRecord):
    def getMessage(self):
        msg = self.msg
        if self.args:
            if isinstance(self.args, dict):
                msg = msg.format(**self.args)
            else:
                msg = msg.format(*self.args)
        return msg

class Logger(logging.Logger):
    def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
        rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func)
        if extra is not None:
            for key in extra:
                rv.__dict__[key] = extra[key]
        return rv

然后设置日志类:

logging.setLoggerClass(Logger)

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

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

日志模块使用旧式的%运算符格式化日志字符串。有关详细信息,请参见^{} method

如果确实要使用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 ^{} module documentation proposes方法,它碰巧也适用于Python 2。

您可以自己设置格式:

logging.info('date={}'.format(date))

正如Martijn Pieters指出的,这将始终运行字符串格式化,而使用日志模块将导致只有在实际记录消息时才执行格式化。

相关问题 更多 >