为应用程序中的所有线程设置ThreadContext



从这个答案https://stackoverflow.com/a/25125159/4367326我有routingAppender工作,但我想为程序中的每个线程设置ThreadContext

设置

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

它适用于主线程并按预期记录日志,但不适用于应用程序中的任何其他线程。我怎样才能做到这一点呢?

如果将系统属性isThreadContextMapInheritable设置为true,则每个子线程都将继承父线程的ThreadContext状态。但这对executor不起作用,所以你需要手动将数据从一个线程复制到另一个线程。

更新# 2

你可以这样做:

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();
}

然后你只需要实现runWithContext方法

最新更新