title: Spring Boot 2 Actuator (2.0.1-RELEASE) - Request and Response body
body: <p>Followed the post <a href="https://stackoverflow.com/questions/35848802/how-to-include-json-response-body-in-spring-boot-actuators-trace">post</a> to create a filter to get the request and response bodies.</p>
  
  <p>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.</p>
  
  <p>Any help much appreciated!</p>
  
  <pre><code>@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 &gt; 0) {
          try {
              payload = new String(buf, 0, buf.length, characterEncoding);
          }
          catch (UnsupportedEncodingException ex) {
              payload = "[unknown]";
          }
      }
      return payload;
  }
  </code></pre>
  
  <p>}</p>