gateway/middleware/jaeger.go
李寻欢 21950f5dbf
All checks were successful
continuous-integration/drone/push Build is passing
🎨 完善网关
2021-09-09 09:48:58 +08:00

76 lines
1.8 KiB
Go

package middleware
import (
"fmt"
gc "gateway/config"
"gateway/core"
"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
tracer, closer := NewJaegerTracer()
defer closer.Close()
spCtx, err := opentracing.GlobalTracer().Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(c.Request.Header))
if err != nil {
core.Log.Error("Jaeger错误: %v", err.Error())
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)
}
}
}
func NewJaegerTracer() (opentracing.Tracer, io.Closer) {
cfg := &config.Configuration{
Sampler: &config.SamplerConfig{
Type: "const", //固定采样
Param: 1, //1=全采样、0=不采样
},
Reporter: &config.ReporterConfig{
LogSpans: true,
LocalAgentHostPort: gc.AppInfo.JaegerServer,
},
ServiceName: gc.AppInfo.AppName,
}
tracer, closer, err := cfg.NewTracer()
if err != nil {
core.Log.Error("Jaeger连接失败: %v", err.Error())
return nil, nil
}
core.Log.Debug("Jaeger连接成功")
opentracing.SetGlobalTracer(tracer)
return tracer, closer
}