forked from mtusi2026/mtusi2026lab6
feat(telemetry): add graceful Shutdown, W3C propagation and sampler configuration from env
This commit is contained in:
@@ -2,6 +2,7 @@ package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
@@ -13,6 +14,7 @@ import (
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
otellog "go.opentelemetry.io/otel/sdk/log"
|
||||
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
|
||||
"go.opentelemetry.io/otel/sdk/resource"
|
||||
@@ -101,9 +103,32 @@ func Setup(ctx context.Context, cfg SetupConfig) (*Providers, error) {
|
||||
otel.SetTracerProvider(tp)
|
||||
otel.SetMeterProvider(mp)
|
||||
|
||||
// Пропагация контекста через W3C Trace Context и Baggage
|
||||
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
|
||||
propagation.TraceContext{}, propagation.Baggage{},
|
||||
))
|
||||
|
||||
return &Providers{Tracer: tp, Meter: mp, Logs: lp}, nil
|
||||
}
|
||||
|
||||
// Shutdown корректно завершает провайдеры, отправляя сохран. данные.
|
||||
func (p *Providers) Shutdown(ctx context.Context) error {
|
||||
if p == nil {
|
||||
return nil
|
||||
}
|
||||
var errs []error
|
||||
if p.Logs != nil {
|
||||
errs = append(errs, p.Logs.Shutdown(ctx))
|
||||
}
|
||||
if p.Meter != nil {
|
||||
errs = append(errs, p.Meter.Shutdown(ctx))
|
||||
}
|
||||
if p.Tracer != nil {
|
||||
errs = append(errs, p.Tracer.Shutdown(ctx))
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
func disabled() bool {
|
||||
return strings.EqualFold(os.Getenv("OTEL_SDK_DISABLED"), "true")
|
||||
}
|
||||
@@ -127,3 +152,31 @@ func metricInterval() time.Duration {
|
||||
}
|
||||
return time.Duration(ms) * time.Millisecond
|
||||
}
|
||||
|
||||
func samplerFromEnv() sdktrace.Sampler {
|
||||
name := strings.ToLower(strings.TrimSpace(os.Getenv("OTEL_TRACES_SAMPLER")))
|
||||
switch name {
|
||||
case "always_off":
|
||||
return sdktrace.NeverSample()
|
||||
case "always_on":
|
||||
return sdktrace.AlwaysSample()
|
||||
case "traceidratio":
|
||||
return sdktrace.TraceIDRatioBased(ratioArg(0.1))
|
||||
case "parentbased_traceidratio":
|
||||
return sdktrace.ParentBased(sdktrace.TraceIDRatioBased(ratioArg(0.1)))
|
||||
default:
|
||||
return sdktrace.ParentBased(sdktrace.AlwaysSample())
|
||||
}
|
||||
}
|
||||
|
||||
func ratioArg(def float64) float64 {
|
||||
v := os.Getenv("OTEL_TRACES_SAMPLER_ARG")
|
||||
if v == "" {
|
||||
return def
|
||||
}
|
||||
f, err := strconv.ParseFloat(v, 64)
|
||||
if err != nil || f < 0 || f > 1 {
|
||||
return def
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user