47 lines
908 B
Go
47 lines
908 B
Go
|
|
package otelsetup
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
|
||
|
|
"go.opentelemetry.io/otel"
|
||
|
|
"go.opentelemetry.io/otel/trace"
|
||
|
|
)
|
||
|
|
|
||
|
|
type Span interface {
|
||
|
|
Context() context.Context
|
||
|
|
Finish()
|
||
|
|
}
|
||
|
|
|
||
|
|
type span struct {
|
||
|
|
otelSpan trace.Span
|
||
|
|
ctx context.Context
|
||
|
|
}
|
||
|
|
|
||
|
|
func (s *span) Finish() {
|
||
|
|
s.otelSpan.End()
|
||
|
|
}
|
||
|
|
|
||
|
|
func (s *span) Context() context.Context {
|
||
|
|
return s.ctx
|
||
|
|
}
|
||
|
|
|
||
|
|
func StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, Span) {
|
||
|
|
ctx, otelSpan := otel.Tracer("").Start(ctx, name, opts...)
|
||
|
|
|
||
|
|
return ctx, &span{
|
||
|
|
otelSpan: otelSpan,
|
||
|
|
ctx: ctx,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
type TraceHandlerFunc func(ctx context.Context, name string) (context.Context, func())
|
||
|
|
|
||
|
|
func (t TraceHandlerFunc) Trace(tx context.Context, name string) (context.Context, func()) {
|
||
|
|
return t(tx, name)
|
||
|
|
}
|
||
|
|
|
||
|
|
func Trace(ctx context.Context, name string) (context.Context, func()) {
|
||
|
|
ctx, s := StartSpan(ctx, name)
|
||
|
|
return ctx, s.Finish
|
||
|
|
}
|