简体   繁体   中英

Spring Webflux, log response body from reactive http request only in debug mode

Small question regarding how to log response body from HTTP request sent from a Webflux Webclient, but only in debug mode please.

Currently, in the app, I am making reactive http outbound calls this way:

webClient.mutate()
         .baseUrl(someURL)
         .build()
         .post()
         .uri(someRoute)
         .body(BodyInserters.fromValue(myRequest))
         .retrieve()
         .bodyToMono(String.class);

This is working fine. However, sometimes, there are issues, and I would like to see the response body for debugging.

Therefore, I took the wrong decision to use.log()

webClient.mutate()
         .baseUrl(someURL)
         .build()
         .post()
         .uri(someRoute)
         .body(BodyInserters.fromValue(myRequest))
         .retrieve()
         .bodyToMono(String.class)
         .log();

And this is great, I was able to see some logs, it resemble to something like this:

[ctor-http-nio-3] reactor.Mono.LiftFuseable.1              : | onSubscribe([Fuseable] ScopePassingSpanSubscriber)
[ctor-http-nio-3] reactor.Mono.LiftFuseable.1              : | request(unbounded)
[ctor-http-nio-3] reactor.Mono.LiftFuseable.1              : | onNext({foo='bar'})
[ctor-http-nio-3] reactor.Mono.LiftFuseable.1              : | onComplete()

However, I am now logging this no matter the log level...

No matter the level I set using logging.level.root=DEBUG I am always seeing the logs now.

May I ask how to achieve this, but for debug log level only please? I am looking at the API, and it seems.log() can take parameter, but I am not able to make it work only for debug.

Or maybe some other ways to achieve logging response body only at debug level would be great.

Thank you

You can conditionally tack on the log() based on logging level (or some other profile/environment indicator).


Mono<String> makeCall(final WebClient webClient, final ?? myRequest) { 
   final Mono<String> response = webClient.mutate()
                                          .baseUrl(someURL)
                                          .build()
                                          .post()
                                          .uri(someRoute)
                                          .body(BodyInserters.fromValue(myRequest))
                                          .retrieve()
                                          .bodyToMono(String.class);

    if (LOG.isDebugEnabled()) {
        return response.log();
    }
    return response;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM