【Spring】RestTemplateを使う際、リクエストとレスポンスの詳細ログを取得したい

java

 RestTemplateを使って外部APIを呼び出しする際、たまにリクエストとレスポンスの詳細を見たい場面があるでしょか?RestTemplateのログレベルをDebugに設定したら、より詳細の情報をログに出せますが、情報が足りないやカスタマイズできないなどやはり不便です。
 ClientHttpRequestInterceptorを使ってリクエストのタイミングで処理を差し込む方法を使えば、ほぼ自由に通信ログをカスタマイズできます。

ClientHttpRequestInterceptorを実装する
package test.common.interceptor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {

    final static Logger logger = LogManager.getLogger();

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        traceRequest(request, body);    //リクエストの詳細を取得
        ClientHttpResponse response = execution.execute(request, body);
        traceResponse(response);    //レスポンスの詳細を取得
        return response;
    }

    private void traceRequest(HttpRequest request, byte[] body) throws IOException {
    	logger.info("===========================request begin================================================");
    	logger.info("URI         : {}", request.getURI());
    	logger.info("Method      : {}", request.getMethod());
    	logger.info("Headers     : {}", request.getHeaders() );
    	logger.info("Request body: {}", new String(body, "UTF-8"));
    	logger.info("==========================request end================================================");
    }

    private void traceResponse(ClientHttpResponse response) throws IOException {
        StringBuilder inputStringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8"));
        String line = bufferedReader.readLine();
        while (line != null) {
            inputStringBuilder.append(line);
            inputStringBuilder.append('\n');
            line = bufferedReader.readLine();
        }
        logger.info("============================response begin==========================================");
        logger.info("Status code  : {}", response.getStatusCode());
        logger.info("Status text  : {}", response.getStatusText());
        logger.info("Headers      : {}", response.getHeaders());
        logger.info("Response body: {}", inputStringBuilder.toString());
        logger.info("=======================response end=================================================");
    }

}
RestTemplate側の設定
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new LoggingRequestInterceptor());
restTemplate.setInterceptors(interceptors);

restTemplate.exchange(……);    //通常通りにrestTemplate処理を実行する
実際のログ
13:06:17.931 [ajp-nio-127.0.0.1-8009-exec-8] INFO  com.test.common.interceptor.LoggingRequestInterceptor - ===========================request begin================================================
13:06:17.931 [ajp-nio-127.0.0.1-8009-exec-8] INFO  com.test.common.interceptor.LoggingRequestInterceptor - URI         : https://XXXXXXXXXXXX
13:06:17.931 [ajp-nio-127.0.0.1-8009-exec-8] INFO  com.test.common.interceptor.LoggingRequestInterceptor - Method      : GET
13:06:17.932 [ajp-nio-127.0.0.1-8009-exec-8] INFO  com.test.common.interceptor.LoggingRequestInterceptor - Headers     : {Accept=[application/json, application/*+json], Authorization=[BASIC YYYYYYYYYYYYYYYYYYY], Content-Length=[0]}
13:06:17.932 [ajp-nio-127.0.0.1-8009-exec-8] INFO  com.test.common.interceptor.LoggingRequestInterceptor - Request body:
13:06:17.932 [ajp-nio-127.0.0.1-8009-exec-8] INFO  com.test.common.interceptor.LoggingRequestInterceptor - ==========================request end================================================
13:06:18.131 [ajp-nio-127.0.0.1-8009-exec-8] INFO  com.test.common.interceptor.LoggingRequestInterceptor - ============================response begin==========================================
13:06:18.131 [ajp-nio-127.0.0.1-8009-exec-8] INFO  com.test.common.interceptor.LoggingRequestInterceptor - Status code  : 200 OK
13:06:18.131 [ajp-nio-127.0.0.1-8009-exec-8] INFO  com.test.common.interceptor.LoggingRequestInterceptor - Status text  : OK
13:06:18.131 [ajp-nio-127.0.0.1-8009-exec-8] INFO  com.test.common.interceptor.LoggingRequestInterceptor - Headers      : {Content-Type=[application/json;charset=UTF-8], Content-Length=[2613], Connection=[keep-alive], Date=[Tue, 25 Jan 2022 04:06:18 GMT], Server=[Apache], X-Track=[aef3f89b], Cache-Control=[no-store], Vary=[Accept-Encoding,Origin], X-Cache=[Miss from cloudfront], Via=[1.1 XXXXXXXX.cloudfront.net (CloudFront)], X-Amz-Cf-Pop=[XXXXXX-XX], X-Amz-Cf-Id=[YYYYYYY]}
13:06:18.132 [ajp-nio-127.0.0.1-8009-exec-8] INFO  com.test.common.interceptor.LoggingRequestInterceptor - Response body: XXXXXXXX(省略)
13:06:18.132 [ajp-nio-127.0.0.1-8009-exec-8] INFO  com.test.common.interceptor.LoggingRequestInterceptor - =======================response end=================================================
終わり

 上記の例はログ用途で使いますが、ログに限らず任意の処理が差し込み可能なので、非常に強力な武器になれます。

コメント

タイトルとURLをコピーしました