2021-09-07 13:40:44 +08:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2021-09-08 14:24:07 +08:00
|
|
|
gc "gateway/config"
|
2021-09-09 09:48:58 +08:00
|
|
|
"gateway/core"
|
2021-09-07 13:40:44 +08:00
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/opentracing/opentracing-go"
|
|
|
|
"github.com/opentracing/opentracing-go/ext"
|
|
|
|
"github.com/uber/jaeger-client-go/config"
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
|
|
|
func OpenTracing() gin.HandlerFunc {
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
var parentSpan opentracing.Span
|
|
|
|
|
2021-09-08 14:24:07 +08:00
|
|
|
tracer, closer := NewJaegerTracer()
|
2021-09-07 13:40:44 +08:00
|
|
|
defer closer.Close()
|
|
|
|
|
|
|
|
spCtx, err := opentracing.GlobalTracer().Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(c.Request.Header))
|
|
|
|
|
|
|
|
if err != nil {
|
2021-09-09 09:48:58 +08:00
|
|
|
core.Log.Error("Jaeger错误: %v", err.Error())
|
2021-09-07 13:40:44 +08:00
|
|
|
parentSpan = tracer.StartSpan(c.Request.URL.Path)
|
|
|
|
defer parentSpan.Finish()
|
|
|
|
} else {
|
|
|
|
parentSpan = opentracing.StartSpan(
|
|
|
|
c.Request.URL.Path,
|
|
|
|
opentracing.ChildOf(spCtx),
|
|
|
|
opentracing.Tag{Key: string(ext.Component), Value: "HTTP"},
|
|
|
|
ext.SpanKindRPCServer,
|
|
|
|
)
|
|
|
|
defer parentSpan.Finish()
|
|
|
|
}
|
|
|
|
|
|
|
|
c.Set("Tracer", tracer)
|
|
|
|
asd := fmt.Sprintf("%v", parentSpan.Context())
|
|
|
|
c.Set("UberTraceId", asd)
|
|
|
|
c.Set("ParentSpanContext", parentSpan.Context())
|
|
|
|
|
|
|
|
c.Next()
|
|
|
|
|
|
|
|
ext.HTTPStatusCode.Set(parentSpan, uint16(c.Writer.Status()))
|
|
|
|
|
|
|
|
if c.Writer.Status() > 299 {
|
|
|
|
ext.Error.Set(parentSpan, true)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-08 14:24:07 +08:00
|
|
|
func NewJaegerTracer() (opentracing.Tracer, io.Closer) {
|
2021-09-07 13:40:44 +08:00
|
|
|
cfg := &config.Configuration{
|
|
|
|
Sampler: &config.SamplerConfig{
|
|
|
|
Type: "const", //固定采样
|
|
|
|
Param: 1, //1=全采样、0=不采样
|
|
|
|
},
|
|
|
|
|
|
|
|
Reporter: &config.ReporterConfig{
|
|
|
|
LogSpans: true,
|
2021-09-08 14:24:07 +08:00
|
|
|
LocalAgentHostPort: gc.AppInfo.JaegerServer,
|
2021-09-07 13:40:44 +08:00
|
|
|
},
|
|
|
|
|
2021-09-08 14:24:07 +08:00
|
|
|
ServiceName: gc.AppInfo.AppName,
|
2021-09-07 13:40:44 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
tracer, closer, err := cfg.NewTracer()
|
|
|
|
if err != nil {
|
2021-09-09 09:48:58 +08:00
|
|
|
core.Log.Error("Jaeger连接失败: %v", err.Error())
|
2021-09-07 13:40:44 +08:00
|
|
|
return nil, nil
|
|
|
|
}
|
2021-09-09 09:48:58 +08:00
|
|
|
core.Log.Debug("Jaeger连接成功")
|
2021-09-07 13:40:44 +08:00
|
|
|
opentracing.SetGlobalTracer(tracer)
|
|
|
|
return tracer, closer
|
|
|
|
}
|