2

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.

ch271828n
  • 15,854
  • 5
  • 53
  • 88

1 Answers1

4

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");
     }
});
Marcin Grzejszczak
  • 10,624
  • 1
  • 16
  • 32
  • Thanks very much! So should I do this for **every** callback like handle/whenCompleete/...? Or, can Sleuth automatically do some magic, like LazyTraceExecutor or even instrumentation? Thanks! – ch271828n Feb 05 '21 at 14:10
  • @ch271828n open-telemetry does this via instrumentation. – Eugene Feb 05 '21 at 17:04
  • @Eugene Thanks very much! It seems that this is not supported to spring yet (?) so I will just do it manually as you have provided – ch271828n Feb 06 '21 at 00:25
  • @Marcin Grzejszczak Do we need to close `SpanInScope` or no? I would like to propagate traceId into completableFuture returned from asyncRabbitTemplate and I don't known when to invoke `close` – ciostek223 Mar 22 '22 at 06:55
  • As you can see we did try with resources on withSpanInScope which means that the scope is only opened when log.info happens. You should close the scope before you get out of the thread – Marcin Grzejszczak Mar 22 '22 at 10:56
  • @Eugene Can you provide details on how this is being manually or auto instrumented in Opentelemetry? – Mooncrater Jul 03 '23 at 12:42