异步任务日志中TraceId和Span为空

问题描述 投票:0回答:1

我在 springboot 中有一个 REST 端点,它使用 CompleteableFuture 调用外部 api 异步多个。使用

Completeablefuture.supplyAsync(() => callExternalApiAndReturnResponse(url, request))
中的resttemplate调用外部api。在 callExternalApiAndReturnResponse 方法中,我捕获 HTTP 异常并记录它,但是当记录此 http 异常时,跟踪和跨度为空,一旦异步任务完成,我就可以在日志中看到 id。

我尝试注入 TraceableExecutorService bean 并将其传递到完整的 Lecture.supplyAsync 中,但 id 为空。

请帮助如何在异步任务中传递相同的traceId?

提前致谢。

spring-boot log4j java.util.concurrent spring-cloud-sleuth distributed-tracing
1个回答
0
投票

注入

ObservationRegistry
并用当前观察包裹供应商。

            Supplier<String> supplier = () -> {
                log.info("inside");
                return "Hello World";
            };

            // when
            Supplier<String> wrappedSupplier = observationRegistry.getCurrentObservation().wrap(supplier);
            CompletableFuture<String> future = CompletableFuture.supplyAsync(wrappedSupplier);
© www.soinside.com 2019 - 2024. All rights reserved.