注释

对于大多数用户来说,开箱即用的仪器化已经完全足够,无需进一步操作。然而,有时用户希望为自己的自定义代码创建span,而无需进行大量代码更改。

如果您将 WithSpan 注解添加到方法中,该方法将被包装在一个 span 中。SpanAttribute 注解允许您将方法参数捕获为属性。

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() {}

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

您可以通过将 otel.instrumentation.annotations.enabled 属性设置为 false 来禁用 OpenTelemetry 注解。

您可以使用 WithSpan 注解的元素来定制 span

名称类型描述默认值
value字符串Span 名称ClassName.Method
kindSpanKindSpan 的 SpanKindSpanKind.INTERNAL

您可以使用 SpanAttribute 注解的 value 元素来设置属性名称

名称类型描述默认值
value字符串属性名称方法参数名称

下一步

除了使用注解之外,OpenTelemetry API 还允许您获取一个 tracer,可用于自定义仪器化