Home > Java > javaTutorial > body text

How to Log Spring RestTemplate Requests and Responses for Effective Debugging?

Susan Sarandon
Release: 2024-11-19 01:51:02
Original
993 people have browsed it

How to Log Spring RestTemplate Requests and Responses for Effective Debugging?

Debugging Spring RestTemplate Requests and Responses: A Comprehensive Guide

When debugging a Spring RestTemplate, inspecting the requests and responses can provide invaluable insights. To replicate the verbose output of the curl command with the "-v" option, we need to enable detailed logging or debugging for the RestTemplate.

One approach involves modifying the RestTemplate's source code to include additional logging statements, but this is not recommended as a primary solution. Instead, we can leverage the power of ClientHttpRequestInterceptor.

Custom ClientHttpRequestInterceptor for Request/Response Logging

To log both request and response details, we can implement a custom ClientHttpRequestInterceptor:

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=================================================");
    }

}
Copy after login

RestTemplate Configuration with Buffering and Interceptor

To use our custom interceptor, configure the RestTemplate as follows:

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

Note that the BufferingClientHttpRequestFactory is necessary to allow the interceptor to access the response body multiple times.

Usage and Expected Output

With this configuration in place, calling restTemplate.execute() will log the request and response details in the desired format:

restTemplate.put("http://someurl", objectToPut, urlPathValues);
Copy after login

And you will see the following in the log:

===========================request begin===============================================
URI         : http://someurl
Method      : PUT
Headers     : {...}
Request body: {...}
==========================request end===============================================

============================response begin==========================================
Status code  : 200
Status text  : OK
Headers      : {...}
Response body: {...}
=======================response end=================================================
Copy after login

This detailed logging provides a comprehensive view of the RestTemplate's interactions, making debugging significantly more efficient and convenient. By avoiding code modifications and leveraging the provided extensibility mechanisms, this approach offers a clean and flexible solution to this common debugging challenge.

The above is the detailed content of How to Log Spring RestTemplate Requests and Responses for Effective Debugging?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template