如何为 Spring Boot WebClient 请求启用日志记录

问题描述 投票:0回答:1

在我的 Spring Boot 项目中,我利用 WebClient 与外部 API 进行通信。我需要深入了解客户发送的确切请求。在寻求建议后,建议的解决方案涉及配置日志记录:


import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;

@Service
public class WebnamesWebClientService {

    private final WebClient webClient;
    
    public WebnamesWebClientService() {
        final HttpClient httpClient = HttpClient.create()
                .wiretap(true);
        this.webClient = WebClient.builder()
        //The line below doesn't work because of ReactorClientHttpConnector class not found
                .clientConnector(new ReactorClientHttpConnector(httpClient)) 
                .build();
    }
    
    public String sendRequest(String requestData) {
        // Your request logic using the WebClient instance
    }

}

但是,我遇到了障碍,因为 ReactorClientHttpConnector 类在指定的包中不可用。以下是所使用的软件包的版本:

  • org.springframework:spring-webflux:5.0.9.RELEASE
  • io.projectreactor.netty:reactor-netty:0.8.11.RELEASE

如何修复此代码或是否有其他方法来启用日志记录?

在尝试为 WebClient 请求启用日志记录时,我按照建议将 ReactorClientHttpConnector 与配置为启用窃听的自定义 HttpClient 结合使用。我预计此设置将允许我记录 WebClient 发送的请求。但是,在实现提供的解决方案时,我遇到了一个错误,表明未找到 ReactorClientHttpConnector 类。这是出乎意料的,因为我验证了我的项目中包含必要的依赖项。结果,我无法按照预期启用日志记录。

java spring-boot logging spring-webflux reactor-netty
1个回答
0
投票

您缺少的类位于 spring-web 库中。添加此依赖项或(更好)使用启动器依赖项

spring-boot-starter-webflux
来代替。这将以正确的版本加载所有相关的依赖项。就连
reactor-netty
.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
© www.soinside.com 2019 - 2024. All rights reserved.