-
Notifications
You must be signed in to change notification settings - Fork 0
/
span.go
78 lines (62 loc) · 1.67 KB
/
span.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package utils
import (
"context"
"os"
"github.com/gin-gonic/gin"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"github.com/tangx/opentelemetry-gin-demo/global"
)
func Span(ctx context.Context, spanName string, opts ...trace.SpanStartOption) (spanctx context.Context, span trace.Span) {
value := ctx.Value(global.TracerKey)
tracer, ok := value.(trace.Tracer)
if !ok {
return ctx, nil
}
// gin 特殊
if c, ok := ctx.(*gin.Context); ok {
spanctx, span = tracer.Start(c.Request.Context(), spanName, opts...)
/*
在这里每次注入新的 Attr
1. host
*/
// 1. 从 context 中获取 "public attr"
// attr:=ctx.Value("")
// 2. 注入 public attr
// span.SetAttributes(attr)
spanctx = context.WithValue(spanctx, global.TracerKey, tracer)
// return spanctx, span
} else {
spanctx, span = tracer.Start(ctx, spanName, opts...)
}
// 设置 Attr
attrkv, ok := ctx.Value("attrkv").(map[string]string)
if ok {
SpanSetStringAttr(span, attrkv)
}
SpanSetStringAttr(span, map[string]string{
"server.host": os.Getenv("HOSTNAME"),
})
return spanctx, span
}
func SpanSetStringAttr(span trace.Span, kvs map[string]string) {
attrkv := []attribute.KeyValue{}
for k, v := range kvs {
attrkv = append(attrkv, attribute.KeyValue{
Key: attribute.Key(k),
Value: attribute.StringValue(v),
})
}
span.SetAttributes(attrkv...)
}
func SpanContextWithAttr(ctx context.Context, kv map[string]string) context.Context {
value := ctx.Value("attrkv")
attrkv, ok := value.(map[string]string)
if !ok {
attrkv = make(map[string]string, 0)
}
for k, v := range kv {
attrkv[k] = v
}
return context.WithValue(ctx, "attrkv", attrkv)
}