gateway/middleware/jaeger.go

79 lines
2.0 KiB
Go
Raw Normal View History

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-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 11:58:02 +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())
// 设置接口地址
ext.HTTPUrl.Set(parentSpan, c.Request.RequestURI)
// 设置请求方式
ext.HTTPMethod.Set(parentSpan, c.Request.Method)
// 执行后续操作
2021-09-07 13:40:44 +08:00
c.Next()
// 设置返回状态码
2021-09-07 13:40:44 +08:00
ext.HTTPStatusCode.Set(parentSpan, uint16(c.Writer.Status()))
// 如果状态码大于299设置错误标签
2021-09-07 13:40:44 +08:00
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 {
//core.Log.Error("Jaeger连接失败: %v", err.Error())
2021-09-07 13:40:44 +08:00
return nil, nil
}
//core.Log.Debug("Jaeger连接成功")
2021-09-07 13:40:44 +08:00
opentracing.SetGlobalTracer(tracer)
return tracer, closer
}