-
-
Notifications
You must be signed in to change notification settings - Fork 7k
Description
I want to pass some custom data to my log records, and I am doing so like this: https://stackoverflow.com/questions/10292082/django-logging-django-request-logger-and-extra-context/
However, when I construct a rest_framework.request.Request out of the given record.request object (Django HttpRequest passed as extra to the django.request logger), I can't access its data attribute if request.data has been explicitly accessed by the view that I am logging. If it hasn't been accessed, then no error occurs. When I say "can't" I mean I get a RawPostDataException: You cannot access body after reading from request's data stream error. 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 TrueAgain, if the view that is being logged doesn't access request.data, no error occurs.
I have also asked a relevant question at SO: https://stackoverflow.com/questions/69437529/cannot-access-request-data-in-log-filter
Any help would be much appreciated.