Annotations

For most users, the out-of-the-box instrumentation is completely sufficient and nothing more has to be done. Sometimes, however, users wish to create spans for their own custom code without needing to make many code changes.

If you add the WithSpan annotation to a method, the method is wrapped in a span. The SpanAttribute annotation allows you to capture the method arguments as attributes.

package otel;

import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.instrumentation.annotations.SpanAttribute;
import io.opentelemetry.instrumentation.annotations.WithSpan;
import org.springframework.stereotype.Component;

/** Test WithSpan */
@Component
public class TracedClass {

  @WithSpan
  public void tracedMethod() {}

  @WithSpan(value = "span name")
  public void tracedMethodWithName() {
    Span currentSpan = Span.current();
    currentSpan.addEvent("ADD EVENT TO tracedMethodWithName SPAN");
    currentSpan.setAttribute("isTestAttribute", true);
  }

  @WithSpan(kind = SpanKind.CLIENT)
  public void tracedClientSpan() {}

  public void tracedMethodWithAttribute(@SpanAttribute("attributeName") String parameter) {}
}

You can disable the OpenTelemetry annotations by setting the otel.instrumentation.annotations.enabled property to false.

You can customize the span by using the elements of the WithSpan annotation:

NameTypeDescriptionDefault Value
valueStringSpan nameClassName.Method
kindSpanKindSpan kind of the spanSpanKind.INTERNAL

You can set the attribute name from the value element of the SpanAttribute annotation:

NameTypeDescriptionDefault Value
valueStringAttribute nameMethod parameter name

Dernière modification July 24, 2024: Include Java example code excerpts (#4642) (99dfcdeb)