Gar*_*lsh 2 java multithreading log4j log4j2
从这个答案/sf/answers/1758761161/我routingAppender正在工作,但我想为ThreadContext程序中的每个线程设置。
当我设定
ThreadContext.put("logFileName", "TestLogFile");
Run Code Online (Sandbox Code Playgroud)
它适用于主线程并按预期方式记录日志,但不适用于我的应用程序中的任何其他线程。我该如何实现?
如果将系统属性isThreadContextMapInheritable设置为true,则每个子线程都将继承父级ThreadContext状态。但这对执行者不起作用,因此您需要手动将数据从一个线程复制到另一个线程。
更新#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();
}
Run Code Online (Sandbox Code Playgroud)
然后,您只需要实现runWithContext方法。