Log4j2 ThreadContext映射不适用于parallelStream() [英] Log4j2 ThreadContext map is not working for parallelStream()

查看:145
本文介绍了Log4j2 ThreadContext映射不适用于parallelStream()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下示例代码:

public class Test {
    static {
        System.setProperty("isThreadContextMapInheritable", "true");
    }

    private static final Logger LOGGER = LogManager.getLogger(Test.class);

    public static void main(String[] args) {
        ThreadContext.put("UUID", UUID.randomUUID().toString());
        LOGGER.info("in main method start");
        new Test().run();
        LOGGER.info("in main method end");    
    }

    private void run() {
        Collections.nCopies(10, 1)
                .parallelStream()
                .forEach(i->LOGGER.info("Inside thread"));    
    }
}

Log4j2模式如下:

Log4j2 pattern is following:

<pattern>%X{UUID} [%t] %msg %n</pattern>

在生产结果上方运行:

2cf774ff-03c8-483e-9828-451b61349221 [main] in main method start 
2cf774ff-03c8-483e-9828-451b61349221 [main] Inside thread 
2cf774ff-03c8-483e-9828-451b61349221 [main] Inside thread 
2cf774ff-03c8-483e-9828-451b61349221 [main] Inside thread 
2cf774ff-03c8-483e-9828-451b61349221 [main] Inside thread 
2cf774ff-03c8-483e-9828-451b61349221 [main] Inside thread 
2cf774ff-03c8-483e-9828-451b61349221 [ForkJoinPool.commonPool-worker-3] Inside thread 
2cf774ff-03c8-483e-9828-451b61349221 [ForkJoinPool.commonPool-worker-1] Inside thread 
 [ForkJoinPool.commonPool-worker-1] Inside thread 
 [ForkJoinPool.commonPool-worker-1] Inside thread 
 [ForkJoinPool.commonPool-worker-3] Inside thread 
2cf774ff-03c8-483e-9828-451b61349221 [main] in main method end 

如您所见,第一次出现在 [ForkJoinPool.commonPool-wor ker-1] [ForkJoinPool.commonPool-worker-3] 线程 UUID 变量

As you can see, the first time in [ForkJoinPool.commonPool-worker-1] and [ForkJoinPool.commonPool-worker-3] threads UUID variable was logged, but other times were not logged.

为什么Log4j2跳过某些线程的 ThreadContext 变量以及如何修复

Why Log4j2 skips ThreadContext variable for some threads and how to fix this?

谢谢您的帮助!

推荐答案

我知道这个是一篇旧文章,

但是我在同一个问题上苦苦挣扎,花了几天的时间才找到可行的解决方案。

这是answer ,创建自定义 ThreadPoolExecutor 确实解决了我的问题。

I know this is an old post,
But I struggled on the same problem and it took me few days to find a working solution.
Here's the answer, creating a custom ThreadPoolExecutor did fix my problem.

这篇关于Log4j2 ThreadContext映射不适用于parallelStream()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆