Setting ThreadContext for all threads in application

时间秒杀一切 提交于 2019-12-11 04:16:49

问题


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.



来源:https://stackoverflow.com/questions/40423667/setting-threadcontext-for-all-threads-in-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!