I've been trying to find a way to log the response body of requests in my spring boot application. I've abandoned this for now and will just log in each controller before returning, because the effort to get this to work (globally, for all controllers with a Filter or request interceptor) seems inordinately large / overly complicated.
In python django projects, it seems this could be as simple as a middleware with something like log.info(response.body)
.
I'm new to Java, so I am sure there is a valid reason, but can someone explain WHY?
To try to get a string representation of the response body in java, from an HttpServletResponse involves all sorts of wrangling like this
CodePudding user response:
HttpServletRequest
/Response
classes are designed to stream the data directly from/to the browser. They are there to handle the I/O communication over the network, but they do not need to store the whole request/response body.
This allows servlets to directly stream data, and by the time you would want to log the response, the data has already been sent over the network (well, except with async processing but that makes things even more complicated for your purposes). A default implementation wouldn’t know that it had to keep a copy of the data for logging purposes.
This is why you need to implement a Filter
that would wrap the request/response in order to keep and log the body, as you have pointed in your link. In general you will probably want to customize this behavior in order to select only specific requests, limit the size, define how to log it etc. so a default implementation is not provided, but you have a lot of solutions.