如何记录Spring 5 WebClient调用 [英] how to log Spring 5 WebClient call

查看:669
本文介绍了如何记录Spring 5 WebClient调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Spring 5 WebClient记录请求。你有什么想法我能做到吗?

I'm trying to log a request using Spring 5 WebClient. Do you have any idea how could I achieve that?

(我正在使用Spring 5和Spring启动2)

(I'm using Spring 5 and Spring boot 2)

此代码现在看起来像这样:

The code looks like this at the moment:

try {
    return webClient.get().uri(url, urlParams).exchange().flatMap(response -> response.bodyToMono(Test.class))
            .map(test -> xxx.set(test));
} catch (RestClientException e) {
    log.error("Cannot get counter from opus", e);
    throw e;
}


推荐答案

您可以轻松地使用它 ExchangeFilterFunction

在创建 WebClient <时,只需添加自定义 logRequest 过滤器/ code>使用 WebClient.Builder

Just add the custom logRequest filter when you create your WebClient using WebClient.Builder.

以下是此类过滤器的示例以及如何添加它到 WebClient

Here is the example of such filter and how to add it to the WebClient.

@Slf4j
@Component
public class MyClient {

    private final WebClient webClient;

    // Create WebClient instance using builder.
    // If you use spring-boot 2.0, the builder will be autoconfigured for you
    // with the "prototype" scope, meaning each injection point will receive
    // a newly cloned instance of the builder.
    public MyClient(WebClient.Builder webClientBuilder) {
        webClient = webClientBuilder // you can also just use WebClient.builder()
                .baseUrl("https://httpbin.org")
                .filter(logRequest()) // here is the magic
                .build();
    }

    // Just example of sending request
    public void send(String path) {
        ClientResponse clientResponse = webClient
                .get().uri(uriBuilder -> uriBuilder.path(path)
                        .queryParam("param", "value")
                        .build())
                .exchange()
                .block();
        log.info("Response: {}", clientResponse.toEntity(String.class).block());
    }

    // This method returns filter function which will log request data
    private static ExchangeFilterFunction logRequest() {
        return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
            log.info("Request: {} {}", clientRequest.method(), clientRequest.url());
            clientRequest.headers().forEach((name, values) -> values.forEach(value -> log.info("{}={}", name, value)));
            return Mono.just(clientRequest);
        });
    }

}

然后只需致电 myClient.send(get); 并且日志消息应该在那里。

Then just call myClient.send("get"); and log messages should be there.

输出示例:

Request: GET https://httpbin.org/get?param=value
header1=value1
header2=value2

这篇关于如何记录Spring 5 WebClient调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆