0

I want to implement Rest logging for API using Spring. I tried this:

public static String readPayload(final HttpServletRequest request) throws IOException {
      String payloadData = null;
      ContentCachingRequestWrapper contentCachingRequestWrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class);
      if (null != contentCachingRequestWrapper) {
          byte[] buf = contentCachingRequestWrapper.getContentAsByteArray();
          if (buf.length > 0) {
              payloadData = new String(buf, 0, buf.length, contentCachingRequestWrapper.getCharacterEncoding());
          }
      }
      return payloadData;
  }  

  public static String getResponseData(final HttpServletResponse response) throws IOException {
        String payload = null;
        ContentCachingResponseWrapper wrapper =
            WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
        if (wrapper != null) {
            byte[] buf = wrapper.getContentAsByteArray();
            if (buf.length > 0) {
                payload = new String(buf, 0, buf.length, wrapper.getCharacterEncoding());
                wrapper.copyBodyToResponse();
            }
        }
        return payload;
    }



  @PostMapping(value = "/v1", consumes = { MediaType.APPLICATION_XML_VALUE,
      MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_XML_VALUE,
          MediaType.APPLICATION_JSON_VALUE })
  public PaymentResponse handleMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {


      HttpServletRequest requestCacheWrapperObject = new ContentCachingRequestWrapper(request);
      requestCacheWrapperObject.getParameterMap();

      .raw_request(readPayload(requestCacheWrapperObject))
      .raw_response(getResponseData(response))
  }

But I get NULL for request and response. Do you know what is the proper way to get the payload from the request and the response?

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808
  • Possible duplicate of [Spring Boot - How to log all requests and responses with exceptions in single place?](https://stackoverflow.com/questions/33744875/spring-boot-how-to-log-all-requests-and-responses-with-exceptions-in-single-pl) – Sambit May 22 '19 at 16:50

2 Answers2

2

So you just need to have your own interceptor.

@Component
public class HttpRequestResponseLoggingInterceptorAdapter extends HandlerInterceptorAdapter {

@Autowired
private LoggingUtils loggingutils;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    loggingutils.preHandle(request, response);
    return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        @Nullable ModelAndView modelAndView) {
    try {
        loggingutils.postHandle(request, response);
    } catch(Exception e) {
        System.out.println("Exception while logging outgoing response");
    }
}

}

Once that is done, you need to bind your new interceptor to existing interceptors.

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

@Autowired
private HttpRequestResponseLoggingInterceptorAdapter httpRequestResponseLoggingInterceptorAdapter;

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(httpRequestResponseLoggingInterceptorAdapter);
}

}

Once that is done, your incoming requests for handlemessage method will be intercepted, and can do whatever pre/post processing you want to have. Logging in this case.

Let me know if this helps.

Debashis
  • 81
  • 1
  • 9
0

Sounds like your usecase would be best suited with a class extending spring's org.springframework.web.servlet.handler.HandlerInterceptorAdapter.

Custom interceptors can override preHandle and postHandle - both of which it sounds like you are inclined to use.

EDIT:

// add to wherevere your source code is
public class CustomInterceptor extends HandlerInterceptorAdapter {
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        // TODO: use 'request' from param above and log whatever details you want
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
                // TODO: use 'response' from param above and log whatever details you want
    }
}


// add to your context
<mvc:interceptors>
    <bean id="customInterceptor" class="your.package.CustomInterceptor"/>
</mvc:interceptors>
Christian B
  • 102
  • 3