Java 为应用程序中的所有线程设置ThreadContext
从这个答案中,我看到了Java 为应用程序中的所有线程设置ThreadContext,java,multithreading,log4j,log4j2,Java,Multithreading,Log4j,Log4j2,从这个答案中,我看到了routingAppender正在工作,但我想为程序中的每个线程设置ThreadContext ThreadContext.put("logFileName", "TestLogFile"); 当我设定 ThreadContext.put("logFileName", "TestLogFile"); 它按预期适用于主线程和日志,但不适用于我的应用程序中的任何其他线程。如何实现这一点?如果将系统属性设置为true,则每个子线程都将继承父线程上下文状态。但这对执行器不起作用
routingAppender
正在工作,但我想为程序中的每个线程设置ThreadContext
ThreadContext.put("logFileName", "TestLogFile");
当我设定
ThreadContext.put("logFileName", "TestLogFile");
它按预期适用于主线程和日志,但不适用于我的应用程序中的任何其他线程。如何实现这一点?如果将系统属性设置为true,则每个子线程都将继承父线程上下文状态。但这对执行器不起作用,所以您需要手动将数据从一个线程复制到另一个线程
ThreadContext.put("logFileName", "TestLogFile");
更新#2
ThreadContext.put("logFileName", "TestLogFile");
您可以这样做:
ThreadContext.put("logFileName", "TestLogFile");
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方法。对于执行器,我可以在它们为所有执行器子级调用的类的run()中设置ThreadContext吗?
ThreadContext.put("logFileName", "TestLogFile");