Propagate slf4j MDC (mapped diagnostic context) in rxjava Observables

Viewed 1396

I'm using rxjava observables (v 1.1.8) in my play framework (with akka) application. I'd like to know if there's a way to propagate MDC info to rxjava Observables. I don't see MDC info in my log statements which get printed within Observable/Subscriber. I understand rxJava uses separate thread pool and there needs to be a mechanism to copy MDC info from akka threads into rxjava threads. Is there a solution for this ?

FYI,within akka actors I'm achieving MDC propagation using lightbends cinnamon plugin (http://developer.lightbend.com/docs/monitoring/latest/extensions/mdc.html)

2 Answers

Even though this thread is old and many would have migrated to RxJava2, but just in case someone wanted an implementation:

For RxJava1:

Source


//client class
public class DemoApplication {

  public static void main(String[] args) {
      MDCContextForSchedulerHook.init();
      // Above line should be before application run
      // rest of the code ....
  }

}


// WebHook class

import rx.functions.Action0;
import rx.plugins.RxJavaPlugins;
import rx.plugins.RxJavaSchedulersHook;

public class MDCContextForSchedulerHook extends RxJavaSchedulersHook {

    @Override
    public Action0 onSchedule(Action0 action) {
        return super.onSchedule(new WrappedAction0(action));
    }

    public static void init() {
        RxJavaPlugins.getInstance().registerSchedulersHook(new MDCContextSchedulerHook());
    }

    private static class WrappedAction0 implements Action0 {
        private final Action0 actual;
        private final MDCContext mdcContext;

        public WrappedAction0(Action0 actual) {
            this.actual = actual;
            this.mdcContext = MDCContext.save();
        }

        @Override
        public void call() {
            mdcContext.restore();
            actual.call();
        }
    }

}

For RXJava 2:

Refer this

Related