gateway/middleware/jaeger.go
李寻欢 e973fea5f3
All checks were successful
continuous-integration/drone/push Build is passing
🔥 移除不必要的日志打印
2021-09-09 11:58:02 +08:00

79 lines
2.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
import (
"fmt"
gc "gateway/config"
"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())
// 设置接口地址
ext.HTTPUrl.Set(parentSpan, c.Request.RequestURI)
// 设置请求方式
ext.HTTPMethod.Set(parentSpan, c.Request.Method)
// 执行后续操作
c.Next()
// 设置返回状态码
ext.HTTPStatusCode.Set(parentSpan, uint16(c.Writer.Status()))
// 如果状态码大于299设置错误标签
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
}