如何获得“不是字符串格式化期间转换的所有参数"的记录TypeError的行号? [英] How do I get the line number for a logging TypeError of "not all arguments converted during string formatting"?
问题描述
如果我使用内置的python日志记录机制,但我犯了一个错误,例如:
If I'm using the built-in python logging mechanism and I make a mistake, such as:
logger.debug("The result is", result)
然后我收到一条无用的错误消息:
Then I get an unhelpful error message:
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
鉴于我有大量的日志记录语句,有什么方法可以得到一条更有用的错误消息-一种显示发生错误的行号的消息吗?
Given I have a very large number of logging statements, is there any way to get a more helpful error message - one showing the line number where the mistake was made?
推荐答案
Thanks to Greg Smith, this is easy to do. Wherever the logging code is set up, do:
import logging
def handleError(self, record):
raise
logging.Handler.handleError = handleError
在堆栈跟踪中的某处将是对logger.debug
的有害调用.注意警告:
Somewhere in the stack trace will be the offending call to logger.debug
. Note the caveat:
请注意,仅插入这样的错误处理程序并不是您要部署的,因为日志记录中的错误会引入应用程序错误.首先,要确保所有日志消息正确无误.在将此错误转储代码永久保留在您的应用程序中之前,请确保您已阅读并通过理解有关handleError如何在消息线程中如何工作的注释进行了跟踪,然后将其永久保留在应用程序中.
Note that just inserting an error handler like this isn't what you want to deploy, because an error in logging should introduce an application error. It's really more for making sure you get all your log messages correct in the first place. Make sure you read and following through understanding the comments about how handleError works later in the message thread before leaving this error dumping code in your app permanently.
这篇关于如何获得“不是字符串格式化期间转换的所有参数"的记录TypeError的行号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!