2

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;
}
Mansur
  • 1,661
  • 3
  • 17
  • 41
  • 1
    Does this help? http://slackspace.de/articles/log-request-body-with-spring-boot/ – Honza Zidek Jul 18 '19 at 08:35
  • 1
    Maybe also one of these: https://stackoverflow.com/q/33744875/2886891 https://stackoverflow.com/q/48301764/2886891 https://stackoverflow.com/q/7952154/2886891 – Honza Zidek Jul 18 '19 at 08:39

1 Answers1

0

you can rewrite a controller class and redirect the request you have intercepted. and also you can write a filter to intercept the request from the front end, then pass it on to the DispatcherServlet. I can't provide the code cause you haven't put your code on.