Spring API中的日志请求和响应

时间:2019-05-22 16:46:26

标签: java spring rest spring-boot spring-rest

我想使用Spring实现API的Rest日志。我尝试过:

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))
  }

但是我得到的请求和响应为NULL。 您知道从请求和响应中获取有效负载的正确方法是什么吗?

2 个答案:

答案 0 :(得分:2)

因此,您只需要拥有自己的拦截器即可。

@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");
    }
}

}

完成后,您需要将新的拦截器绑定到现有的拦截器。

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

@Autowired
private HttpRequestResponseLoggingInterceptorAdapter httpRequestResponseLoggingInterceptorAdapter;

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

}

完成后,您对handlemessage方法的传入请求将被拦截,并且可以执行您希望进行的任何前/后处理。 在这种情况下登录。

让我知道这是否有帮助。

答案 1 :(得分:0)

像用例这样的声音最适合用于扩展spring的org.springframework.web.servlet.handler.HandlerInterceptorAdapter的类。

自定义拦截器可以覆盖preHandle和postHandle-听起来好像您都倾向于使用。

编辑:

// 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>