-
Notifications
You must be signed in to change notification settings - Fork 5
/
tracer.go
57 lines (51 loc) · 1.45 KB
/
tracer.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
package middleware
import (
"context"
"github.com/uber/jaeger-client-go"
"github.com/opentracing/opentracing-go/ext"
"github.com/golang-minibear2333/gin-blog/global"
"github.com/gin-gonic/gin"
"github.com/opentracing/opentracing-go"
)
// Tracing 让每次接口调用都能上报到追踪系统中
func Tracing() func(c *gin.Context) {
return func(c *gin.Context) {
var newCtx context.Context
var span opentracing.Span
spanCtx, err := opentracing.GlobalTracer().Extract(
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(c.Request.Header),
)
if err != nil {
span, newCtx = opentracing.StartSpanFromContextWithTracer(
c.Request.Context(),
global.Tracer,
c.Request.URL.Path,
)
} else {
span, newCtx = opentracing.StartSpanFromContextWithTracer(
c.Request.Context(),
global.Tracer,
c.Request.URL.Path,
opentracing.ChildOf(spanCtx),
opentracing.Tag{Key: string(ext.Component), Value: "HTTP"},
)
}
defer span.Finish()
var traceID string
var spanID string
// 通过span context 获取 traceID 和 spanID
var spanContext = span.Context()
switch spanContext.(type) {
case jaeger.SpanContext:
jaegerContext := spanContext.(jaeger.SpanContext)
traceID = jaegerContext.TraceID().String()
spanID = jaegerContext.SpanID().String()
}
// 注册到上下文元数据中
c.Set("X-Trace-ID", traceID)
c.Set("X-Span-ID", spanID)
c.Request = c.Request.WithContext(newCtx)
c.Next()
}
}