Search code examples
javaspringspring-cloudspring-cloud-sleuth

How to tag a subtree of spans in Spring Cloud Sleuth? Or, how to sub-divide traces?


When a sender sends a post, I need to notify multiple subscribers. In this case, "sender sends a post" is a HTTP post and create a trace.

My goal: When looking at my logs, I will know "which subscriber is the method creating this log notifying".

My naive thoughts: For each of the "notify subscriber A", "notify subscriber B", etc, they are a sub-tree of spans. If I can give tag onto each of these sub-tree of spans then I am done.

However, I do not know how to do that. Or, is there any other ways to achieve my goal?

Thanks!


Solution

  • If I understand what you are trying to achieve here, that is the default behavior of Sleuth, please take a look at the docs for the trace-span and the parent-child spans relationships.

    The only thing you need to do is creating a new Span every time you notify a subscriber. There are multiple ways to do this, please see the the docs (e.g.: tracer.withSpan, @NewSpan).

    Here's an imaginary example:

    @GetMapping("/something") // Sleuth has already created a span for your endpoint
    public void something() {
        subscribers.forEach(subscriber -> notify(subscriber, new Event("foo")));
    }
    
    @NewSpan // This does the trick
    public void notify(Subscriber subscriber, Event event) {
        subscriber.notify(event);
    }
    

    If you want to tag your spans, please check the link to the docs I put above, it will show you how to attach tags.