簡體   English   中英

在 Spring API 中記錄請求和響應

[英]Log Request and response in Spring API

我想使用 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。 您知道從請求和響應中獲取有效負載的正確方法是什么嗎?

所以你只需要擁有自己的攔截器。

@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 方法的傳入請求將被攔截,並且可以執行您想要的任何前/后處理。 在這種情況下記錄。

如果這有幫助,請告訴我。

聽起來您的用例最適合擴展 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM