I am using Django REST Framework, and following this django logging - django.request logger and extra context answer to include custom data to my log records. When trying to access record.request.data
inside filter()
(to store it to record.data
as that answer suggests) I get RawPostDataException: You cannot access body after reading from request's data stream
. I have tried many things, none of which worked. Cannot manually rewind the request's data stream, nor get a fresh copy of the request object. I never manually access request.body
, as the SO answers suggest avoiding. Any help would be appreciated.
Here is the code:
import logging
from rest_framework.request import Request
from rest_framework.settings import api_settings
class RequestInfoFilter(logging.Filter):
def filter(self, record):
parsers = [parser() for parser in api_settings.DEFAULT_PARSER_CLASSES]
authenticators = [
auth() for auth in api_settings.DEFAULT_AUTHENTICATION_CLASSES]
request = Request(
record.request, parsers=parsers, authenticators=authenticators)
record.method = request.method
record.query_params = request.query_params
record.data = request.data # RawPostDataException: You cannot access body after reading from request's data stream
return True
Note that this happens only when logging views that access request.data
themselves. If they don't, no error occurs.