Followed the post post to create a filter to get the request and response bodies.
Spring Boot 2 filter (HttpTraceFilter) appears to be a bit different so not sure how to set the http trace properties from the request attributes.
Any help much appreciated!
@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;
}
}