使用 Django 将 404 Not Found 页面记录到 Sentry

Logging 404 Not Found pages to Sentry with Django

我想将 404 Not Found 错误代码记录到 Django 1.7 中的 Sentry。

Django 提供了哪些钩子以便我可以为这些推送 logger.error() 消息?

关于如何使用 Django 和 Sentry 监控非 500 个丢失/异常行为的页面还有其他想法吗?

查看自定义错误处理程序的文档。

基本上我认为您可能想要为要捕获的错误设置视图,这些视图可以呈现您需要的模板或记录消息等; Customising error views。 显然,在这些视图中,您可以访问请求对象的部分内容以收集您可能需要的任何信息。

Sentry 有一个中间件可以自动记录 404。

# Use ``MIDDLEWARE_CLASSES`` prior to Django 1.10
MIDDLEWARE = (
    'raven.contrib.django.raven_compat.middleware.Sentry404CatchMiddleware',
    ...,
) + MIDDLEWARE

请参阅 Sentry Django 文档中的 "404 Logging" 了解更多信息,包括如何忽略某些路径的 404。

检查 Django 哨兵文档的 Reporting other status codes 部分:

如果你想向Sentry报告404 Not Found和除未捕获异常(500 Internal Server Error)之外的其他错误,你需要为这些状态码编写自己的Django视图。例如:

# in the root URL conf urls.py

handler404 = 'myapp.views.my_custom_page_not_found_view'

# myapp/views.py

from django.http import HttpResponseNotFound
from sentry_sdk import capture_message


def my_custom_page_not_found_view(*args, **kwargs):
    capture_message("Page not found!", level="error")

    # return any response here, e.g.:
    return HttpResponseNotFound("Not found")

有关自定义错误的详细信息,请阅读 relevant Django Docs