Java 如何使用 spring 记录 RestTemplate 请求和响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31474006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to log RestTemplate request and response with spring?
提问by membersound
I'm using spring
with RestTemplate
to execute GET
queries.
我正在使用spring
withRestTemplate
来执行GET
查询。
How can I log any request and response data to a logfile automatically on each request?
如何在每个请求中自动将任何请求和响应数据记录到日志文件中?
回答by S Boot
You can achieve this by using ClientHttpRequestInterceptorin Spring. You have to override method interceptof interface ClientHttpRequestInterceptor.
您可以通过在 Spring 中使用ClientHttpRequestInterceptor来实现这一点。您必须覆盖接口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;
}
}