Search code examples
javaspringspring-cloudcompletable-futurespring-cloud-sleuth

Keep trace/span across CompletableFuture in Spring Cloud Sleuth


I am using Sleuth with CompletableFuture.handle. Example:

log.info("first");
apnsClient.sendNotification(...).handle((response, cause) -> {
     log.info("second");
});

I want the second log to have the same trace id as the first log. However, it does not. Thus I wonder what to do? Thanks!

P.S. I cannot control how apnsClient.sendNotification manage threads (since that is from Pushy), so there is no way to use things like LazyTraceExecutor.


Solution

  • What you can do is retrieve the span (e.g. via tracer.currentSpan()) before log.info("first"), pass the span to the lambda with log.info("second") and manually continue the trace via tracer.withSpanInScope(span). It would look like this:

    Span span = tracer.currentSpan();
    log.info("first");
    apnsClient.sendNotification(...).handle((response, cause) -> {
         try (SpanInScope ws = tracer.withSpanInScope(span)) {
             log.info("second");
         }
    });