Sleuth traceId and spanId are not propagated to parallelStream worker threads

Viewed 1429

I have integrated Sleuth to my Spring Boot project in order to have a better traceability. It logs perfectly traceId and spanId. However, these fields are not added to logs generated in some operations performed using parallelStream.

Sleuth doc suggests to use CompletableFuture instead:

Sleuth does not work with parallelStream() out of the box. If you want to have the tracing information propagated through the stream, you have to use the approach with supplyAsync(...), as shown earlier

But it says that parallelStream does not work "out of the box". So, is there any workaround to use parallelStream ?

Thanks for any help or comment on this

1 Answers

The closest you can do is to call a completable future

CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> {
                ingredientsCollector.collectIngredients(order, processId).stream()
                        .filter(ingredient -> ingredient != null)
                        .forEach((Ingredient ingredient) -> {
                            log.info("Adding an ingredient [{}] for order [{}] , processId [{}]", ingredient);
                            ingredientWarehouse.addIngredient(ingredient);
                        });
                return null;
            }, new TraceableExecutorService(this.beanFactory, Executors.newFixedThreadPool(5), "fetchIngredients"));
Related