Our goal here is to implement the logging functionality for all requests and responses performed by RestTemplate client. We want to log everything - the http method, url, http headers, payloads and response code.

Create LoggingInterceptor

First we’ll need to create the LoggingInterceptor class which is the implementation of the ClientHttpRequestInterceptor

public class LoggingInterceptor implements ClientHttpRequestInterceptor {

  private static final MyLogger = ...;

  @Override
  public ClientHttpResponse intercept(HttpRequest request, byte[] requestBody, ClientHttpRequestExecution execution) throws IOException{
    MyLogger.info(request.getMethod().name() + " " + request.getURI().toString());
    MyLogger.info("Request Headers: {}", request.getHeaders());
    MyLogger.info("Request Payload: {}", new String(requestBody. UTF_8));

    ClientHttpResponse response = execution.execute(request, requestBody);

    MyLogger.info("Response Code: {}". response.getStatusCode().value());
    MyLogger.info("Response Headers: {}", response.getHeaders());

    InputStreamReader reader = new InputStreamReader(response.getBody(), UTF_8);
    String responsePayload = new BufferedReader(reader).lines().collect(Collectors.joining("\n"));
    MyLogger.info("Response Payload: {}", responseBody);

    return response;
  }
}

Add LoggingInterceptor to RestTemplate

Now we include LoggingInterceptor to the list of interceptors of RestTemplate’s instance.

restTemplate.getInterceptors();
if (interceptors == null) {
  interceptors = new ArrayList<>();
}
interceptors.add(new LoggingInterceptor());
restTemplate.setInterceptors(new LoggingInterceptors());

Now every request that you send and response that you receive using that RestTemplate instance will be logged.


You may also find these posts interesting: