Spring Boot 2 Actuator(2.0.1-RELEASE) - 请求和响应正文

时间:2018-04-24 00:29:16

标签: spring-boot spring-boot-actuator

按照帖子post创建过滤器以获取请求和响应正文。

Spring Boot 2过滤器(HttpTraceFilter)似乎有点不同,因此不确定如何从请求属性设置http跟踪属性。

非常感谢任何帮助!

@Component
public class RequestTraceFilter extends HttpTraceFilter {

/**
 * Create a new {@link HttpTraceFilter} instance.
 *
 * @param repository the trace repository
 * @param tracer     used to trace exchanges
 */
public RequestTraceFilter(HttpTraceRepository repository,
        HttpExchangeTracer tracer) {
    super(repository, tracer);
}

//TODO override the filter :(
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws
        ServletException,
        IOException {

    ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
    ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);

    filterChain.doFilter(requestWrapper, responseWrapper);
    responseWrapper.copyBodyToResponse();
    request.setAttribute("REQUEST_BODY", getRequestBody(requestWrapper));
    request.setAttribute("RESPONSE_BODY", getResponseBody(responseWrapper));

    super.doFilterInternal(requestWrapper, responseWrapper, filterChain);

}

private String getRequestBody(ContentCachingRequestWrapper request) {
    ContentCachingRequestWrapper wrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class);
    String characterEncoding = wrapper.getCharacterEncoding();
    return getPayload(wrapper.getContentAsByteArray(), characterEncoding);
}

private String getResponseBody(ContentCachingResponseWrapper response) {
    ContentCachingResponseWrapper wrapper = WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
    return getPayload(wrapper.getContentAsByteArray(), wrapper.getCharacterEncoding());
}

public String getPayload(byte[] buf, String characterEncoding) {
    String payload = null;
    if (buf.length > 0) {
        try {
            payload = new String(buf, 0, buf.length, characterEncoding);
        }
        catch (UnsupportedEncodingException ex) {
            payload = "[unknown]";
        }
    }
    return payload;
}

}

2 个答案:

答案 0 :(得分:2)

在wilkinsona的github收到回复:

https://github.com/spring-projects/spring-boot/issues/12953

2.0中的HTTP跟踪故意不如1.5中的灵活性。 1.5中实现的灵活性引起了许多问题,并且无法在WebFlux,Spring MVC和Jersey之上提供支持。跟踪请求和响应正文从未得到过支持。删除了对跟踪参数的支持,因为当请求POST表单数据时,它需要读取整个请求主体。如果你想捕获其中一个或两个,我建议你不要,你应该实现自己的端点。

答案 1 :(得分:0)

使用webflux反​​应堆,可以使用spring-cloud-gateway捕获http请求和响应正文,并通过定义自定义HttpTraceWebFilter将它们注入到执行器httptrace中。

https://gist.github.com/gberche-orange/06c26477a313df9d19d20a4e115f079f上查看完整的关联代码

这需要很多重复,希望springboot团队会减少重复,请参见相关的https://github.com/spring-projects/spring-boot/issues/23907

ps:此答案重复了https://stackoverflow.com/a/64538270/1484823,请随时删除