tracing.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 tracing provides some utility functions for tracing functionality.
  7. package tracing
  8. import (
  9. "math"
  10. "time"
  11. "go.opentelemetry.io/otel/trace"
  12. "github.com/gogf/gf/v2/container/gtype"
  13. "github.com/gogf/gf/v2/encoding/gbinary"
  14. "github.com/gogf/gf/v2/util/grand"
  15. )
  16. var (
  17. randomInitSequence = int32(grand.Intn(math.MaxInt32))
  18. sequence = gtype.NewInt32(randomInitSequence)
  19. )
  20. // NewIDs creates and returns a new trace and span ID.
  21. func NewIDs() (traceID trace.TraceID, spanID trace.SpanID) {
  22. return NewTraceID(), NewSpanID()
  23. }
  24. // NewTraceID creates and returns a trace ID.
  25. func NewTraceID() (traceID trace.TraceID) {
  26. var (
  27. timestampNanoBytes = gbinary.EncodeInt64(time.Now().UnixNano())
  28. sequenceBytes = gbinary.EncodeInt32(sequence.Add(1))
  29. randomBytes = grand.B(4)
  30. )
  31. copy(traceID[:], timestampNanoBytes)
  32. copy(traceID[8:], sequenceBytes)
  33. copy(traceID[12:], randomBytes)
  34. return
  35. }
  36. // NewSpanID creates and returns a span ID.
  37. func NewSpanID() (spanID trace.SpanID) {
  38. copy(spanID[:], gbinary.EncodeInt64(time.Now().UnixNano()/1e3))
  39. copy(spanID[4:], grand.B(4))
  40. return
  41. }