2014-04-25 36 views
2

我正在寻找一种获取403错误的方法,以便通过完整的堆栈跟踪和请求转储触发管理员错误电子邮件 - 类似于500错误。在Django中设置日志以电子邮件发送403错误(CSRF错误)

具体如何将它添加到我的日志记录配置CSRF中间件发出警告级别消息。但我不希望所有django.request警告消息,只有403S ..

将工作
+0

你看了这页吗? https://docs.djangoproject.com/en/dev/howto/error-reporting/ –

+0

https://docs.djangoproject.com/zh/dev/topics/logging/更有用,但仍然不那么清楚 –

回答

1

一种方法是使用自定义的403处理器视图,并调用mail_admins从那里:

在你urls.py,添加

handler403 = 'myproj.myviews.error403' 

myviews.py

def error403(request): 
    """ 
    Custom handling of 403s, to send an email to the admins 
    """ 

    mail_admins(
     "403 alert", 
     "%s got hit in the face with Forbidden shovel" % request.user 
    ) 
    # NB: this isn't a robust reporting message as 
    #may not be partic suited to anonymous users 

    return HttpResponseForbidden() 

理想情况下,你的邮件需要进行排队和发送异步到PR事件你的用户不得不等待,但这是一个单独的事情。

+0

不错解决办法 - 理想情况下,我想将其添加到我的日志记录配置中,但如果不是这样,这也可以解决问题。 –

+0

通过适当设置的日志记录,您可以在视图中提高logger.critical()而不是mail_admins,并且这将使记录器设置报告它 –

+0

好点谢谢 –