Logging Spring REST template requests

5+

Spring Framework is a powerful must-have tool for any Java developer. Spring offers a convenient template to consume REST resources. One day I encountered problem in our production environment and realized that I need some mechanism to log exactly what requests SpringTemplate sends to REST endpoints. In this post we’ll deal with logging Spring REST template requests.

Fortunately, since Spring 3.1 it’s available through writing your own interceptor which implements  ClientHttpRequestInterceptor and override it’s intercept method.

Writing custom ClientHttpRequestInterceptor

In this method you can get all info you need about the request was sent (http method, headers, URI, body) and response received (status code, headers, body).

Here we use public static byte[] toByteArray(InputStream in) method from Guava library to read all bytes to byte array, but if you’re using Java 9 you can do it without additional libraries by using public byte[] readAllBytes() throws IOException.

I’m using Logback here for logging.

Now you have to set your new interceptor when constructing RestTemplate:

There are few things to notice:

  • When constructing template you should wrap your request factory with BufferingClientHttpRequestFactory. In this case I’m using default SimpleClientHttpRequestFactory. Otherwise response body will be null after you read all bytes from InputStream.
  • If you have other interceptors set and some of them are modifying request parameters , your logging interceptor should be the last one in chain.

Finally you can create helper method to instantiate template this way:

5+