我正在使用 MDC Logger,除了一种情况外,它对我来说非常适合。无论我们在代码中的何处使用 CompletableFuture,对于创建的线程,MDC 数据都不会传递到下一个线程,因此日志会失败。例如,在代码中我使用下面的代码片段来创建新线程。
CompletableFuture.runAsync(() -> getAcountDetails(user));
日志结果如下
2019-04-29 11:44:13,690 INFO | /app/rest/controller/userdetails | f80fdc1f-8123-3932-a405-dda2dc2a80d5 |[http-nio-8182-exec-5] RestServiceExecutor: service:
2019-04-29 11:44:13,690 INFO | /app/rest/controller/userdetails | f80fdc1f-8123-3932-a405-dda2dc2a80d5 |[http-nio-8182-exec-5] RestServiceExecutor:
2019-04-29 11:44:13,779 INFO | /app/rest/controller/userdetails | f80fdc1f-8123-3932-a405-dda2dc2a80d5 |[http-nio-8182-exec-5] UserDetailsRepoImpl:
2019-04-29 11:44:13,950 INFO [ForkJoinPool.commonPool-worker-3] RestServiceExecutor: header:
2019-04-29 11:44:13,950 INFO [ForkJoinPool.commonPool-worker-3] RestServiceExecutor: service:
2019-04-29 11:44:14,012 INFO [ForkJoinPool.commonPool-worker-3] CommonMasterDataServiceImpl: Cache: Retrieving Config Data details.
2019-04-29 11:44:14,028 INFO [ForkJoinPool.commonPool-worker-3] CommonMasterDataServiceImpl: Cache: Retrieved Config Data details : 1
2019-04-29 11:44:14,028 INFO [ForkJoinPool.commonPool-worker-3] CommonMasterDataServiceImpl: Cache: Retrieving Config Data details.
2019-04-29 11:44:14,033 INFO [ForkJoinPool.commonPool-worker-3] CommonMasterDataServiceImpl: Cache: Retrieved Config Data details : 1
2019-04-29 11:44:14,147 INFO | /app/rest/controller/userdetails | f80fdc1f-8123-3932-a405-dda2dc2a80d5 |[http-nio-8182-exec-5] SecondaryCacheServiceImpl: Fetching from secondary cache
2019-04-29 11:44:14,715 INFO | /app/rest/controller/userdetails | f80fdc1f-8123-3932-a405-dda2dc2a80d5 |[http-nio-8182-exec-5] CommonMasterDataServiceImpl: Cache: Retrieving Config Data details.
2019-04-29 11:44:14,749 INFO | /app/rest/controller/userdetails | f80fdc1f-8123-3932-a405-dda2dc2a80d5 |[http-nio-8182-exec-5]
下面是我的 MDC 数据,它没有通过线程传递[ForkJoinPool.commonPool-worker-3]
| /app/rest/controller/userdetails | f80fdc1f-8123-3932-a405-dda2dc2a80d5 |
下面是我的 logback.xml 配置,其中会话ID是MDC数据
<configuration scan="true">
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<charset>utf-8</charset>
<Pattern>%d %-5level %X{sessionID} [%thread] %logger{0}: %msg%n</Pattern>
</encoder>
</appender>
</configuration>
我尝试了下面的链接
http://shengwangi.blogspot.com/2015/09/using-log-mdc-in-multi-thread-helloworld-example.html?_sm_au_=iVVrZDSwwf0vP6MR http://shengwangi.blogspot.com/2015/09/using-log-mdc-in-multi-thread-helloworld-example.html?_sm_au_=iVVrZDSwwf0vP6MR
这非常适合 TaskExecutor。但我还没有找到 CompletableFuture 的任何解决方案。