Home > Back-end >  Spring WebClient - logging is2xxSuccessful HTTPStatus
Spring WebClient - logging is2xxSuccessful HTTPStatus

Time:10-14

I am downloading files using Spring WebClient like below:

private void dnloadFileAPI(String theId, String destination) {
        log.info("Downloading file.. "   theId);
        Flux<DataBuffer> dataBuffer = webClient
                .get()
                .uri("/some/fancy/"   theId   "/api")
                .retrieve()
                .onStatus(HttpStatus::is2xxSuccessful, response -> Mono.just(new CustomException("Success")))
                .bodyToFlux(DataBuffer.class);
        DataBufferUtils.write(dataBuffer, Paths.get(destination), StandardOpenOption.CREATE).share().block();
    }

File(s) get downloaded fine. The only piece I am struggling is, when the response is 200, I just want to log one line like this:

log.info("{}", theId   " - File downloaded successfully")

I tried this too but didnt get what I am looking for - How to log Spring WebClient response

In short, is there some way above can be achieved without writing a separate CustomException ? Feeling lost and clueless here. Any pointers in this regard will be highly appreciated.

CodePudding user response:

I think adding the following after the bodyToFlux(DataBuffer.class) line will be what you need

.doOnComplete(() -> log.info("File downloaded successfully"))

Something like this

private void dnloadFileAPI(String theId, String destination) {
    log.info("Downloading file.. "   theId);
    Flux<DataBuffer> dataBuffer = webClient
        .get()
        .uri("/some/fancy/"   theId   "/api")
        .retrieve()
        .bodyToFlux(DataBuffer.class)
        .doOnComplete(() -> log.info("File downloaded successfully"));
    DataBufferUtils.write(dataBuffer, Paths.get(destination), StandardOpenOption.CREATE).share().block();
}
  • Related