title: How to log all the request-responses in spring rest?
body: <p>The application should log the following information without impacting a client, asynchronously(in a separate thread).</p>
  
  <ul>
  <li>Request HTTP Method and URI</li>
  <li>Request Headers (Except the default)</li>
  <li>Client's IP Address</li>
  <li>Request Processing Time(In milliseconds)</li>
  <li>Request Body</li>
  <li>Response Body</li>
  </ul>
  
  <p>If we consume <code>inputstream</code> in the filter, then it cant be consumed again by spring for json to object mapping. Somewhere during the input stream to object mapping, can we plug our logger?</p>
  
  <p><strong>Update:</strong></p>
  
  <p>We can write over logging code in a <a href="https://gist.github.com/TheNilesh/9c7f3ab13ab0511c144e33e63672b08c" rel="noreferrer">MessageConverter</a>, but it doesnt seems to be a good idea.</p>
  
  <pre><code>public class MyMappingJackson2MessageConverter extends AbstractHttpMessageConverter&lt;Object&gt; {
      ...
      protected Object readInternal(Class&lt;? extends Object&gt; clazz, HttpInputMessage inputMessage)
              throws IOException, HttpMessageNotReadableException {
          InputStream inputStream = inputMessage.getBody();
          String requestBody = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
          String method = request.getMethod();
          String uri = request.getRequestURI();
          LOGGER.debug("{} {}", method, uri);
          LOGGER.debug("{}", requestBody);
          return objectMapper.readValue(requestBody, clazz);
      }
  
      protected void writeInternal(Object o, HttpOutputMessage outputMessage)
              throws IOException, HttpMessageNotWritableException {
          String responseBody = objectMapper.writeValueAsString(o);
          LOGGER.debug("{}", responseBody);
          outputMessage.getBody().write(responseBody.getBytes(StandardCharsets.UTF_8));
      }
  }
  </code></pre>