Using Spring boot actuator trace, I am trying to add trace with request & response body. I have followed the post How to include JSON response body in Spring Boot Actuator's Trace? and created a RequestTraceFilter class without using logback. But if I make a request, then I get an exception in console "Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing:"
Also, swagger-ui.html cannot load once I add this filter.
Did I miss something in the below class?
@Component
public class RequestTraceFilter extends WebRequestTraceFilter {
private static final String RESPONSE_BODY = "resBody";
private static final String REQUEST_BODY = "reqBody";
public RequestTraceFilter(TraceRepository repository, TraceProperties properties) {
super(repository, properties);
}
@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);
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);
}
@Override
protected Map<String, Object> getTrace(HttpServletRequest request) {
Map<String, Object> trace = super.getTrace(request);
Object requestBody = request.getAttribute(REQUEST_BODY);
Object responseBody = request.getAttribute(RESPONSE_BODY);
if(requestBody != null) {
trace.put(REQUEST_BODY, (String) requestBody);
}
if(responseBody != null) {
trace.put(RESPONSE_BODY, (String) responseBody);
}
return trace;
}
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;
}
private String getResponseBody(ContentCachingResponseWrapper response) {
ContentCachingResponseWrapper wrapper = WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
return getPayload(wrapper.getContentAsByteArray(), wrapper.getCharacterEncoding());
}
}