【问题标题】:Log4j ThreadContext MultiThread won't inheritLog4j ThreadContext MultiThread 不会继承
【发布时间】: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 属性事件打印。

【问题讨论】:

    标签: java log4j


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2022-08-05
        • 1970-01-01
        • 2016-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-22
        • 2015-04-19
        • 1970-01-01
        相关资源
        最近更新 更多