Below is the Interceptor code for logging request and response when doing Async Rest Call from Spring's AsyncRestTemplate
.
This code is working provided we can use BufferingClientHttpResponseWrapper
in some other package.
Here are some details about BufferingClientHttpResponseWrapper
and how to add it with AsyncRestTemplate.
My Question is when I am using HttpComponentsAsyncClientHttpRequestFactory
in my AsyncRestTemplate. How I can get the Buffered Response. We CAN NOT use BufferingClientHttpResponseWrapper
as show below in my code as it is not a public class. Is there any other way to do it?
I know there are wire log available for HttpComponent AsyncHttpClient. But it will have all the logs from all the AsyncResttemplates in whole application. If we want to capture the logs only for one template then Interceptor is the only way I think. Please suggest if there is any other option available.
public class AsyncRestReqResInterceptor implements AsyncClientHttpRequestInterceptor {
private static final XLogger REQ_RES_LOGGER = XLoggerFactory.getXLogger("myLogger");
@Override
public ListenableFuture<ClientHttpResponse> intercept(HttpRequest request, byte[] body, AsyncClientHttpRequestExecution execution) throws IOException {
String requestPath = request.getURI().getPath();
REQ_RES_LOGGER.debug(request.getMethod()+" "+requestPath);
String requestBody = new String(body);
REQ_RES_LOGGER.debug(requestBody);
ListenableFuture<ClientHttpResponse> listenableFuture = execution.executeAsync(request, body);
ListenableFutureAdapter<ClientHttpResponse,ClientHttpResponse> futureAdapter=
new ListenableFutureAdapter<ClientHttpResponse, ClientHttpResponse>(listenableFuture) {
@Override
protected ClientHttpResponse adapt(ClientHttpResponse adapteeResult) throws ExecutionException {
return logResponseBody(adapteeResult);
}
};
return futureAdapter;
}
private ClientHttpResponse logResponseBody(ClientHttpResponse response,boolean isImageInResponse){
try {
BufferingClientHttpResponseWrapper responseWrapper = new BufferingClientHttpResponseWrapper(response);
REQ_RES_LOGGER.debug("Response Status Code :" + responseWrapper.getStatusCode().value());
REQ_RES_LOGGER.debug("Response Status Text :" + responseWrapper.getStatusText());
if (response != null && response.getBody() != null) {
String responseXml = IOUtils.toString(responseWrapper.getBody(), Charset.defaultCharset());
REQ_RES_LOGGER.debug(responseXml);
} else {
REQ_RES_LOGGER.debug("Empty Response Body");
}
return responseWrapper;
}catch (IOException io){
REQ_RES_LOGGER.error("Unexpected Error ",io);
return response;
}
}
}