Setting ThreadContext for all threads in applicati

2019-07-14 19:46发布

问题:

From this answer https://stackoverflow.com/a/25125159/4367326 I have routingAppender working but I want to set the ThreadContext for every thread in the program.

When I set

ThreadContext.put("logFileName", "TestLogFile");

it works for the main thread and logs as expected but not for any other threads in my application. How can I achieve this?

回答1:

Every child thread will inherit fathers ThreadContext state if you set up system property isThreadContextMapInheritable to true. But this will not work for Executors so you need to manually copy data from one thread to another.

Update#2

You can do something like this:

public abstract class ThreadContextRunnable implements Runnable {

  private final Map context = ThreadContext.getContext();

  @Override
  public final void run() {
    if (context != null) {
      ThreadContext.putAll(context);
    }
    try {
      runWithContext();
    } finally {
      ThreadContext.clearAll();
    }
  }

  protected abstract void runWithContext();
}

And then you only need to implement runWithContext method.