2

While learning how to use the REST Framework and the authentication mechanisms, I'm looking for a way to log the accesses to the API views for debugging purpose. Inspired by this question and the errors that came with it, I overloaded the initial method and got this:

class ItemViewSet(viewsets.ModelViewSet):
    model = Item
    queryset = Item.objects.all()
    serializer_class = ItemSerializer
    permission_classes = [permissions.IsAuthenticated,]

    def initial(self, request, *args, **kwargs):
        log_data = {
            'user': request.user.pk,

            'remote_address': request.META['REMOTE_ADDR'],

            'request_method': request.method,
            'request_path': request.get_full_path(),
            'request_body': request.data ,
            'request_query_params': request.query_params ,
            'request_auth': request.auth,
        }
        if not os.path.exists('log'):
            os.makedirs('log')

        with open('log/logging.json', 'w') as f:
            json.dump(log_data, f, sort_keys=True, indent=4)
        viewsets.ModelViewSet.initial(self, request, *args, **kwargs)

With this, I indeed get a file created when I run a unit test making a get request on the view or when I access the view with a browser. However, when I make a curl request, it reaches the view, gets a response but the request is not logged. What is wrong with the curl request? How can I log all info related to the request (headers, content...)?

Thank you for helping.

Community
  • 1
  • 1
Xosted
  • 321
  • 2
  • 15
  • have you considered doing this with a custom middleware class? – nkhumphreys Aug 08 '16 at 18:20
  • This is the approach suggested into the question I linked in my original post. However, it creates issues with exception thrown as it seems that the POST data cannot be accessed at middleware level. The suggested solution was to overload the initial method, which I did. – Xosted Aug 08 '16 at 18:33
  • In case it's useful to anyone else the original code served a need I had and it worked fine. I had to remove the reference to request.auth because as I was using a token the `json.dump` didn't like it. That wasn't an issue for me and I was pleased to have this code made available for a quick fix. – glaucon Jul 09 '17 at 10:20

0 Answers0