-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(trace): 支持传入任意函数实现 CALL trace 追踪
- Loading branch information
Showing
3 changed files
with
51 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
package trace | ||
|
||
import ( | ||
"context" | ||
|
||
"go.opentelemetry.io/otel" | ||
"go.opentelemetry.io/otel/codes" | ||
"go.opentelemetry.io/otel/trace" | ||
) | ||
|
||
// Call | ||
// 基于otel规范实现一个 call 函数,用于注入任意函数实现链路追踪 | ||
func Call[T any](ctx context.Context, spanName string, f func(ctx context.Context) (T, error)) (T, error) { | ||
// 基于otel规范实现一个 call 函数,用于注入任意函数实现链路追踪 | ||
tr := otel.Tracer("xpkg.trace") | ||
ctx, span := tr.Start(ctx, spanName, | ||
trace.WithSpanKind(trace.SpanKindInternal), | ||
) | ||
defer span.End() | ||
reply, err := f(ctx) | ||
if err != nil { | ||
span.RecordError(err) | ||
span.SetStatus(codes.Error, err.Error()) | ||
} else { | ||
span.SetStatus(codes.Ok, "OK") | ||
} | ||
return reply, err | ||
} |