如果我理解得正确,这里的问题是回溯无法告诉您错误从代码的哪个部分开始。您需要追踪到出错的行。
logging.debug('This is a string %d', str(foo))
自我介绍。
日志模块的设计是这样的,发生在emit()调用期间的异常由处理程序的handleError方法处理:
def handleError(self, record):
"""
Handle errors which occur during an emit() call.
This method should be called from handlers when an exception is
encountered during an emit() call. If raiseExceptions is false,
exceptions get silently ignored. This is what is mostly wanted
for a logging system - most users will not care about errors in
the logging system, they are more interested in application errors.
You could, however, replace this with a custom handler if you wish.
The record which was being processed is passed in to this method.
"""
您可以重写此方法以查看完整的回溯信息:
import sys
import logging
class MyStreamHandler(logging.StreamHandler):
def handleError(self, record):
raise
if __name__ == '__main__':
console = MyStreamHandler()
logger=logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(console)
logger.debug('%d','ahh')
收益率
Traceback (most recent call last):
File "/tmp/test.py", line 25, in <module>
logger.debug('%d','ahh')
File "/usr/lib/python2.6/logging/__init__.py", line 1036, in debug
self._log(DEBUG, msg, args, **kwargs)
File "/usr/lib/python2.6/logging/__init__.py", line 1165, in _log
self.handle(record)
File "/usr/lib/python2.6/logging/__init__.py", line 1175, in handle
self.callHandlers(record)
File "/usr/lib/python2.6/logging/__init__.py", line 1212, in callHandlers
hdlr.handle(record)
File "/usr/lib/python2.6/logging/__init__.py", line 673, in handle
self.emit(record)
File "/usr/lib/python2.6/logging/__init__.py", line 796, in emit
self.handleError(record)
File "/usr/lib/python2.6/logging/__init__.py", line 768, in emit
msg = self.format(record)
File "/usr/lib/python2.6/logging/__init__.py", line 648, in format
return fmt.format(record)
File "/usr/lib/python2.6/logging/__init__.py", line 436, in format
record.message = record.getMessage()
File "/usr/lib/python2.6/logging/__init__.py", line 306, in getMessage
msg = msg % self.args
TypeError: %d format: a number is required, not str
如果使用普通的StreamHandler,你只能得到以下结果:
Traceback (most recent call last):
File "/usr/lib/python2.6/logging/__init__.py", line 768, in emit
msg = self.format(record)
File "/usr/lib/python2.6/logging/__init__.py", line 648, in format
return fmt.format(record)
File "/usr/lib/python2.6/logging/__init__.py", line 436, in format
record.message = record.getMessage()
File "/usr/lib/python2.6/logging/__init__.py", line 306, in getMessage
msg = msg % self.args
TypeError: %d format: a number is required, not str