Search code examples
javaspringspring-cloud-sleuth

How to add information to every span with Spring Cloud Sleuth


I am currently trying to understand how I can customize Spring Cloud Sleuth in a scalable way to add information to every Span.

What I have tried so far:

Using my own implementation of GenericFilterBean and HandlerInterceptorAdapter, give them a Tracer in the constructor and write Tags everytime they are called with tracer.addTag("key", "value")

I had a look at the idea of the new baggage information - however I interpret it in a way that it is global for the whole trace - and as the trace has several requests accross different services/machines it would not fit my purpose of adding information on service/machine level.

So far the tags from the Filter and Interceptor get set for some Spans but not for all, when I inspect the JSON that is written to my kafka topic through spring-cloud-stream-binder-kafka

So my question would be: Which types of requests/actions do exist that create spans and what are the appropriate ways to inject something into those spans. As I want to deploy this implementation to several micro services I do not want to annotate each and every method or do similarly work intensive and therefor not scalable approaches.


Solution

  • There are a lot of such places... but actually, we can tackle the problem from another angle. There's a single place where you can hook in - when the span is closed. https://github.com/spring-cloud/spring-cloud-sleuth/blob/master/spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/SpanReporter.java - you can create your own implementation of SpanReporter that before delegating to for example Zipkin span reporter will add a tag. Even easier way will be to just register the SpanAdjuster bean that adjusts the span before it gets reported. That way you can add the tag only in one place.