tokuhirom's blog

RxJava で無理やり MDC を使うライフハック

import java.util.Map;

import org.slf4j.MDC;

import rx.functions.Action0;
import rx.functions.Func1;

/**
 * Propagate MDC contexts between Observables
 */
public class MdcPropagator implements Func1<Action0, Action0> {
    @Override
    public Action0 call(Action0 original) {
        Map<String, String> context = MDC.getCopyOfContextMap();
        return () -> {
            final Map<String, String> originalMdc = MDC.getCopyOfContextMap();

            if (context != null) {
                MDC.setContextMap(context);
            }

            try {
                original.call();
            } finally {
                if (originalMdc != null) {
                    MDC.setContextMap(originalMdc);
                }
            }
        };
    }
}
Created: 2016-11-25 07:37:58 +0000
Updated: 2016-11-25 07:37:58 +0000