【问题标题】:How to log only POST ant PATCH request from WebClient如何仅记录来自 WebClient 的 POST ant PATCH 请求
【发布时间】:2021-07-15 13:54:15
【问题描述】:

我正在注册过滤器以记录来自 WebClient 的响应,但我只想记录 POST 和 PATCH 请求(没有大量我不感兴趣的 GET 请求)。如何只记录特定的 POST 和 PATCH 响应?

WebClient bean:

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

logResponse 过滤器:

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

【问题讨论】:

    标签: java spring-boot rest logging webclient


    【解决方案1】:

    我认为您可以像这样实现自己的 ExchangeFilterFunction:

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

    【讨论】:

    • 很好,但是请将return Mono.just(response)改为return response。语句next.exhange(request) 已经返回Mono<T>,所以你的整个过滤函数将返回Mono<Mono<ClientResponse>>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2021-07-21
    • 2015-05-21
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多