I'm using spring
with RestTemplate
to execute GET
queries.
How can I log any request and response data to a logfile automatically on each request?
You can achieve this by using ClientHttpRequestInterceptor in Spring. You have to override method intercept of interface ClientHttpRequestInterceptor.
Below is the code snippet :
@Component
public class LogRequestResponseFilter implements ClientHttpRequestInterceptor {
private static final Logger logger=LoggerFactory.getLogger(LogRequestResponseFilter.class);
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
traceRequest(request, body);
ClientHttpResponse clientHttpResponse = execution.execute(request, body);
traceResponse(clientHttpResponse);
return clientHttpResponse;
}
private void traceRequest(HttpRequest request, byte[] body) throws IOException {
logger.debug("request URI : " + request.getURI());
logger.debug("request method : " + request.getMethod());
logger.debug("request body : " + getRequestBody(body));
}
private String getRequestBody(byte[] body) throws UnsupportedEncodingException {
if (body != null && body.length > 0) {
return (new String(body, "UTF-8"));
} else {
return null;
}
}
private void traceResponse(ClientHttpResponse response) throws IOException {
String body = getBodyString(response);
logger.debug("response status code: " + response.getStatusCode());
logger.debug("response status text: " + response.getStatusText());
logger.debug("response body : " + body);
}
private String getBodyString(ClientHttpResponse response) {
try {
if (response != null && response.getBody() != null) {// &&
// isReadableResponse(response))
// {
StringBuilder inputStringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), StandardCharsets.UTF_8));
String line = bufferedReader.readLine();
while (line != null) {
inputStringBuilder.append(line);
inputStringBuilder.append('\n');
line = bufferedReader.readLine();
}
return inputStringBuilder.toString();
} else {
return null;
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
return null;
}
}