Search code examples
javaspring-bootrestloggingwebclient

How to log only POST ant PATCH request from WebClient


I'm registering the filter for logging the response from WebClient, but I would like to log only the POST and PATCH request (without plenty of GET requests on which I'm not interested in). How I can log only the specific POST and PATCH response?

The WebClient bean:

  @Bean
  public WebClient sfWebClient() {
    return WebClient.builder()
        .filter(logResponse())
        .build();
  }

The logResponse filter:

  ExchangeFilterFunction logResponse() {
    return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
      if (log.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder();
        sb.append("Request finished with the status: ").append(clientResponse.statusCode());
        log.debug(sb.toString());
      }
      return Mono.just(clientResponse);
    });
  }

Solution

  • I think you can implement your own ExchangeFilterFunction like this:

    WebClient.builder().filter((request, next) ->
            next.exchange(request).map(response -> {
                if ((request.method() == HttpMethod.POST || request.method() == HttpMethod.PATCH) && log.isDebugEnabled()) {
                    StringBuilder sb = new StringBuilder();
                    sb.append("Request finished with the status: ").append(response.statusCode());
                    log.debug(sb.toString());
                }
                return response;
            });
        );