Log4j ThreadContext MultiThread 不会继承



我遇到了这篇文章的问题
这里是我的代码示例

public class StackOverflow implements RequestHandler<Map<String, String>, ApiGatewayResponse> {
private static final Logger LOGGER = LogManager.getLogger(StackOverflow.class);
public abstract class StreamGobbler extends Thread {
// Working Interceptor using this.print("message")
public abstract void print(String line);
}
private class ErrStreamGobbler extends StreamGobbler {
ErrStreamGobbler(InputStream in) { super(in); }
@Override
public void print(String line) { LOGGER.error(line); }
}
private class OutStreamGobbler extends StreamGobbler {
OutStreamGobbler(InputStream in) { super(in); }
@Override
public void print(String line) { LOGGER.info(line); }
}

// MAIN METHOD
@Override
public ApiGatewayResponse handleRequest(Map<String, String> params, Context context) {
// ThreadContext propagation
System.setProperty("isThreadContextMapInheritable", "true");
ThreadContext.put("foo", "bar");
LOGGER.info("Hello from main");
// My process will return value on System.in & System.out
ProcessBuilder pb = new ProcessBuilder("sh", String.format("batchs/JOB_FOO/run.sh"));
Process p = pb.start();
// Intercept those logs
new ErrStreamGobbler(p.getErrorStream()).start();
new OutStreamGobbler(p.getInputStream()).start();
p.waitFor();
}
}

来自LOGGER.info("Hello from main");ThreadContext确实工作,并且还打印foo: bar
但是我的子线程StreamGobbler没有得到ThreadContext,并且如果isThreadContextMapInheritable设置为true,则不会将foo: bar打印为log4j属性事件。

刚刚遇到这个问题。在应用程序启动时发现设置-DisThreadContextMapInheritable=true有效,即使在代码中设置它无效。

使用自定义ThreadPoolExecutor确实解决了我的问题
使用此答案找到此解决方案。

最新更新