Gre*_*reg 9 python django django-middleware django-email django-errors
有没有办法我可以自定义Django错误报告,所以当它通过电子邮件发送给我时,它让我知道哪个用户触发了错误?
如果重要的话,我在Django 1.2.
非常感谢提前!
Mar*_*rau 14
如果您不想使用哨兵,您可以使用这个简单的中间件将用户信息附加到错误邮件:
# source: https://gist.github.com/646372
class ExceptionUserInfoMiddleware(object):
"""
Adds user details to request context on receiving an exception, so that they show up in the error emails.
Add to settings.MIDDLEWARE_CLASSES and keep it outermost(i.e. on top if possible). This allows
it to catch exceptions in other middlewares as well.
"""
def process_exception(self, request, exception):
"""
Process the exception.
:Parameters:
- `request`: request that caused the exception
- `exception`: actual exception being raised
"""
try:
if request.user.is_authenticated():
request.META['USERNAME'] = str(request.user.username)
request.META['USER_EMAIL'] = str(request.user.email)
except:
pass
Run Code Online (Sandbox Code Playgroud)
您可以简单地将此类放在Django项目下面的*.py文件中,并添加对它的引用MIDDLEWARE_CLASSES
.即如果你把它放在项目根目录(你的settings.py所在的)中的"中间件"文件中,你只需添加即可middleware.ExceptionUserInfoMiddleware
.