Search code examples
springspring-cloud-sleuthdistributed-tracingbrave

How to write custom trace sender in Spring Sleuth / Brave


My company has got custom distributed tracing solution. I've got Java client/proxy library ready for it, its able to send traces/spans to server.

However I would like to integrate it with Spring Boot Sleuth / Brave, so to implement some kind of bridge from Brave, so brave would use my client/proxy libraries to send traces/spans.

How to customize only sender part in Brave ?

Another approach is to implement from scratch all Sleuth api interfaces (Tracer, Span, TraceContext, ... etc) which is a huge task.

I would like to use Brave implementation, only to inject some kind of bridge/adapter which will use my custom client/proxy.


Solution

  • I don't recommend implementing all the Sleuth interfaces, in that case you are writing a Tracing library (you are rewriting Brave).

    You can implement the zipkin2.reporter.Sender interface and create a @Bean from it, here is an example:

    public class SoutSender extends Sender {
        @Override
        public Encoding encoding() {
            return JSON;
        }
    
        @Override
        public int messageMaxBytes() {
            return 500 * 1024; //500 KiB
        }
    
        @Override
        public int messageSizeInBytes(List<byte[]> encodedSpans) {
            return encodedSpans.stream()
                    .mapToInt(encodedSpan -> encodedSpan.length)
                    .sum();
        }
    
        @Override
        public Call<Void> sendSpans(List<byte[]> encodedSpans) {
            encodedSpans.stream()
                    .map(String::new)
                    .forEach(System.out::println);
    
            return Call.create(null);
        }
    }
    

    You need to create a Reporter<zipkin2.Span> bean too but for this, you don't need to implement anything:

    @Bean
    Reporter<Span> soutReporter(SoutSender soutSender) {
        return AsyncReporter.create(soutSender);
    }
    
    @Bean
    Sender soutSender(SoutSender sender) {
        return new SoutSender();
    }
    

    This will register an additional reporter, if you only want to keep yours and don't want to report to zipkin and to your own system, you need to name the beans accordingly, please see the docs: https://docs.spring.io/spring-cloud-sleuth/docs/current/reference/html/project-features.html#overriding-the-auto-configuration-of-zipkin