gredis_conn_tracing.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. package gredis
  7. import (
  8. "context"
  9. "fmt"
  10. "github.com/gogf/gf"
  11. "github.com/gogf/gf/internal/json"
  12. "github.com/gogf/gf/net/gtrace"
  13. "go.opentelemetry.io/otel"
  14. "go.opentelemetry.io/otel/attribute"
  15. "go.opentelemetry.io/otel/codes"
  16. "go.opentelemetry.io/otel/trace"
  17. )
  18. // tracingItem holds the information for redis tracing.
  19. type tracingItem struct {
  20. err error
  21. commandName string
  22. arguments []interface{}
  23. costMilli int64
  24. }
  25. const (
  26. tracingInstrumentName = "github.com/gogf/gf/database/gredis"
  27. tracingAttrRedisHost = "redis.host"
  28. tracingAttrRedisPort = "redis.port"
  29. tracingAttrRedisDb = "redis.db"
  30. tracingEventRedisExecution = "redis.execution"
  31. tracingEventRedisExecutionCommand = "redis.execution.command"
  32. tracingEventRedisExecutionCost = "redis.execution.cost"
  33. tracingEventRedisExecutionArguments = "redis.execution.arguments"
  34. )
  35. // addTracingItem checks and adds redis tracing information to OpenTelemetry.
  36. func (c *Conn) addTracingItem(item *tracingItem) {
  37. if !gtrace.IsTracingInternal() || !gtrace.IsActivated(c.ctx) {
  38. return
  39. }
  40. tr := otel.GetTracerProvider().Tracer(
  41. tracingInstrumentName,
  42. trace.WithInstrumentationVersion(gf.VERSION),
  43. )
  44. ctx := c.ctx
  45. if ctx == nil {
  46. ctx = context.Background()
  47. }
  48. _, span := tr.Start(ctx, "Redis."+item.commandName, trace.WithSpanKind(trace.SpanKindInternal))
  49. defer span.End()
  50. if item.err != nil {
  51. span.SetStatus(codes.Error, fmt.Sprintf(`%+v`, item.err))
  52. }
  53. span.SetAttributes(gtrace.CommonLabels()...)
  54. span.SetAttributes(
  55. attribute.String(tracingAttrRedisHost, c.redis.config.Host),
  56. attribute.Int(tracingAttrRedisPort, c.redis.config.Port),
  57. attribute.Int(tracingAttrRedisDb, c.redis.config.Db),
  58. )
  59. jsonBytes, _ := json.Marshal(item.arguments)
  60. span.AddEvent(tracingEventRedisExecution, trace.WithAttributes(
  61. attribute.String(tracingEventRedisExecutionCommand, item.commandName),
  62. attribute.String(tracingEventRedisExecutionCost, fmt.Sprintf(`%d ms`, item.costMilli)),
  63. attribute.String(tracingEventRedisExecutionArguments, string(jsonBytes)),
  64. ))
  65. }