TraceId and Span are empty in async task logs

330 Views Asked by At

I have a REST endpoint in springboot which calls an external api async multiple using CompleteableFuture. The external api is called using resttemplate in Completeablefuture.supplyAsync(() => callExternalApiAndReturnResponse(url, request)). In the callExternalApiAndReturnResponse method I am catching HTTP exception and logging it, but the trace and span are coming as empty when this http exception is logged and I can see the id's in the logs once the async task is completed.

I tried injecting TraceableExecutorService bean and passing it in the completea lecture.supplyAsync but the id's are coming as empty.

Please help in how to pass the same traceId in the async task?

Thanks in advance.

1

There are 1 best solutions below

0
Martin Theiss On

Inject ObservationRegistry and wrap the supplier with the current observation.

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

            // when
            Supplier<String> wrappedSupplier = observationRegistry.getCurrentObservation().wrap(supplier);
            CompletableFuture<String> future = CompletableFuture.supplyAsync(wrappedSupplier);