如何获取日志TypeError的行号“在字符串格式化过程中不是所有参数都被转换”?

时间:2013-08-01 17:42:14

标签: python exception logging error-handling error-logging

如果我使用内置的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

鉴于我有大量的日志记录语句,有没有办法得到更有用的错误信息 - 一个显示错误发生的行号?

2 个答案:

答案 0 :(得分:0)

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

import logging

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

堆栈跟踪中的某个位置将是对logger.debug的违规调用。请注意警告:

  

请注意,只是插入这样的错误处理程序不是您想要部署的,因为日志记录中的错误应该引入应用程序错误。确保您首先正确地记录所有日志消息的确非常重要。在将此错误转储代码永久保留在应用程序中之前,请务必阅读并理解有关handleError如何在消息线程中工作的注释。

答案 1 :(得分: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的回答中提出的任何技巧。