任务:当我的一个视图中发生错误时,我需要显示自定义错误视图.错误类型无关紧要.
我尝试通过registring查看所有异常来覆盖所有异常,如下所示:
它运作良好.所有例外都显示了我的观点.但问题是那些错误停止了记录.在我的错误视图中,我可以执行类似logger.error(traceback)的操作,但这是一个愚蠢的想法.
最佳答案
您可以通过普通的旧python日志记录在视图中记录错误.或者将响应的状态设置为500(假设您的视图现在返回状态200,表示响应成功).
原文链接:https://www.f2er.com/python/439270.html编辑:工作示例
我不是一个日志记录专家,但我的印象是你的developer.ini / production.ini中的日志配置会被拾取,下面的例子似乎证明了这一点,但你是判断……
从默认情况下更改为日志配置
[formatter_generic]
# format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s
format = y u no work??!!?? %(message)s
# End logging configuration
观点
from pyramid.view import view_config
from webob import Response
import logging
log = logging.getLogger(__name__)
@view_config(route_name='home',renderer='templates/mytemplate.pt')
def my_view(request):
raise ValueError("oops")
return {'project':'tstLogError'}
@view_config(context=Exception)
def exception_view(context,request):
log.error("The error was: %s" % context,exc_info=(context))
return Response(status_int=500,body=str(context))
from pyramid.view import view_config
from webob import Response
控制台输出:
serving on http://0.0.0.0:6543
y u no work??!!?? The error was: oops
Traceback (most recent call last):
File "/home/twillis/projects/TestLogError/local/lib/python2.7/site-packages/pyramid/tweens.py",line 20,in excview_tween
response = handler(request)
File "/home/twillis/projects/TestLogError/local/lib/python2.7/site-packages/pyramid/router.py",line 164,in handle_request
response = view_callable(context,request)
File "/home/twillis/projects/TestLogError/local/lib/python2.7/site-packages/pyramid/config/views.py",line 333,in rendered_view
result = view(context,line 471,in _requestonly_view
response = view(request)
File "/home/twillis/projects/TestLogError/tstLogError/tstlogerror/views.py",line 8,in my_view
raise ValueError("oops")
ValueError: oops