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.