Search code examples
vert.xdistributed-tracingvertx-eventbus

How to implement tracing in eventbus in vertx using opentracing or opentelemetry?


The webpage doesn't give much description on the same, Share some examples if possible.

    public class MainVerticle extends AbstractVerticle {
        
        Tracer tracer=GlobalTracer.getTracer();
        @Override
        public void start() {
            vertx.deployVerticle(new MainVerticle());
            Router router =Router.router(vertx);
            router.get("/home").handler(this::message);
            router.get("/home/:name").handler(this::messagectm);
            Tracer tracer = getTracer();
            vertx.createHttpServer(new HttpServerOptions().setTracingPolicy(TracingPolicy.ALWAYS)).requestHandler(router).listen(8080);
            Span span = tracer.buildSpan("my-operation")
          .withTag("example", "test")
          .start();
          OpenTracingUtil.setSpan(span);
          DeliveryOptions options = new DeliveryOptions().setTracingPolicy(TracingPolicy.ALWAYS);
            vertx.eventBus().send("addr","test",options);
            span.finish();
        }

This is my sample implementation that I tried but didn't work as expected


Solution

  • start() method is basically what happens during bootstrap. What you're actually doing is creating a span only once, when the application starts, and immediately close it.

    What you actually want to do is open a span in each route, similar to this:

    router.get("/home").handler((ctx) -> {
        Span span = tracer.buildSpan("my-operation")
          .withTag("example", "test")
          .start();
        this.message(ctx);
        span.finish();
    });
    

    Now, this code above is easy to understand, but not entirely correct, due to Vert.x asynchronous nature. What you'll get with it is probably a tiny span each time, unless your message() method is actually blocking.

    More correct way would be:

    router.get("/home").handler((ctx) -> {
        Span span = tracer.buildSpan("my-operation")
          .withTag("example", "test")
          .start();
        ctx.response().endHandler((h)->{span.finish();})
        this.message(ctx);
        
    });
    

    This will invoke end of span when your response closes, and that's probably what you want.

    To be clear, I don't have a running Vert.x instance with OpenTracing at the moment, so this is just an idea of how this should be implemented. Maybe you'll have to make some adjustments.