How to log requests that are not successful?

I want to write a middleware that log all requests which have not a successful (200 statuses) and using causes the error You cannot access body after reading from request's data stream and when I do something like request_clone = copy.copy(request) and then using it’s body, it’s empty.

I would think you’d be looking for the status_code attribute of the response object.

What are you looking to retrieve from the request object?

(You could make a copy of what you need from the request object before passing the request to the view, then using that information along with the status_code after the view has been executed.)

As I’ve stated, tried to copy the request itself but the body property is empty.

I think we’d need to see your middleware code to be able to provide any further assistance.

When posting code here, please enclose it between lines consisting only of three backtick (`) characters. This means you’ll have a line that is only ```, followed by your code, followed by another line of ```. This allows your code to remain formatted.

It’s my middleware code:

class RequestLoggerMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        self.logger = logging.getLogger("portal.request")

    def __call__(self, request):
        response = self.get_response(request)
        request_log = (
        if hasattr(response, "rendered_content"):
            response_log = (
            response_log = (
        if not status.is_success(response.status_code):
                f"{request.path} {response.status_code}"
                f" {response.reason_phrase}\n{request_log}\n\n{response_log}"
        return response

Also documented in the request object docs.

I can’t get your point, would you mind providing a short code snippet of what I would do?

The Middleware docs do a much better job of describing this than I could.

I’ve read the docs, and currently viewing the source code but I doubt I missed your point.

I copy the request object like this request_clone = copy.copy(request) so it should be OK to access the clone object body, but it gives me Error and if I use it’s empty.

Tnx BTW, I fixed it by copying just the request.body part.
Happy Coding