go-app/pkg/otel/ctx.go
2025-01-04 12:24:42 -05:00

55 lines
1.0 KiB
Go

package otel
import (
"context"
"errors"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
)
type otelCtxKey uint8
const (
ctxKeyTracer otelCtxKey = iota
ctxKeyMeter
)
func MustTracerFromCtx(ctx context.Context) trace.Tracer {
ctxData := ctx.Value(ctxKeyTracer)
if ctxData == nil {
panic(errors.New("no tracer found in context"))
}
tracer, ok := ctxData.(trace.Tracer)
if !ok {
panic(errors.New("invalid tracer found in context"))
}
return tracer
}
func AddTracerToCtx(ctx context.Context, tracer trace.Tracer) context.Context {
ctx = context.WithValue(ctx, ctxKeyTracer, tracer)
return ctx
}
func MustMeterFromCtx(ctx context.Context) metric.Meter {
ctxData := ctx.Value(ctxKeyMeter)
if ctxData == nil {
panic(errors.New("no meter found in context"))
}
meter, ok := ctxData.(metric.Meter)
if !ok {
panic(errors.New("invalid meter found in context"))
}
return meter
}
func AddMeterToCtx(ctx context.Context, meter metric.Meter) context.Context {
ctx = context.WithValue(ctx, ctxKeyMeter, meter)
return ctx
}