How to add custom OpenTelemetry Span Attribute in Vertx for Head Sampling

128 views Asked by At

To use Span Attribute for Head Sampling, attribute must set before startSpan(). In Vertx, Span is created in very low level, and the attributes is limited from fixed implementation of TagExtractor. https://github.com/eclipse-vertx/vertx-tracing/blob/4.4.6/vertx-opentelemetry/src/main/java/io/vertx/tracing/opentelemetry/OpenTelemetryTracer.java#L148-L154

For workaround we can create custom OpenTelemetryOptions and OpenTelemetryTracer to have custom TagExtractor to insert the attribute we want. But this look like a hack to me.

The Span.current() will not work for me, not only because head sampling, but also my custom attribute details can obtain only before vertx sendRequest.

@Override
  public <R> Span sendRequest(
          final Context context,
          final SpanKind kind,
          final TracingPolicy policy,
          final R request,
          final String operation,
          final BiConsumer<String, String> headers,
          final TagExtractor<R> tagExtractor) {

    ...

    final Span span = reportTagsAndStart(tracer.spanBuilder(operation)
                    .setParent(tracingContext)
                    .setSpanKind(SpanKind.RPC.equals(kind) ? io.opentelemetry.api.trace.SpanKind.CLIENT : io.opentelemetry.api.trace.SpanKind.PRODUCER)
            , request, customTagExtractor != null ? (TagExtractor<R>) customTagExtractor : tagExtractor);

    tracingContext = tracingContext.with(span);
    propagators.getTextMapPropagator().inject(tracingContext, headers, setter);

    return span;
  }
TagExtractor<HttpRequestHead> customTagExtractor = new TagExtractor<HttpRequestHead>() {
    @Override
    public int len(HttpRequestHead req) {
        return 1;
    }
    @Override
    public String name(HttpRequestHead req, int index) {
        switch (index) {
            case 0:
                return "filter";
        }
        throw new IndexOutOfBoundsException("Invalid tag index " + index);
    }
    @Override
    public String value(HttpRequestHead req, int index) {
        switch (index) {
            case 0:
                return req.headers.get("filter");
        }
        throw new IndexOutOfBoundsException("Invalid tag index " + index);
    }
};

I am looking for better solution than this workaround or correct way to handle this.

0

There are 0 answers