Home > Net >  how to log pipelines in Java project reactor?
how to log pipelines in Java project reactor?

Time:01-28

I have started a new project that uses java reactor and spring webFLux. Recently I had to debug a production bug and It was a nightmare since they do not log anything. So, reading I found two ways to start adding logs to pipelines. One by using .log() and another one by using one rrorResume, doOnSubscribe, doOnSuccess. Do you know which one should I use? Are better ways to log pipelines?

    return repositoryName.findById(event.eventId())
        .filter(event -> event.completedDate() == null)
        .filterWhen(event ->
            externalService.getEventSummary(event.getUser().userId())
        .doOnNext(event -> log.info("Event found {} and should be marked as found", event.id()))

CodePudding user response:

I highly recommend the Reactor doc to check what each method does https://projectreactor.io/docs/core/release/reference/

doOnNext, doOnError, doOnSuccess are highly used to execute blocking operations without side effects on the current stream. If you received a Square object on your doOnNext and doOnError, this method would return precisely the received Square object (even if you changed its properties)

doOnNext to execute after the previous sequence finishes try-catch

doOnError the subsequent execution if an exception was thrown (and there's no other exception handler on stream)

doOnSuccess is similar to a finally block from try-catch

onErrorResume is most used to handle exceptions if needed, similar to catch(Exception e), but it will return a new object

As you can see, it's okay to have logs on flatMap, map, doOnNext, doOnError, or onErrorResume. The correct one to use will vary on what you need. If logging is the only thing you need, I recommend doOnNext, doOnError, or doOnFinally.

As said before, please refer to the docs too to check what each method stands for

  • Related