Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log all REST API requests before they arrive at a viewset

I want to be able to log all REST requests that arrive at the Django REST framework API. I want to log the response of API calls too. Where can I define my function that logs all REST API requests and responses?

like image 280
linuxfreak Avatar asked Nov 08 '22 14:11

linuxfreak


1 Answers

You can write a Django middleware component to intercept traffic into and out of the application.

There will be two methods, process_response and process_request. Use each one to log the response and request, respectively.

class LoggingMiddleware:

    def process_request(self, request):
        # do your logging here

    def process_response(self, request, response):
        # do your logging here

But this will log all requests and responses, not only to the specific API. If you want to log only API ones, you can easily check the URL in this method for prefix like /api and log info based on this.

like image 94
Aldarund Avatar answered Nov 15 '22 05:11

Aldarund