我遇到这个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();
}
}
来自
ThreadContext
的 LOGGER.info("Hello from main");
可以工作并且还可以打印 foo: bar
。StreamGobbler
设置为 ThreadContext
,我的子线程 foo: bar
不会获得 isThreadContextMapInheritable
并且不会将 true
作为 log4j 属性事件打印。
刚刚遇到这个问题。发现在应用程序启动时设置 -DisThreadContextMapInheritable=true 有效,即使在代码中设置它不起作用。
除了jonathan的回答。
您还可以在代码中设置此属性,如下所示:
(在包含
main
方法的类中,在第一次调用 LogManager
之前。)
public class YourClass {
static {
System.setProperty("isThreadContextMapInheritable", "true");
}
...
public static void main(String[] args) {
...
}