79 lines
2.0 KiB
Go
79 lines
2.0 KiB
Go
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
|
||
}
|