Home » Java » java – How to log a response body in Spring Webflux WebClient?-Exceptionshub

java – How to log a response body in Spring Webflux WebClient?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I need to write the http response data to a log. I have Spring Webflux WebClient which sends the requests.
I know how to log a response status code and headers, but I did not find a solution to access the plain body response data to put them to log too.

How to make Spring Webflux WebClient write the body of an http response to the log?

Here is what my WebClient looks like:

public class CmsClient {

  private static final Logger logger = LoggerFactory.getLogger(CmsClient.class);

  private WebClient createWebClient() {
    return WebClient.builder()
        .clientConnector(
            new ReactorClientHttpConnector(HttpClient.create()))
        .baseUrl(cmsProperties.getBasePath())
        .filter(logResponse())
        .build();
  }

  private static ExchangeFilterFunction logResponse() {
    return ExchangeFilterFunction.ofResponseProcessor(
        response -> {
          logger.debug(
              "Response status code: {}, Headers: {}.",
              response.statusCode(),
              response.headers().asHttpHeaders());
          return Mono.just(response);
        });
  }
}

I write the status and headers with the help of logResponse() method calling
it in WebClient via .filter(logResponse()). The status and the headers are simply available in response, but body is returned only in the reactive form. How to decode this reactive form to a string representation to log it nicely?

How to&Answers: