如果我对您的理解正确,这里的问题是回溯没有给您任何指示错误源自代码中的何处。不知何故,你不得不追查这条线
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