Reputation: 761
I have a django project on production. In my settings.py
file Debug=False
to avoid security risks which arrises when Debug=True
I heard about python logging module which I am trying to set up. But after reading documentation like I understand I should put logging instances in each piece of code where error can be arrised, but what if I need to handle 404 errors? How I can handle them? Please anyone guide me
Upvotes: 0
Views: 1341
Reputation: 1618
I think there is quite a bunch of information around about 404 handling in django. The most basic thing might be the 404 view that you can override with your custom logics (which i think is not preferred, but might come in handy in some specific cases): https://docs.djangoproject.com/en/3.0/topics/http/views/#customizing-error-views
The preferred method would be going deeper in to the core of request and response handling where you can manipulate your requests having a response status_code of 404
or what so ever. In your middleware
you can extend and override behavior of existing middlewares or add your own: https://docs.djangoproject.com/en/3.0/topics/http/middleware/
Below you have simple example of a middleware that checkes the response's status code and uses log.warning
when the reponse has a status_code of 404
. In this scenario you'll have a single location being responsible of logging the faulty paths that are being requested.
# myproject.middleware.py
import logging
logger = logging.getLogger(__name__)
class PageNotFoundMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
if response.status_code == 404:
logger.warning("Page not found at {}".format(request.path))
return response
in your settings.py
you can now add the middleware:
MIDDLEWARE = [
...
'myproject.middleware.PageNotFoundMiddleware',
]
Upvotes: 1