Skip to content

Instantly share code, notes, and snippets.

@jei0486
Created January 10, 2023 02:13
Show Gist options
  • Save jei0486/7464ee9bd995857d1c30f04ffa42fbfc to your computer and use it in GitHub Desktop.
Save jei0486/7464ee9bd995857d1c30f04ffa42fbfc to your computer and use it in GitHub Desktop.
/**
Helper that copies the state of Reactor [Context] to MDC on the #onNext function.
*/
@Slf4j
@RequiredArgsConstructor
public class MdcContextLifter<T> implements CoreSubscriber<T> {
    private final CoreSubscriber<T> coreSubscriber;
    @Override
    public void onSubscribe(Subscription subscription) {
        coreSubscriber.onSubscribe(subscription);
    }
    @Override
    public void onNext(T t) {
        copyToMdc(coreSubscriber.currentContext());
        coreSubscriber.onNext(t);
    }
    @Override
    public void onError(Throwable throwable) {
        coreSubscriber.onError(throwable);
    }
    @Override
    public void onComplete() {
        coreSubscriber.onComplete();
    }
    @Override
    public Context currentContext() {
        return coreSubscriber.currentContext();
    }
    /**
     * Extension function for the Reactor [Context]. Copies the current context to the MDC, if context
     * is empty clears the MDC. State of the MDC after calling this method should be same as Reactor
     * [Context] state. One thread-local access only.
     */
    void copyToMdc(Context context) {
        if (context != null && !context.isEmpty()) {
            Map<String, String> map =
                    context.stream()
                            .collect(Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue().toString()));
            MDC.setContextMap(map);
        } else {
            MDC.clear();
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment