首页 > 解决方案 > Log4j:为什么在提交给 ExecutorService 的 Callable 中登录时缺少日志条目

问题描述

我有一些看起来像这样的东西:

private static final Logger log = Logger.getLogger(thisClass.class);
private static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(1);
...
...
public void method1() {
    Callable<Integer> callable = () -> {
        Timer timer = new Timer();
        try {
            Integer i = someMethod();
            log.info("got " + i + " in " + timer.getElapsedTime());
        } catch (Exception e) {
            log.info("exception thrown after " + timer.getElapsedTime());
            throw e;
        }
        return i;
    };
    method2(callable);
    log.info("method1 called method2");
}

public static void method2(Callable<Integer> callable) {
    Future<Integer> future = EXECUTOR.submit(task);
    future.get();
}

出于某种原因,当我使用 maven 运行我的应用程序时,method1 被调用了 200 次,我可以看到 Callable 之外的日志条目(“method1 调用 method2”)200 次,但我只看到为Callable 中的一个(“在 t 秒内得到 i”)

我究竟做错了什么?

标签: javamavenlogginglog4jexecutorservice

解决方案


使用 AsyncAppender 解决了问题


推荐阅读