注释
对于大多数用户来说,开箱即用的仪器化已经完全足够,无需进一步操作。然而,有时用户希望为自己的自定义代码创建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) {}
}
注意
OpenTelemetry 注解使用基于代理的 Spring AOP。
这些注解仅适用于代理的方法。您可以在Spring 文档中了解更多信息。
在以下示例中,当调用 GET 端点时,WithSpan 注解将不起作用
@RestController
public class MyControllerManagedBySpring {
@GetMapping("/ping")
public void aMethod() {
anotherMethod();
}
@WithSpan
public void anotherMethod() {
}
}
注意
要使用 OpenTelemetry 注解,您需要将 Spring Boot Starter AOP 依赖添加到您的项目中
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
dependencies {
implementation("org.springframework.boot:spring-boot-starter-aop")
}
您可以通过将 otel.instrumentation.annotations.enabled 属性设置为 false 来禁用 OpenTelemetry 注解。
您可以使用 WithSpan 注解的元素来定制 span
| 名称 | 类型 | 描述 | 默认值 |
|---|---|---|---|
value | 字符串 | Span 名称 | ClassName.Method |
kind | SpanKind | Span 的 SpanKind | SpanKind.INTERNAL |
您可以使用 SpanAttribute 注解的 value 元素来设置属性名称
| 名称 | 类型 | 描述 | 默认值 |
|---|---|---|---|
value | 字符串 | 属性名称 | 方法参数名称 |
下一步
除了使用注解之外,OpenTelemetry API 还允许您获取一个 tracer,可用于自定义仪器化。