-
-
Notifications
You must be signed in to change notification settings - Fork 106
/
withspan.go
93 lines (86 loc) · 2.61 KB
/
withspan.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package otelx
import (
"context"
"errors"
"fmt"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
// WithSpan wraps execution of f in a span identified by name.
//
// If f returns an error or panics, the span status will be set to the error
// state. The error (or panic) will be propagated unmodified.
//
// f will be wrapped in a child span by default. To make a new root span
// instead, pass the trace.WithNewRoot() option.
func WithSpan(ctx context.Context, name string, f func(context.Context) error, opts ...trace.SpanStartOption) (err error) {
ctx, span := trace.SpanFromContext(ctx).TracerProvider().Tracer("").Start(ctx, name, opts...)
defer func() {
defer span.End()
if r := recover(); r != nil {
setErrorStatusPanic(span, r)
panic(r)
} else if err != nil {
span.SetStatus(codes.Error, err.Error())
setErrorTags(span, err)
}
}()
return f(ctx)
}
// End finishes span, and automatically sets the error state if *err is not nil
// or during panicking.
//
// Usage:
//
// func Divide(ctx context.Context, numerator, denominator int) (ratio int, err error) {
// ctx, span := tracer.Start(ctx, "my-operation")
// defer otelx.End(span, &err)
// if denominator == 0 {
// return 0, errors.New("cannot divide by zero")
// }
// return numerator / denominator, nil
// }
func End(span trace.Span, err *error) {
defer span.End()
if r := recover(); r != nil {
setErrorStatusPanic(span, r)
panic(r)
}
if err == nil || *err == nil {
return
}
span.SetStatus(codes.Error, (*err).Error())
setErrorTags(span, *err)
}
func setErrorStatusPanic(span trace.Span, recovered any) {
switch e := recovered.(type) {
case error:
span.SetStatus(codes.Error, "panic: "+e.Error())
setErrorTags(span, e)
case string, fmt.Stringer:
span.SetStatus(codes.Error, fmt.Sprintf("panic: %v", e))
default:
span.SetStatus(codes.Error, "panic")
case nil:
// nothing
}
}
func setErrorTags(span trace.Span, err error) {
if e := interface{ Reason() string }(nil); errors.As(err, &e) {
span.SetAttributes(attribute.String("error.reason", e.Reason()))
}
if e := interface{ Debug() string }(nil); errors.As(err, &e) {
span.SetAttributes(attribute.String("error.debug", e.Debug()))
}
if e := interface{ ID() string }(nil); errors.As(err, &e) {
span.SetAttributes(attribute.String("error.id", e.ID()))
}
if e := interface{ Details() map[string]interface{} }(nil); errors.As(err, &e) {
for k, v := range e.Details() {
span.SetAttributes(attribute.String("error.details."+k, fmt.Sprintf("%v", v)))
}
}
}