首頁 >Java >java教程 >如何使用 Spring RestTemplate 為請求和回應啟用詳盡的偵錯日誌記錄?

如何使用 Spring RestTemplate 為請求和回應啟用詳盡的偵錯日誌記錄?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-11-23 02:43:14249瀏覽

How to Enable Exhaustive Debugging Logging for Requests and Responses using Spring RestTemplate?

如何使用Spring RestTemplate 為請求和回應啟用詳盡的調試日誌記錄

問題

使用Spring RestTemplate 請求時具有偵錯請求和回應挑戰性,因為它缺乏詳細的日誌記錄資訊。與curl的詳細模式類似,您可能需要深入了解發送和接收的數據,包括標頭和cookie。

解決方案

您可以使用自訂的ClientHttpRequestInterceptor來取代修改RestTemplate原始碼攔截並記錄請求和回應資料。這是一個完整的範例:

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 log = LoggerFactory.getLogger(LoggingRequestInterceptor.class);

    @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 {
        log.info("===========================request begin================================================");
        log.debug("URI         : {}", request.getURI());
        log.debug("Method      : {}", request.getMethod());
        log.debug("Headers     : {}", request.getHeaders() );
        log.debug("Request body: {}", new String(body, "UTF-8"));
        log.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();
        }
        log.info("============================response begin==========================================");
        log.debug("Status code  : {}", response.getStatusCode());
        log.debug("Status text  : {}", response.getStatusText());
        log.debug("Headers      : {}", response.getHeaders());
        log.debug("Response body: {}", inputStringBuilder.toString());
        log.info("=======================response end=================================================");
    }

}

要使用此攔截器,請使用BufferingClientHttpRequestFactory 實例化RestTemplate 並註冊LoggingRequestInterceptor:

RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new LoggingRequestInterceptor());
restTemplate.setInterceptors(interceptors);

此解決方案提供了一種自自認為定義且方便的方法來捕獲和記錄記錄請求和響應詳細信息,幫助使用Spring 進行故障排除和調試RESTful Web 服務通訊休息範本。

以上是如何使用 Spring RestTemplate 為請求和回應啟用詳盡的偵錯日誌記錄?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn