Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83438

Logging 404 Not Found pages to Sentry with Django

I'd like to log 404 Not Found errors codes to Sentry in Django 1.7.

What hooks Django provides so I could push logger.error() message for these?

Any other ideas how one should monitor non-500 missing / weirdly behaving pages with Django and Sentry?

Upvotes: 5

Views: 3753

Answers (3)

GunnerFan
GunnerFan

Reputation: 4047

Checkout the Reporting other status codes section of the Sentry Docs for Django:

If you want to report 404 Not Found and other errors besides uncaught exceptions (500 Internal Server Error) to Sentry, you need to write your own Django view for those status codes. For example:

# 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")

For more information on customizing errors, read the relevant Django Docs

Upvotes: 4

Jeff Bowen
Jeff Bowen

Reputation: 6162

Sentry has a middleware to log 404s automatically.

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

See "404 Logging" in the Sentry Django documentation for more info including how to ignore 404s for certain paths.

Upvotes: 2

markwalker_
markwalker_

Reputation: 12859

Take a look at the docs for custom error handlers.

Basically I think you'll probably want to setup views for the errors you want to capture which can render templates you need or log messages etc; Customising error views. Obviously in those views you can access parts of the request object to collect any information you might need.

Upvotes: 1

Related Questions