Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

question from:https://stackoverflow.com/questions/66064271/keep-trace-span-across-completablefuture-in-spring-cloud-sleuth

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
715 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 sth like this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...