gitee.com/woood2/luca@v1.0.4/internal/trace/zipkin.go (about) 1 package trace 2 3 import ( 4 "context" 5 "gitee.com/woood2/luca/internal/conf" 6 "github.com/gin-gonic/gin" 7 "github.com/go-kit/kit/tracing/zipkin" 8 "github.com/go-kit/kit/transport/grpc" 9 opzipkin "github.com/openzipkin/zipkin-go" 10 "github.com/openzipkin/zipkin-go/reporter" 11 "github.com/openzipkin/zipkin-go/reporter/http" 12 "log" 13 ) 14 15 var ( 16 rpt reporter.Reporter 17 zkTracer *opzipkin.Tracer 18 zkClientTrace grpc.ClientOption 19 zkServerTrace grpc.ServerOption 20 ) 21 22 /** 23 在测试环境,可以开启httpReporter 24 在生产环境,建议使用NoopReporter,避免性能问题 25 如有必要,也可考虑kafka+elastic-search方案,但实施起来比较复杂,前期暂不引入 26 */ 27 func Open(c *conf.Zipkin) { 28 if c.ReporterAddr == "" { 29 rpt = reporter.NewNoopReporter() 30 } else { 31 rpt = http.NewReporter(c.ReporterAddr) 32 } 33 var err error 34 zkTracer, err = opzipkin.NewTracer(rpt) 35 if err != nil { 36 log.Panicln(err) 37 } 38 zkClientTrace = zipkin.GRPCClientTrace(zkTracer) 39 zkServerTrace = zipkin.GRPCServerTrace(zkTracer) 40 } 41 42 func ClientTrace() grpc.ClientOption { 43 return zkClientTrace 44 } 45 46 func ServerTrace() grpc.ServerOption { 47 return zkServerTrace 48 } 49 50 func Close() { 51 rpt.Close() 52 } 53 54 func StartSpan(name string, options ...opzipkin.SpanOption) opzipkin.Span { 55 return zkTracer.StartSpan(name, options...) 56 } 57 58 func NewGinContext(c *gin.Context, s opzipkin.Span) { 59 c.Set(spanKey, s) 60 } 61 62 func SpanFromGinContext(c *gin.Context) opzipkin.Span { 63 if s, ok := c.Get(spanKey); ok { 64 span := s.(opzipkin.Span) 65 return span 66 } else { 67 return nil 68 } 69 } 70 71 func Ctx(c *gin.Context) context.Context { 72 span := SpanFromGinContext(c) 73 return opzipkin.NewContext(context.Background(), span) 74 } 75 76 func ID(ctx context.Context) string { 77 traceID := "-" 78 span := opzipkin.SpanFromContext(ctx) 79 if span != nil { 80 traceID = span.Context().TraceID.String() 81 } 82 return traceID 83 } 84 85 func GinID(c *gin.Context) string { 86 span := SpanFromGinContext(c) 87 traceID := "-" 88 if span != nil { 89 traceID = span.Context().TraceID.String() 90 } 91 return traceID 92 } 93 94 95 func SpanKey() string { 96 return spanKey 97 } 98 99 var spanKey = "gin-zipkin-span-key"