OpenTelemetry笔记(5)-Attributes

AttributeKey

是带有类型的键

接口定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public interface AttributeKey<T> {

String getKey();

AttributeType getType();
}
public enum AttributeType {
STRING,
BOOLEAN,
LONG,
DOUBLE,
STRING_ARRAY,
BOOLEAN_ARRAY,
LONG_ARRAY,
DOUBLE_ARRAY
}

创建 AttributeKey

使用 AttributeKey 的静态方法进行快捷创建

1
2
AttributeKey.stringKey("hello");
AttributeKey.longKey("age");

Attributes

Attribute 由一个 AttributeKey 和 Value 组成,类似于 Map 的 MapEntry

;Attributes 则由多个 Attribute 组成,Attributes 可以理解为 AttributeKey 的 Map 实现

接口定义

1
2
3
4
5
6
7
8
9
public interface Attributes {

<T> T get(AttributeKey<T> key);
void forEach(BiConsumer<? super AttributeKey<?>, ? super Object> consumer);

int size();
boolean isEmpty();
Map<AttributeKey<?>, Object> asMap();
}

创建 Attributes

调用 Attributes 的 of 静态方法创建

of 方法有多个重载版本,可以由单个或多个 Attribute 一起创建

1
2
Attributes attributes = Attributes.of(stringKey("key"), "value");
Attributes attributes = Attributes.of(stringKey("key1"), "value1", longKey("key2"), 333L);

使用 AttributesBuilder 创建

1
2
3
4
5
6
7
8
9
Attributes attributes =
Attributes.builder()
.put("string", "value1")
.put("long", 100)
.put(longKey("long2"), 10)
.put("double", 33.44)
.put("boolean", "duplicateShouldBeRemoved")
.put("boolean", false)
.build();

Attribute 扩展

AttributeSetter

设置 AttributeKey 的一个函数式接口,对应 Span 的 setAttribute 方法

接口定义

1
2
3
4
5
@Deprecated
@FunctionalInterface
public interface AttributeSetter {
<T> void setAttribute(AttributeKey<T> key, T value);
}

示例

1
2
3
Span span = tracer.spanBuilder("basicSpan").startSpan();
AttributeSetter attributeSetter=span::setAttribute;
attributeSetter.setAttribute(AttributeKey.stringKey("hello"),"hello");

AttributeBinding

其内部绑定了一个 AttributeKey,执行时不需要知道 AttributeKey

接口定义

1
2
3
4
5
@FunctionalInterface
public interface AttributeBinding {

void apply(AttributeSetter setter, Object arg);
}

示例

1
2
3
AttributeKey<String> key = AttributeKey.stringKey("hello");
AttributeBinding binding=(setter, arg) -> setter.setAttribute(key, (String) arg);
binding.apply(span::setAttribute,"hello");

AttributeBindings

AttributeBindingd 的 args 表示方法入参的长度,其默认实现中,内部有一个参数索引,可以选择一个索引来选择参数作为 AttributeSetter 的入参

接口和实现定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public interface AttributeBindings {
boolean isEmpty();
void apply(AttributeSetter setter, Object[] args);
}

final class CombinedAttributeBindings implements AttributeBindings {

private final int index;
private final AttributeBinding binding;
@Override
public boolean isEmpty() {
return false;
}

@Override
public void apply(AttributeSetter setter, Object[] args) {
if (args != null && args.length > index) {
Object arg = args[index];
if (arg != null) {
binding.apply(setter, arg);
}
}
}
}