Search code examples
javareactive-programmingproject-reactormdc

Operators#lift: good idea for MDC logging?


Project Reactor documentation suggests the following pattern for MDC logging:

.doOnEach(logOnNext(r -> LOG.debug("found restaurant {} for ${}", r.getName(), r.getPricePerPerson())))

To avoid having to wrap each logging call, would a custom subscriber, populating the MDC from the currentContext before each signal, added using Hooks.onEachOperator(Operators.lift(...)) be a good idea?

My main conerns are:

1.) The cost of populating the MDC before every signal, even if there is no logging happening.

2.) Operator fusion: Does Operators.lift(...) on each operator effectively disable operator fusion? Attempting a quick test with StepVerifier#expectFusion seems to indicate that. If this is true, how much of a performance hit is this, in practice?

Any input is appreciated!


Solution

  • This is the approach that was initially taken by Sleuth, via Hooks.onEachOperator. However, this is very costly and probably not worth it if you only need logging/MDC on a subset of operations in you reactive pipeline. Not to mention that this approach not only impacts reactive steps defined by you, but also any other library / framework.

    The recommendation is there for a reason: better control, less impact and a more explicit approach.