package tracer import ( "context" "path" "runtime" "strings" "github.com/spf13/viper" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/trace" ) type AdditionSpanLayerInfo struct { LayerName string FuncName string FilePath string Line int } func StartSpan(ctx context.Context, libName, spanName string, additionSpanLayer ...AdditionSpanLayerInfo) (context.Context, trace.Span) { var ( finalFunc string finalFile string finalLine int finalLayer string ) if len(additionSpanLayer) > 0 { finalFunc = additionSpanLayer[0].FuncName finalFile = additionSpanLayer[0].FilePath finalLine = additionSpanLayer[0].Line finalLayer = additionSpanLayer[0].LayerName } else { pc, file, line, ok := runtime.Caller(1) if ok { finalFile = file finalLine = line if fn := runtime.FuncForPC(pc); fn != nil { finalFunc = fn.Name() } finalLayer = "undefined" } } tracer := otel.Tracer(path.Join(viper.GetString("server.application"), libName)) return tracer.Start(ctx, path.Join(libName, spanName), trace.WithAttributes( attribute.String("code.function", finalFunc), attribute.String("code.file", ShortPath(finalFile)), attribute.Int("code.line", finalLine), attribute.String("trace.layer", finalLayer), )) } func ShortPath(path string) string { parts := strings.Split(path, "cms-server/") if len(parts) > 1 { return "cms-server/" + parts[1] } return path }