1

如果我使用的是内置的 python 日志记录机制并且我犯了一个错误,例如:

logger.debug("The result is", result)

然后我收到一条无用的错误消息:

Traceback (most recent call last):
File "/usr/lib/python2.6/logging/__init__.py", line 760, in emit
msg = self.format(record)
File "/usr/lib/python2.6/logging/__init__.py", line 644, in format
return fmt.format(record)
File "/usr/lib/python2.6/logging/__init__.py", line 432, in format
record.message = record.getMessage()
File "/usr/lib/python2.6/logging/__init__.py", line 302, in getMessage
msg = msg % self.args
TypeError: not all arguments converted during string formatting

鉴于我有大量的日志记录语句,有没有办法获得更有用的错误消息 - 显示错误所在的行号?

4

2 回答 2

0

感谢Greg Smith,这很容易做到。无论在何处设置日志记录代码,请执行以下操作:

import logging

def handleError(self, record):
    raise
logging.Handler.handleError = handleError

堆栈跟踪中的某处将是对logger.debug. 注意警告:

请注意,仅插入这样的错误处理程序并不是您想要部署的,因为日志记录中的错误应该会引入应用程序错误。确保您一开始就正确获取所有日志消息确实更重要。确保您阅读并理解了稍后在消息线程中有关 handleError 如何工作的评论,然后再将此错误转储代码永久保留在您的应用程序中。

于 2013-08-01T17:42:14.210 回答
0

在最新版本的 Python 中,会打印您想要的信息。考虑以下脚本logex.py

import logging

logger = logging.getLogger(__name__)

def test():
    logger.debug('The result is ', 'abc')

def main():
    test()

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    main()

当使用 Python 2.7 运行时:

$ python logex.py
Traceback (most recent call last):
  File "/usr/lib/python2.7/logging/__init__.py", line 842, in emit
    msg = self.format(record)
  File "/usr/lib/python2.7/logging/__init__.py", line 719, in format
    return fmt.format(record)
  File "/usr/lib/python2.7/logging/__init__.py", line 464, in format
    record.message = record.getMessage()
  File "/usr/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 logex.py, line 6

使用 Python 3.2:

$ python3.2 logex.py
Traceback (most recent call last):
  File "/usr/lib/python3.2/logging/__init__.py", line 937, in emit
    msg = self.format(record)
  File "/usr/lib/python3.2/logging/__init__.py", line 812, in format
    return fmt.format(record)
  File "/usr/lib/python3.2/logging/__init__.py", line 551, in format
    record.message = record.getMessage()
  File "/usr/lib/python3.2/logging/__init__.py", line 319, in getMessage
    msg = msg % self.args
TypeError: not all arguments converted during string formatting
Logged from file logex.py, line 6

因此,除非您使用的是旧版本的 Python,否则您不必使用 Claudiu 回答中建议的任何技巧。

于 2013-08-01T20:39:57.950 回答