Nikolai Prokoschenko
Nikolai Prokoschenko

Reputation: 8755

Why does Django's flatpages allow logging a 404 error?

A funny thing I've noticed about Django's flatpages app: it allows core/handlers/base.py to log a warning Not Found: $page. As a result of that, my Sentry logs are full with 404s for legitimate and working pages. It seems to happen because first Django logs a 404, then it returns a HttpResponseNotFound object and then the flatpages middleware kicks in and returns a proper 200 response.

Is this something I could consider a bug in Django? My reasoning is that a valid flatpage is not a missing page and thus shouldn't log a 404 message. Isn't there an other way to catch a 404 without logging it as missing?

Upvotes: 1

Views: 498

Answers (2)

Maik Hoepfel
Maik Hoepfel

Reputation: 1797

I think the solution to your problem is easy: just re-order the Sentry404CatchMiddleware to the top of your MIDDLEWARES setting. At the very least, it should be above the flatpages middleware.

To explain what's going on, it's helpful to understand the order in which middlewares are executed. I'm guessing you followed the Sentry docs and placed it at the bottom. That makes it the first middleware to be executed. If a request comes in for an unmatched URL pattern, Django raises a 404 and the Sentry middleware logs it. But Django then runs through the other middlewares, and the flatpages middleware does it's thing where it looks up if a matching page exists, and actually replaces the response.

If you move the Sentry middleware to the top, only 404 errors that bubble all the way through the middleware stack will get logged, which is likely what you want.

Upvotes: 2

seler
seler

Reputation: 9193

It's not a bug, it's the way that django flatpages app work: its middleware kicks in after 404 from urls. That's why your sentry is full of 404s.

Consider not registering 404 in sentry. :/ I dont see any other way here.

There might be another solution: instead of using middleware try to include flatpages.urls at end of your urlpatterns.

Upvotes: 1

Related Questions