2

I have a spring application which exchanges JSON with the mobile. Spring controller looks like this:

@RequestMapping(value = "/register", method = RequestMethod.POST, headers = {"Content-type=application/json"})
public String register(@RequestBody @Valid UserRegistrationRequest urf, BindingResult bindingResult) {
    return toJson(someResponse);
}

I wonder, what is the best way to log http request body and response body? At the moment, I have custom json message converter and it logs a request body, before creating a bean out of json. and I use CustomTraceInterceptor to log a response body. Unfortunately, CustomTraceInterceptor doesn't allow to log request body.

Any advice for better solutions would be highly appreciated!

Thank you in advance.

user3489820
  • 1,459
  • 3
  • 22
  • 38
  • Write a JEE filter (or a spring variant of a filter) and perform logging in that. – DwB Jun 11 '14 at 14:50

1 Answers1

3

Extend HandlerInterceptorAdapter, and override postHandle. Which has request and response injected into it.

You can also use new HttpServletResponseWrapper((HttpServletResponse) response) which has a more friendly api, and spring probably has even nicer wrapper as well ...

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
  • 1
    And how I get response body? – user3489820 Jun 11 '14 at 13:26
  • http://docs.oracle.com/javaee/6/api/javax/servlet/ServletResponse.html#getWriter() – NimChimpsky Jun 11 '14 at 13:49
  • And to enable the interceptor with JavaConfig, in your @Configuration which implements WebMvcConfigurer (usually by way of extending WebMvcConfigurerAdapter) , add \@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new HttpLoggingInterceptor()); } – dan carter Sep 08 '14 at 00:44