github.com/gogf/gf@v1.16.9/database/gredis/gredis_conn_tracing.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gredis 8 9 import ( 10 "context" 11 "fmt" 12 "github.com/gogf/gf" 13 "github.com/gogf/gf/internal/json" 14 "github.com/gogf/gf/net/gtrace" 15 "go.opentelemetry.io/otel" 16 "go.opentelemetry.io/otel/attribute" 17 "go.opentelemetry.io/otel/codes" 18 "go.opentelemetry.io/otel/trace" 19 ) 20 21 // tracingItem holds the information for redis tracing. 22 type tracingItem struct { 23 err error 24 commandName string 25 arguments []interface{} 26 costMilli int64 27 } 28 29 const ( 30 tracingInstrumentName = "github.com/gogf/gf/database/gredis" 31 tracingAttrRedisHost = "redis.host" 32 tracingAttrRedisPort = "redis.port" 33 tracingAttrRedisDb = "redis.db" 34 tracingEventRedisExecution = "redis.execution" 35 tracingEventRedisExecutionCommand = "redis.execution.command" 36 tracingEventRedisExecutionCost = "redis.execution.cost" 37 tracingEventRedisExecutionArguments = "redis.execution.arguments" 38 ) 39 40 // addTracingItem checks and adds redis tracing information to OpenTelemetry. 41 func (c *Conn) addTracingItem(item *tracingItem) { 42 if !gtrace.IsTracingInternal() || !gtrace.IsActivated(c.ctx) { 43 return 44 } 45 tr := otel.GetTracerProvider().Tracer( 46 tracingInstrumentName, 47 trace.WithInstrumentationVersion(gf.VERSION), 48 ) 49 ctx := c.ctx 50 if ctx == nil { 51 ctx = context.Background() 52 } 53 _, span := tr.Start(ctx, "Redis."+item.commandName, trace.WithSpanKind(trace.SpanKindInternal)) 54 defer span.End() 55 if item.err != nil { 56 span.SetStatus(codes.Error, fmt.Sprintf(`%+v`, item.err)) 57 } 58 span.SetAttributes(gtrace.CommonLabels()...) 59 span.SetAttributes( 60 attribute.String(tracingAttrRedisHost, c.redis.config.Host), 61 attribute.Int(tracingAttrRedisPort, c.redis.config.Port), 62 attribute.Int(tracingAttrRedisDb, c.redis.config.Db), 63 ) 64 jsonBytes, _ := json.Marshal(item.arguments) 65 span.AddEvent(tracingEventRedisExecution, trace.WithAttributes( 66 attribute.String(tracingEventRedisExecutionCommand, item.commandName), 67 attribute.String(tracingEventRedisExecutionCost, fmt.Sprintf(`%d ms`, item.costMilli)), 68 attribute.String(tracingEventRedisExecutionArguments, string(jsonBytes)), 69 )) 70 }