From 0ab2d12c390cdd4293dbe50fe93c09ca1e2fe039 Mon Sep 17 00:00:00 2001 From: SoXX Date: Mon, 26 Aug 2024 13:00:51 +0200 Subject: [PATCH] feat(telemetry): added base functions added base function for OTEL Setup --- pkg/telemetry/metrics.go | 28 +++++++++++++++++++++++++++ pkg/telemetry/otlp.go | 19 +++++++++++++++++++ pkg/telemetry/tracing.go | 41 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 88 insertions(+) create mode 100644 pkg/telemetry/metrics.go create mode 100644 pkg/telemetry/otlp.go create mode 100644 pkg/telemetry/tracing.go diff --git a/pkg/telemetry/metrics.go b/pkg/telemetry/metrics.go new file mode 100644 index 0000000..1535460 --- /dev/null +++ b/pkg/telemetry/metrics.go @@ -0,0 +1,28 @@ +package telemetry + +import ( + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/exporters/prometheus" + "go.opentelemetry.io/otel/sdk/metric" +) + +func SetupMeterProvider(plugName string) error { + res, err := newResource(plugName) + + if err != nil { + return err + } + + promReader, err := prometheus.New() + + if err != nil { + return err + } + + meterProvider := metric.NewMeterProvider( + metric.WithResource(res), + metric.WithReader(promReader), + ) + otel.SetMeterProvider(meterProvider) + return nil +} diff --git a/pkg/telemetry/otlp.go b/pkg/telemetry/otlp.go new file mode 100644 index 0000000..bba29c5 --- /dev/null +++ b/pkg/telemetry/otlp.go @@ -0,0 +1,19 @@ +package telemetry + +import ( + "go.opentelemetry.io/otel/sdk/resource" + semconv "go.opentelemetry.io/otel/semconv/v1.26.0" +) + +func newResource(serviceName string) (*resource.Resource, error) { + otelResource, err := resource.Merge(resource.Default(), + resource.NewWithAttributes(semconv.SchemaURL, + semconv.ServiceName(serviceName), + )) + + if err != nil { + return nil, err + } + + return otelResource, nil +} diff --git a/pkg/telemetry/tracing.go b/pkg/telemetry/tracing.go new file mode 100644 index 0000000..1679033 --- /dev/null +++ b/pkg/telemetry/tracing.go @@ -0,0 +1,41 @@ +package telemetry + +import ( + "context" + + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" + "go.opentelemetry.io/otel/sdk/trace" +) + +func SetupTraceProvider(ctx context.Context, plugName string) error { + res, err := newResource(plugName) + + if err != nil { + return err + } + + exporter, err := traceExporter(ctx) + + if err != nil { + return err + } + + provider := trace.NewTracerProvider( + trace.WithResource(res), + trace.WithBatcher(exporter), + ) + + otel.SetTracerProvider(provider) + return nil +} + +func traceExporter(ctx context.Context) (trace.SpanExporter, error) { + spanExporter, err := otlptracegrpc.New(ctx) + + if err != nil { + return nil, err + } + + return spanExporter, nil +}