【发布时间】:2020-09-29 13:51:40
【问题描述】:
我遇到了这个post的问题
这是我的代码示例
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。
但是如果isThreadContextMapInheritable 设置为true,我的子线程StreamGobbler 不会得到ThreadContext 并且不会将foo: bar 作为log4j 属性事件打印。
【问题讨论】: