trace.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. //@File trace.go
  2. //@Time 2022/05/16
  3. //@Author #Suyghur,
  4. package trace
  5. import (
  6. "context"
  7. gozerotrace "github.com/zeromicro/go-zero/core/trace"
  8. "go.opentelemetry.io/otel"
  9. "go.opentelemetry.io/otel/attribute"
  10. "go.opentelemetry.io/otel/propagation"
  11. oteltrace "go.opentelemetry.io/otel/trace"
  12. "net/http"
  13. "ylink/comm/utils"
  14. )
  15. func StartTrace(ctx context.Context, name string, callback func(context.Context), kv ...attribute.KeyValue) {
  16. tracer := otel.GetTracerProvider().Tracer(gozerotrace.TraceName)
  17. spanCtx, span := tracer.Start(ctx, name, oteltrace.WithSpanKind(oteltrace.SpanKindInternal), oteltrace.WithAttributes(kv...))
  18. defer span.End()
  19. callback(spanCtx)
  20. }
  21. func RunOnTracing(traceId string, callback func(ctx context.Context), kv ...attribute.KeyValue) {
  22. propagator := otel.GetTextMapPropagator()
  23. tracer := otel.GetTracerProvider().Tracer(gozerotrace.TraceName)
  24. header := http.Header{}
  25. if len(traceId) != 0 {
  26. header.Set("x-trace-id", traceId)
  27. }
  28. ctx := propagator.Extract(context.Background(), propagation.HeaderCarrier(header))
  29. spanName := utils.CallerFuncName()
  30. traceIdFromHex, _ := oteltrace.TraceIDFromHex(traceId)
  31. ctx = oteltrace.ContextWithSpanContext(ctx, oteltrace.NewSpanContext(oteltrace.SpanContextConfig{
  32. TraceID: traceIdFromHex,
  33. }))
  34. spanCtx, span := tracer.Start(ctx, spanName, oteltrace.WithSpanKind(oteltrace.SpanKindConsumer), oteltrace.WithAttributes(kv...))
  35. defer span.End()
  36. propagator.Inject(spanCtx, propagation.HeaderCarrier(header))
  37. callback(spanCtx)
  38. }