Saving Django 400 bad requests for analyzing purposes
<p>I have a Django-based API.</p>

<p>Sometimes my customers inform me that some of the their requests return 400 (bad request) even that they're not supposed to.</p>

<p>I thought about a good way to handle and debug that exact problem, by saving the failed-requests, with all of the headers (such as the Access Token) and a timestamp, so when I'll see problematic pattern I'll be able to debug it and find the reason.</p>

<p>My question regarding to my method is - how can I "trigger" a function that will collect the request with all of its headers everytime that I'm returning a response with 400 status?</p>

<p>If the 400 response is generated by Django, you can use a <a href="https://docs.djangoproject.com/en/1.10/topics/http/middleware/" rel="nofollow">custom middleware</a> (beware: the middleware api changed in 1.10, for django &lt;= 1.9 the doc is <a href="https://docs.djangoproject.com/en/1.9/topics/http/middleware/" rel="nofollow">here</a>) and the <a href="https://docs.python.org/2/library/logging.html" rel="nofollow"><code>logging</code> module</a> - just make sure your logging is <a href="https://docs.djangoproject.com/en/1.10/topics/logging/" rel="nofollow">correctly configured</a> in your django settings.</p>

<p>If the 400 response happens at a higher level then you'll have to check the relevant doc according to how your project is deployed</p>

<p>Also FYIY <code>django.core.WSGIHandler</code> yields a 400 response when a <code>UnicodeDecodeError</code> happens while instanciating the <code>HttpRequest</code> object - in this case AFAICT the middlewares won't even be invoked. You should already find traces of these occurences in the logger configured for <code>django.requests</code> (cf <a href="https://docs.djangoproject.com/en/1.10/topics/logging/#django-request" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/logging/#django-request</a>)</p>

python django