I have following sample code:
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 is following:
<pattern>%X{UUID} [%t] %msg %n</pattern>
Running above produce result:
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
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.
Why Log4j2 skips ThreadContext
variable for some threads and how to fix this?
Thanks for any help!