我想在我的TB应用程序中记录日志文件的所有异常.所以,我像往常一样尝试使用自定义sys.excepthook.但是仍然会引发每个异常并且不记录任何内容.这是我的代码:
class RootController(BaseController):
secc = SecureController()
error = ErrorController()
def __init__(self):
self.installExceptHook()
super(RootController, self).__init__()
def installExceptHook(self):
def exceptHook(type, value, tb):
logger = logging.getLogger('app')
logger.critical(''.join(traceback.format_exception(type, value, tb)))
sys.excepthook = exceptHook
当我在索引方法中引发ValueError时:
@expose('app.templates.index')
def index(self, **kwargs):
raise ValueError
return dict(page = 'index')
我仍然在浏览器中获取WebError Traceback页面,并且没有记录任何内容.
你知道我做错了什么吗?任何的想法?
最佳答案 从文档(
http://docs.python.org/2/library/sys.html#sys.excepthook):
When an exception is raised and uncaught, the interpreter calls
sys.excepthook […] in a Python program this happens just before the
program exits.
现在,由于WebError捕获异常并处理它(您的应用程序甚至不会退出此类异常),因此该异常未达到调用sys.excepthook的程度.
对于快速而肮脏的解决方案,您可以尝试在配置中设置full_stack = False以禁用WebError中间件(https://github.com/TurboGears/tg2/blob/tg2.2.2/tg/configuration/app_config.py#L1036),这当然意味着您在Web服务器中处理失败响应代码.
如果您只想记录异常但仍使用WebError调试/电子邮件功能,则只需设置自定义中间件,将其包装在应用程序中,记录异常并将其传递.