79 lines
1.7 KiB
Go
79 lines
1.7 KiB
Go
|
package middleware
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"github.com/gin-gonic/gin"
|
||
|
"github.com/opentracing/opentracing-go"
|
||
|
"github.com/opentracing/opentracing-go/ext"
|
||
|
"github.com/uber/jaeger-client-go/config"
|
||
|
"io"
|
||
|
)
|
||
|
|
||
|
const (
|
||
|
AppName = "gateway"
|
||
|
JaegerHostPort = "192.168.0.124:6831"
|
||
|
)
|
||
|
|
||
|
func OpenTracing() gin.HandlerFunc {
|
||
|
return func(c *gin.Context) {
|
||
|
var parentSpan opentracing.Span
|
||
|
|
||
|
tracer, closer := NewJaegerTracer(AppName)
|
||
|
defer closer.Close()
|
||
|
|
||
|
spCtx, err := opentracing.GlobalTracer().Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(c.Request.Header))
|
||
|
|
||
|
if err != nil {
|
||
|
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)
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
//var Tracer opentracing.Tracer
|
||
|
|
||
|
func NewJaegerTracer(serviceName string) (opentracing.Tracer, io.Closer) {
|
||
|
cfg := &config.Configuration{
|
||
|
Sampler: &config.SamplerConfig{
|
||
|
Type: "const", //固定采样
|
||
|
Param: 1, //1=全采样、0=不采样
|
||
|
},
|
||
|
|
||
|
Reporter: &config.ReporterConfig{
|
||
|
LogSpans: true,
|
||
|
LocalAgentHostPort: JaegerHostPort,
|
||
|
},
|
||
|
|
||
|
ServiceName: serviceName,
|
||
|
}
|
||
|
|
||
|
tracer, closer, err := cfg.NewTracer()
|
||
|
if err != nil {
|
||
|
return nil, nil
|
||
|
}
|
||
|
opentracing.SetGlobalTracer(tracer)
|
||
|
//Tracer = tracer
|
||
|
return tracer, closer
|
||
|
}
|