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: {}", responsePayload);
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.
Resolve Empty Reponse Issue
The response stream can be read only once. The interceptor reads the response stream first. Next attempts to access the response body will get an empty body. So we have to buffer the stream content into memory. In order to do that we change the way we instantiate RestTemplate.
This is how
RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
You may also find these posts interesting: