Skip to content

Instantly share code, notes, and snippets.

@floyola

floyola/trace.go Secret

Created Nov 11, 2021
Embed
What would you like to do?
Opentelemetry tracer initilization
package main
import (
"context"
"crypto/tls"
"go.opentelemetry.io/otel"
"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"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
)
// tracingConfig is used to configure the driver used to send traces to the Otel Collector
type tracingConfig struct {
CollectorAddress string
Environment string
ServiceName string
ServiceVersion string
}
var (
// traceExporter exports trace data in the OTLP wire format.
traceExporter *otlptrace.Exporter
// tracerProvider holds a new and configured sdktrace.TracerProvider.
tracerProvider *sdktrace.TracerProvider
)
// initTracer initializes and configures a trace provider in order to generate traces and send them to a collector.
func initTracer(ctx context.Context, conf tracingConfig) error {
var err error
traceExporter, err = otlptracehttp.New(ctx,
otlptracehttp.WithTLSClientConfig(
&tls.Config{InsecureSkipVerify: true},
),
otlptracehttp.WithEndpoint(conf.CollectorAddress),
otlptracehttp.WithCompression(otlptracehttp.GzipCompression),
)
if err != nil {
return err
}
res, err := resource.New(ctx,
resource.WithAttributes(
semconv.ServiceNameKey.String(conf.ServiceName),
semconv.DeploymentEnvironmentKey.String(conf.Environment),
semconv.ServiceVersionKey.String(conf.ServiceVersion),
),
)
if err != nil {
return err
}
bsp := sdktrace.NewBatchSpanProcessor(traceExporter)
tracerProvider = sdktrace.NewTracerProvider(
sdktrace.WithSampler(sdktrace.AlwaysSample()),
sdktrace.WithResource(res),
sdktrace.WithSpanProcessor(bsp),
)
otel.SetTracerProvider(tracerProvider)
otel.SetTextMapPropagator(
propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{},
propagation.Baggage{},
))
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment