我有以下示例代码:
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 模式如下:
<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-worker-1]
and [ForkJoinPool.commonPool-worker-3]
线程UUID
变量已记录,但其他时间未记录。
为什么 Log4j2 会跳过ThreadContext
某些线程的变量以及如何解决这个问题?
谢谢你的帮助!
我知道这是一篇旧帖子
但我在同样的问题上苦苦挣扎,花了几天时间才找到可行的解决方案。
这是answer https://stackoverflow.com/a/19329668/11825162,创建自定义ThreadPoolExecutor
确实解决了我的问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)