I want to access the raw payload (in my case Json body) before it gets deserialized into a POJO.
My controller has a method with a signature like the following.
public ResponseEntity doSomething(@RequestBody @Validated Dto dto, Errors erros)
Now, I would like to just access the initial payload so that I can log it.
What I have tried so far is creating an interceptor in which get the HttpServletRequest
object and get either Reader
or InputStream
and do the logging. It works perfect. But the issue is what happens afterwards. Since I have already accessed Reader
or InputStream
objects, it throws IllegalStateException
saying They have already been called
.
What I tried next was ContentCachingRequestWrapper
. It solves the issue above but this time when I call the endpoint, it generates Bad Request
with no response body. I think something's wrong with ParameterMap
in this solution. Which is also pointed out here. Also the solution there doesn't work for me, the byte array seems empty.
So is there any way to log the raw payload before it is deserialized? I don't want to touch the controller, actually. To my mind, it would be better to do this through Interceptors. Thanks, beforehand.
Update. Thanks for directing me to correct resources. I used the following solution which worked perfectly. Adding CommonsRequestLoggingFilter
worked. But please note that logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG
should be enabled.
@Bean
public CommonsRequestLoggingFilter requestLoggingFilter() {
CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();
loggingFilter.setIncludeClientInfo(true);
loggingFilter.setIncludeQueryString(true);
loggingFilter.setIncludePayload(true);
return loggingFilter;
}