common/tracing/tracing.go

101 lines
2.6 KiB
Go
Raw Normal View History

2023-10-14 10:30:19 +00:00
package tracing
import (
"context"
"os"
"go.ntppool.org/common/logger"
"go.ntppool.org/common/version"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource"
otelsdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.21.0"
"go.opentelemetry.io/otel/trace"
)
// https://github.com/open-telemetry/opentelemetry-go/blob/main/exporters/otlp/otlptrace/otlptracehttp/example_test.go
2023-10-14 11:20:29 +00:00
func Tracer() trace.Tracer {
2023-10-14 10:30:19 +00:00
traceProvider := otel.GetTracerProvider()
2023-10-14 11:20:29 +00:00
return traceProvider.Tracer("ntppool-tracer")
2023-10-14 10:30:19 +00:00
}
type TracerConfig struct {
ServiceName string
Environment string
}
func InitTracer(ctx context.Context, cfg *TracerConfig) error {
log := logger.Setup()
// exporter, err := srv.newStdoutExporter(os.Stdout)
var err error
var exporter otelsdktrace.SpanExporter
2023-10-22 04:49:51 +00:00
if otlpEndPoint := os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT"); len(otlpEndPoint) > 0 {
2023-10-14 10:30:19 +00:00
exporter, err = newOLTPExporter(ctx)
}
if err != nil {
return err
}
if exporter != nil {
tp := otelsdktrace.NewTracerProvider(
otelsdktrace.WithSampler(otelsdktrace.AlwaysSample()),
otelsdktrace.WithBatcher(exporter),
otelsdktrace.WithResource(newResource(cfg)),
)
otel.SetTracerProvider(tp)
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))
} else {
log.Warn("tracing not configured")
}
return nil
}
func newOLTPExporter(ctx context.Context) (otelsdktrace.SpanExporter, error) {
client := otlptracehttp.NewClient()
exporter, err := otlptrace.New(ctx, client)
if err != nil {
logger.Setup().Error("creating OTLP trace exporter", "err", err)
}
return exporter, err
}
// func (srv *Server) newStdoutExporter(w io.Writer) (sdktrace.SpanExporter, error) {
// return stdouttrace.New(
// stdouttrace.WithWriter(w),
// // Use human-readable output.
// stdouttrace.WithPrettyPrint(),
// // Do not print timestamps for the demo.
// stdouttrace.WithoutTimestamps(),
// )
// }
// newResource returns a resource describing this application.
func newResource(cfg *TracerConfig) *resource.Resource {
r, err := resource.Merge(
resource.Default(),
resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceNameKey.String(cfg.ServiceName),
semconv.ServiceVersionKey.String(version.Version()),
attribute.String("environment", cfg.Environment),
),
)
if err != nil {
panic(err)
}
return r
}