Extend tracing and metrics
Tracing: OTLP gRPC/HTTP exporters with TLS and headers, parent-based sampling, W3C TraceContext/Baggage propagation, richer resource attributes, no-export mode without an endpoint, Disabled flag, and Trace/RecordError/TraceID helpers. Metrics: idempotent registration, Sub, GaugeFunc, CounterFunc, RegisterDBStats, OpenMetrics handler with trace exemplars. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
362267470e
commit
9a8ebe987b
6 files changed
+570
-41
No files matched your search
@@ -6,8 +6,10 @@ require (
|
||||
github.com/prometheus/client_golang v1.22.0
|
||||
go.opentelemetry.io/otel v1.35.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.35.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.35.0
|
||||
go.opentelemetry.io/otel/sdk v1.35.0
|
||||
go.opentelemetry.io/otel/trace v1.35.0
|
||||
google.golang.org/grpc v1.71.0
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -31,6 +33,5 @@ require (
|
||||
golang.org/x/text v0.22.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250218202821-56aae31c358a // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a // indirect
|
||||
google.golang.org/grpc v1.71.0 // indirect
|
||||
google.golang.org/protobuf v1.36.5 // indirect
|
||||
)
|
||||
@@ -45,6 +45,8 @@ go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0 h1:1fTNlAIJZGWLP5FVu0f
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0/go.mod h1:zjPK58DtkqQFn+YUMbx0M2XV3QgKU0gS9LeGohREyK4=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.35.0 h1:m639+BofXTvcY1q8CGs4ItwQarYtJPOWmVobfM1HpVI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.35.0/go.mod h1:LjReUci/F4BUyv+y4dwnq3h/26iNOeC3wAIqgvTIZVo=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.35.0 h1:xJ2qHD0C1BeYVTLLR9sX12+Qb95kfeD/byKj6Ky1pXg=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.35.0/go.mod h1:u5BF1xyjstDowA1R5QAO9JHzqK+ublenEW/dyqTjBVk=
|
||||
go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M=
|
||||
go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE=
|
||||
go.opentelemetry.io/otel/sdk v1.35.0 h1:iPctf8iprVySXSKJffSS79eOjl9pvxV9ZqOWT0QejKY=
|
||||
|
||||
+98
-16
@@ -1,10 +1,15 @@
|
||||
package obsx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/collectors"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// MetricsConfig configures the metrics factory.
|
||||
@@ -14,65 +19,142 @@ type MetricsConfig struct {
|
||||
}
|
||||
|
||||
// Metrics is a factory for creating Prometheus metrics with consistent naming.
|
||||
//
|
||||
// Creating a metric that is already registered with the same name, help and
|
||||
// labels returns the existing collector instead of panicking, so factories may
|
||||
// be called from several places (e.g. per-handler middleware) safely.
|
||||
type Metrics struct {
|
||||
cfg MetricsConfig
|
||||
registry *prometheus.Registry
|
||||
}
|
||||
|
||||
// NewMetrics creates a new Metrics factory.
|
||||
// NewMetrics creates a new Metrics factory backed by an isolated registry
|
||||
// pre-loaded with process and Go runtime collectors.
|
||||
func NewMetrics(cfg MetricsConfig) *Metrics {
|
||||
reg := prometheus.NewRegistry()
|
||||
reg.MustRegister(prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}))
|
||||
reg.MustRegister(prometheus.NewGoCollector())
|
||||
reg.MustRegister(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}))
|
||||
reg.MustRegister(collectors.NewGoCollector())
|
||||
return &Metrics{cfg: cfg, registry: reg}
|
||||
}
|
||||
|
||||
// Sub returns a factory sharing the same registry and namespace but using the
|
||||
// given subsystem, e.g. m.Sub("db").Counter("queries_total", ...) produces
|
||||
// "<namespace>_db_queries_total".
|
||||
func (m *Metrics) Sub(subsystem string) *Metrics {
|
||||
return &Metrics{
|
||||
cfg: MetricsConfig{Namespace: m.cfg.Namespace, Subsystem: subsystem},
|
||||
registry: m.registry,
|
||||
}
|
||||
}
|
||||
|
||||
// base returns a factory without namespace/subsystem sharing the registry.
|
||||
// Built-in instrumentation uses it so that standard metric names are identical
|
||||
// across all services.
|
||||
func (m *Metrics) base() *Metrics {
|
||||
return &Metrics{registry: m.registry}
|
||||
}
|
||||
|
||||
// Counter creates and registers a new CounterVec.
|
||||
func (m *Metrics) Counter(name, help string, labels ...string) *prometheus.CounterVec {
|
||||
c := prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
return register(m.registry, prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: m.cfg.Namespace,
|
||||
Subsystem: m.cfg.Subsystem,
|
||||
Name: name,
|
||||
Help: help,
|
||||
}, labels)
|
||||
m.registry.MustRegister(c)
|
||||
return c
|
||||
}, labels))
|
||||
}
|
||||
|
||||
// Histogram creates and registers a new HistogramVec.
|
||||
// nil buckets default to prometheus.DefBuckets.
|
||||
func (m *Metrics) Histogram(name, help string, buckets []float64, labels ...string) *prometheus.HistogramVec {
|
||||
if buckets == nil {
|
||||
buckets = prometheus.DefBuckets
|
||||
}
|
||||
h := prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
||||
return register(m.registry, prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Namespace: m.cfg.Namespace,
|
||||
Subsystem: m.cfg.Subsystem,
|
||||
Name: name,
|
||||
Help: help,
|
||||
Buckets: buckets,
|
||||
}, labels)
|
||||
m.registry.MustRegister(h)
|
||||
return h
|
||||
}, labels))
|
||||
}
|
||||
|
||||
// Gauge creates and registers a new GaugeVec.
|
||||
func (m *Metrics) Gauge(name, help string, labels ...string) *prometheus.GaugeVec {
|
||||
g := prometheus.NewGaugeVec(prometheus.GaugeOpts{
|
||||
return register(m.registry, prometheus.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Namespace: m.cfg.Namespace,
|
||||
Subsystem: m.cfg.Subsystem,
|
||||
Name: name,
|
||||
Help: help,
|
||||
}, labels)
|
||||
m.registry.MustRegister(g)
|
||||
return g
|
||||
}, labels))
|
||||
}
|
||||
|
||||
// GaugeFunc registers a gauge whose value is computed by fn on every scrape,
|
||||
// e.g. queue length or cache size.
|
||||
func (m *Metrics) GaugeFunc(name, help string, fn func() float64) {
|
||||
register[prometheus.Collector](m.registry, prometheus.NewGaugeFunc(prometheus.GaugeOpts{
|
||||
Namespace: m.cfg.Namespace,
|
||||
Subsystem: m.cfg.Subsystem,
|
||||
Name: name,
|
||||
Help: help,
|
||||
}, fn))
|
||||
}
|
||||
|
||||
// CounterFunc registers a counter whose value is computed by fn on every
|
||||
// scrape. fn must return monotonically increasing values.
|
||||
func (m *Metrics) CounterFunc(name, help string, fn func() float64) {
|
||||
register[prometheus.Collector](m.registry, prometheus.NewCounterFunc(prometheus.CounterOpts{
|
||||
Namespace: m.cfg.Namespace,
|
||||
Subsystem: m.cfg.Subsystem,
|
||||
Name: name,
|
||||
Help: help,
|
||||
}, fn))
|
||||
}
|
||||
|
||||
// RegisterDBStats exports database/sql connection pool statistics
|
||||
// (go_sql_* metrics) labeled with db_name=name.
|
||||
func (m *Metrics) RegisterDBStats(db *sql.DB, name string) {
|
||||
register(m.registry, collectors.NewDBStatsCollector(db, name))
|
||||
}
|
||||
|
||||
// Handler returns an http.Handler for the /metrics endpoint.
|
||||
// OpenMetrics format is negotiated when requested, which exposes trace
|
||||
// exemplars attached by the built-in instrumentation.
|
||||
func (m *Metrics) Handler() http.Handler {
|
||||
return promhttp.HandlerFor(m.registry, promhttp.HandlerOpts{})
|
||||
return promhttp.HandlerFor(m.registry, promhttp.HandlerOpts{
|
||||
EnableOpenMetrics: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Registry returns the underlying Prometheus registry.
|
||||
func (m *Metrics) Registry() *prometheus.Registry {
|
||||
return m.registry
|
||||
}
|
||||
|
||||
// register registers c, returning the already registered collector when an
|
||||
// identical one exists. It panics on any other registration error, matching
|
||||
// MustRegister semantics.
|
||||
func register[T prometheus.Collector](reg prometheus.Registerer, c T) T {
|
||||
if err := reg.Register(c); err != nil {
|
||||
var are prometheus.AlreadyRegisteredError
|
||||
if errors.As(err, &are) {
|
||||
if existing, ok := are.ExistingCollector.(T); ok {
|
||||
return existing
|
||||
}
|
||||
}
|
||||
panic(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// observe records v, attaching the trace ID from ctx as an exemplar when the
|
||||
// span is sampled.
|
||||
func observe(ctx context.Context, o prometheus.Observer, v float64) {
|
||||
if sc := trace.SpanContextFromContext(ctx); sc.IsSampled() {
|
||||
if eo, ok := o.(prometheus.ExemplarObserver); ok {
|
||||
eo.ObserveWithExemplar(v, prometheus.Labels{"trace_id": sc.TraceID().String()})
|
||||
return
|
||||
}
|
||||
}
|
||||
o.Observe(v)
|
||||
}
|
||||
@@ -1,11 +1,17 @@
|
||||
package obsx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
)
|
||||
|
||||
func TestMetrics_Counter(t *testing.T) {
|
||||
@@ -62,3 +68,75 @@ func scrape(t *testing.T, m *Metrics) string {
|
||||
body, _ := io.ReadAll(w.Body)
|
||||
return string(body)
|
||||
}
|
||||
|
||||
func TestMetrics_Sub(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{Namespace: "app"})
|
||||
m.Sub("db").Counter("queries_total", "Queries").WithLabelValues().Inc()
|
||||
|
||||
if !strings.Contains(scrape(t, m), "app_db_queries_total 1") {
|
||||
t.Error("Sub factory must share the registry and namespace")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetrics_IdempotentRegistration(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
a := m.Counter("events_total", "Events", "kind")
|
||||
b := m.Counter("events_total", "Events", "kind")
|
||||
if a != b {
|
||||
t.Error("registering an identical metric must return the existing collector")
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if recover() == nil {
|
||||
t.Error("conflicting registration must panic")
|
||||
}
|
||||
}()
|
||||
m.Counter("events_total", "Events", "other_label")
|
||||
}
|
||||
|
||||
func TestMetrics_Funcs(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{Namespace: "q"})
|
||||
m.GaugeFunc("depth", "Queue depth", func() float64 { return 7 })
|
||||
m.CounterFunc("processed_total", "Processed", func() float64 { return 3 })
|
||||
|
||||
body := scrape(t, m)
|
||||
if !strings.Contains(body, "q_depth 7") || !strings.Contains(body, "q_processed_total 3") {
|
||||
t.Errorf("func metrics missing:\n%s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetrics_DBStats(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
// sql.OpenDB does not dial, so no real database is needed.
|
||||
db := sql.OpenDB(nopConnector{})
|
||||
defer db.Close()
|
||||
m.RegisterDBStats(db, "main")
|
||||
m.RegisterDBStats(db, "main") // idempotent
|
||||
|
||||
if !strings.Contains(scrape(t, m), `go_sql_max_open_connections{db_name="main"}`) {
|
||||
t.Error("db stats missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetrics_Exemplars(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
h := m.Histogram("latency_seconds", "Latency", nil)
|
||||
|
||||
tp := sdktrace.NewTracerProvider()
|
||||
ctx, span := tp.Tracer("t").Start(context.Background(), "op")
|
||||
observe(ctx, h.WithLabelValues(), 0.2)
|
||||
span.End()
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
r := httptest.NewRequest("GET", "/metrics", nil)
|
||||
r.Header.Set("Accept", "application/openmetrics-text; version=1.0.0")
|
||||
m.Handler().ServeHTTP(w, r)
|
||||
if !strings.Contains(w.Body.String(), `# {trace_id="`+span.SpanContext().TraceID().String()+`"} 0.2`) {
|
||||
t.Errorf("exemplar missing from OpenMetrics output:\n%s", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
type nopConnector struct{}
|
||||
|
||||
func (nopConnector) Connect(context.Context) (driver.Conn, error) { return nil, errors.New("no db") }
|
||||
func (nopConnector) Driver() driver.Driver { return nil }
|
||||
@@ -2,66 +2,247 @@ package obsx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
|
||||
"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.26.0"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"go.opentelemetry.io/otel/trace/noop"
|
||||
"google.golang.org/grpc/credentials"
|
||||
)
|
||||
|
||||
// instrumentationName is the OpenTelemetry instrumentation scope used by
|
||||
// obsx helpers and built-in instrumentation.
|
||||
const instrumentationName = "obsx"
|
||||
|
||||
// Supported OTLP protocols for TracerConfig.Protocol.
|
||||
const (
|
||||
ProtocolGRPC = "grpc"
|
||||
ProtocolHTTP = "http"
|
||||
)
|
||||
|
||||
// TracerConfig configures the OpenTelemetry tracer.
|
||||
type TracerConfig struct {
|
||||
ServiceName string
|
||||
ServiceVersion string
|
||||
Endpoint string // OTLP gRPC endpoint, e.g. "localhost:4317"
|
||||
Sampler float64 // sampling ratio, default: 1.0 (sample everything)
|
||||
Environment string // deployment.environment resource attribute, e.g. "production"
|
||||
|
||||
// Endpoint is the OTLP collector endpoint: "host:port" or a URL
|
||||
// ("https://collector:4318"). When empty, the standard
|
||||
// OTEL_EXPORTER_OTLP_ENDPOINT / OTEL_EXPORTER_OTLP_TRACES_ENDPOINT
|
||||
// variables are used; if those are unset too, spans are still created and
|
||||
// propagated (trace IDs appear in logs) but not exported.
|
||||
Endpoint string
|
||||
Protocol string // ProtocolGRPC (default) or ProtocolHTTP
|
||||
TLS *tls.Config // nil: plaintext connection for "host:port" endpoints
|
||||
Headers map[string]string // extra headers sent to the collector, e.g. auth tokens
|
||||
|
||||
Sampler float64 // parent-based ratio sampling, default: 1.0 (sample everything)
|
||||
Disabled bool // install a no-op provider: no spans are recorded or propagated
|
||||
Attributes map[string]string // extra resource attributes
|
||||
|
||||
// Exporter overrides the OTLP exporter (e.g. stdouttrace or an in-memory
|
||||
// exporter in tests). Endpoint, Protocol, TLS and Headers are ignored.
|
||||
Exporter sdktrace.SpanExporter
|
||||
}
|
||||
|
||||
func (c *TracerConfig) defaults() {
|
||||
if c.Sampler <= 0 {
|
||||
c.Sampler = 1.0
|
||||
}
|
||||
if c.Protocol == "" {
|
||||
c.Protocol = ProtocolGRPC
|
||||
}
|
||||
}
|
||||
|
||||
// SetupTracer initializes an OpenTelemetry tracer provider with OTLP gRPC exporter.
|
||||
// Returns a shutdown function that must be called on application exit.
|
||||
// SetupTracer initializes an OpenTelemetry tracer provider with an OTLP
|
||||
// exporter and registers it, together with W3C TraceContext and Baggage
|
||||
// propagators, as the global provider.
|
||||
// Returns a shutdown function that must be called on application exit to
|
||||
// flush pending spans.
|
||||
func SetupTracer(ctx context.Context, cfg TracerConfig) (shutdown func(context.Context) error, err error) {
|
||||
tp, shutdown, err := newTracerProvider(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
setGlobalTracing(tp)
|
||||
return shutdown, nil
|
||||
}
|
||||
|
||||
func newTracerProvider(ctx context.Context, cfg TracerConfig) (trace.TracerProvider, func(context.Context) error, error) {
|
||||
cfg.defaults()
|
||||
|
||||
exporter, err := otlptracegrpc.New(ctx,
|
||||
otlptracegrpc.WithEndpoint(cfg.Endpoint),
|
||||
otlptracegrpc.WithInsecure(),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if cfg.Disabled {
|
||||
return noop.NewTracerProvider(), func(context.Context) error { return nil }, nil
|
||||
}
|
||||
|
||||
attrs := []resource.Option{
|
||||
resource.WithAttributes(semconv.ServiceName(cfg.ServiceName)),
|
||||
exporter, err := newExporter(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("obsx: create trace exporter: %w", err)
|
||||
}
|
||||
|
||||
res, err := newResource(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("obsx: create trace resource: %w", err)
|
||||
}
|
||||
|
||||
opts := []sdktrace.TracerProviderOption{
|
||||
sdktrace.WithResource(res),
|
||||
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(cfg.Sampler))),
|
||||
}
|
||||
if exporter != nil {
|
||||
opts = append(opts, sdktrace.WithBatcher(exporter))
|
||||
}
|
||||
|
||||
tp := sdktrace.NewTracerProvider(opts...)
|
||||
return tp, tp.Shutdown, nil
|
||||
}
|
||||
|
||||
// newExporter returns nil (and no error) when no endpoint is configured.
|
||||
func newExporter(ctx context.Context, cfg TracerConfig) (sdktrace.SpanExporter, error) {
|
||||
if cfg.Exporter != nil {
|
||||
return cfg.Exporter, nil
|
||||
}
|
||||
if cfg.Endpoint == "" &&
|
||||
os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT") == "" &&
|
||||
os.Getenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT") == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
isURL := strings.Contains(cfg.Endpoint, "://")
|
||||
|
||||
switch cfg.Protocol {
|
||||
case ProtocolGRPC:
|
||||
var opts []otlptracegrpc.Option
|
||||
switch {
|
||||
case isURL:
|
||||
opts = append(opts, otlptracegrpc.WithEndpointURL(cfg.Endpoint))
|
||||
case cfg.Endpoint != "":
|
||||
opts = append(opts, otlptracegrpc.WithEndpoint(cfg.Endpoint))
|
||||
}
|
||||
switch {
|
||||
case cfg.TLS != nil:
|
||||
opts = append(opts, otlptracegrpc.WithTLSCredentials(credentials.NewTLS(cfg.TLS)))
|
||||
case cfg.Endpoint != "" && !isURL:
|
||||
opts = append(opts, otlptracegrpc.WithInsecure())
|
||||
}
|
||||
if len(cfg.Headers) > 0 {
|
||||
opts = append(opts, otlptracegrpc.WithHeaders(cfg.Headers))
|
||||
}
|
||||
return otlptracegrpc.New(ctx, opts...)
|
||||
|
||||
case ProtocolHTTP, "http/protobuf":
|
||||
var opts []otlptracehttp.Option
|
||||
switch {
|
||||
case isURL:
|
||||
opts = append(opts, otlptracehttp.WithEndpointURL(cfg.Endpoint))
|
||||
case cfg.Endpoint != "":
|
||||
opts = append(opts, otlptracehttp.WithEndpoint(cfg.Endpoint))
|
||||
}
|
||||
switch {
|
||||
case cfg.TLS != nil:
|
||||
opts = append(opts, otlptracehttp.WithTLSClientConfig(cfg.TLS))
|
||||
case cfg.Endpoint != "" && !isURL:
|
||||
opts = append(opts, otlptracehttp.WithInsecure())
|
||||
}
|
||||
if len(cfg.Headers) > 0 {
|
||||
opts = append(opts, otlptracehttp.WithHeaders(cfg.Headers))
|
||||
}
|
||||
return otlptracehttp.New(ctx, opts...)
|
||||
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported OTLP protocol %q (want %q or %q)", cfg.Protocol, ProtocolGRPC, ProtocolHTTP)
|
||||
}
|
||||
}
|
||||
|
||||
func newResource(ctx context.Context, cfg TracerConfig) (*resource.Resource, error) {
|
||||
var attrs []attribute.KeyValue
|
||||
if cfg.ServiceName != "" {
|
||||
attrs = append(attrs, semconv.ServiceName(cfg.ServiceName))
|
||||
}
|
||||
if cfg.ServiceVersion != "" {
|
||||
attrs = append(attrs, resource.WithAttributes(semconv.ServiceVersion(cfg.ServiceVersion)))
|
||||
attrs = append(attrs, semconv.ServiceVersion(cfg.ServiceVersion))
|
||||
}
|
||||
if cfg.Environment != "" {
|
||||
attrs = append(attrs, semconv.DeploymentEnvironment(cfg.Environment))
|
||||
}
|
||||
if host, err := os.Hostname(); err == nil {
|
||||
attrs = append(attrs, semconv.ServiceInstanceID(host))
|
||||
}
|
||||
for k, v := range cfg.Attributes {
|
||||
attrs = append(attrs, attribute.String(k, v))
|
||||
}
|
||||
|
||||
res, err := resource.New(ctx, attrs...)
|
||||
if err != nil {
|
||||
// Later options win: explicit configuration overrides OTEL_RESOURCE_ATTRIBUTES.
|
||||
res, err := resource.New(ctx,
|
||||
resource.WithTelemetrySDK(),
|
||||
resource.WithHost(),
|
||||
resource.WithFromEnv(),
|
||||
resource.WithAttributes(attrs...),
|
||||
)
|
||||
if res == nil {
|
||||
return nil, err
|
||||
}
|
||||
// Partial detector failures still yield a usable resource.
|
||||
return res, nil
|
||||
}
|
||||
|
||||
tp := sdktrace.NewTracerProvider(
|
||||
sdktrace.WithBatcher(exporter),
|
||||
sdktrace.WithResource(res),
|
||||
sdktrace.WithSampler(sdktrace.TraceIDRatioBased(cfg.Sampler)),
|
||||
)
|
||||
|
||||
func setGlobalTracing(tp trace.TracerProvider) {
|
||||
otel.SetTracerProvider(tp)
|
||||
|
||||
return tp.Shutdown, nil
|
||||
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
|
||||
propagation.TraceContext{},
|
||||
propagation.Baggage{},
|
||||
))
|
||||
}
|
||||
|
||||
// StartSpan starts a new span using the global tracer provider.
|
||||
func StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span) {
|
||||
return otel.Tracer("obsx").Start(ctx, name, opts...)
|
||||
return otel.Tracer(instrumentationName).Start(ctx, name, opts...)
|
||||
}
|
||||
|
||||
// Trace runs fn inside a new span. A non-nil error returned by fn is recorded
|
||||
// on the span and the span status is set to Error.
|
||||
func Trace(ctx context.Context, name string, fn func(ctx context.Context) error) error {
|
||||
ctx, span := StartSpan(ctx, name)
|
||||
defer span.End()
|
||||
|
||||
err := fn(ctx)
|
||||
if err != nil {
|
||||
failSpan(span, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// RecordError records err on the span stored in ctx and marks the span as
|
||||
// failed. It is a no-op when err is nil or ctx carries no recording span.
|
||||
func RecordError(ctx context.Context, err error, opts ...trace.EventOption) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
failSpan(trace.SpanFromContext(ctx), err, opts...)
|
||||
}
|
||||
|
||||
// TraceID returns the hex trace ID of the span in ctx, or "" if there is none.
|
||||
// Useful for returning a correlation ID to clients.
|
||||
func TraceID(ctx context.Context) string {
|
||||
sc := trace.SpanContextFromContext(ctx)
|
||||
if !sc.HasTraceID() {
|
||||
return ""
|
||||
}
|
||||
return sc.TraceID().String()
|
||||
}
|
||||
|
||||
func failSpan(span trace.Span, err error, opts ...trace.EventOption) {
|
||||
span.RecordError(err, opts...)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
}
|
||||
+185
@@ -2,13 +2,17 @@ package obsx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/sdk/resource"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
"go.opentelemetry.io/otel/sdk/trace/tracetest"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
func setupTestTracer(t *testing.T) *tracetest.InMemoryExporter {
|
||||
@@ -122,3 +126,184 @@ func TestStartSpan_CreatesSpan(t *testing.T) {
|
||||
t.Errorf("expected span name 'my-operation', got %q", spans[0].Name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewExporter_Selection(t *testing.T) {
|
||||
t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "")
|
||||
t.Setenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "")
|
||||
ctx := context.Background()
|
||||
|
||||
exp, err := newExporter(ctx, TracerConfig{Protocol: ProtocolGRPC})
|
||||
if err != nil || exp != nil {
|
||||
t.Errorf("no endpoint: exporter = %v, err = %v; want nil, nil", exp, err)
|
||||
}
|
||||
|
||||
for _, cfg := range []TracerConfig{
|
||||
{Protocol: ProtocolGRPC, Endpoint: "localhost:4317"},
|
||||
{Protocol: ProtocolGRPC, Endpoint: "https://collector:4317", Headers: map[string]string{"x-token": "t"}},
|
||||
{Protocol: ProtocolHTTP, Endpoint: "localhost:4318"},
|
||||
{Protocol: "http/protobuf", Endpoint: "http://localhost:4318/v1/traces"},
|
||||
} {
|
||||
exp, err := newExporter(ctx, cfg)
|
||||
if err != nil || exp == nil {
|
||||
t.Errorf("%+v: exporter = %v, err = %v", cfg, exp, err)
|
||||
continue
|
||||
}
|
||||
_ = exp.Shutdown(ctx)
|
||||
}
|
||||
|
||||
if _, err := newExporter(ctx, TracerConfig{Protocol: "thrift", Endpoint: "x:1"}); err == nil {
|
||||
t.Error("expected error for unsupported protocol")
|
||||
}
|
||||
|
||||
t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4317")
|
||||
exp, err = newExporter(ctx, TracerConfig{Protocol: ProtocolGRPC})
|
||||
if err != nil || exp == nil {
|
||||
t.Errorf("env endpoint: exporter = %v, err = %v", exp, err)
|
||||
} else {
|
||||
_ = exp.Shutdown(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewTracerProvider_NoExporterStillTraces(t *testing.T) {
|
||||
t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "")
|
||||
t.Setenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "")
|
||||
tp, shutdown, err := newTracerProvider(context.Background(), TracerConfig{ServiceName: "local"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer shutdown(context.Background())
|
||||
|
||||
ctx, span := tp.Tracer("t").Start(context.Background(), "op")
|
||||
defer span.End()
|
||||
if TraceID(ctx) == "" {
|
||||
t.Error("spans must have trace IDs even without an exporter (log correlation)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewTracerProvider_Disabled(t *testing.T) {
|
||||
tp, shutdown, err := newTracerProvider(context.Background(), TracerConfig{Disabled: true, Endpoint: "localhost:4317"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := shutdown(context.Background()); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
ctx, span := tp.Tracer("t").Start(context.Background(), "op")
|
||||
span.End()
|
||||
if TraceID(ctx) != "" {
|
||||
t.Error("disabled tracing must not create spans")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewTracerProvider_ParentBasedSampling(t *testing.T) {
|
||||
exp := tracetest.NewInMemoryExporter()
|
||||
tp, shutdown, err := newTracerProvider(context.Background(), TracerConfig{Sampler: 0.000001, Exporter: exp})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer shutdown(context.Background())
|
||||
|
||||
// A sampled parent from an upstream service must be honored.
|
||||
parent := trace.NewSpanContext(trace.SpanContextConfig{
|
||||
TraceID: trace.TraceID{1},
|
||||
SpanID: trace.SpanID{1},
|
||||
TraceFlags: trace.FlagsSampled,
|
||||
Remote: true,
|
||||
})
|
||||
_, span := tp.Tracer("t").Start(trace.ContextWithRemoteSpanContext(context.Background(), parent), "child")
|
||||
if !span.SpanContext().IsSampled() {
|
||||
t.Error("child of a sampled remote parent must be sampled")
|
||||
}
|
||||
span.End()
|
||||
}
|
||||
|
||||
func TestNewResource_Attributes(t *testing.T) {
|
||||
res, err := newResource(context.Background(), TracerConfig{
|
||||
ServiceName: "svc",
|
||||
ServiceVersion: "v1",
|
||||
Environment: "prod",
|
||||
Attributes: map[string]string{"team": "payments"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := map[string]string{}
|
||||
for _, kv := range res.Attributes() {
|
||||
got[string(kv.Key)] = kv.Value.Emit()
|
||||
}
|
||||
for k, v := range map[string]string{
|
||||
"service.name": "svc",
|
||||
"service.version": "v1",
|
||||
"deployment.environment": "prod",
|
||||
"team": "payments",
|
||||
} {
|
||||
if got[k] != v {
|
||||
t.Errorf("resource %s = %q, want %q", k, got[k], v)
|
||||
}
|
||||
}
|
||||
if got["service.instance.id"] == "" {
|
||||
t.Error("service.instance.id not set")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrace_RecordsError(t *testing.T) {
|
||||
prev := otel.GetTracerProvider()
|
||||
t.Cleanup(func() { otel.SetTracerProvider(prev) })
|
||||
exp := setupTestTracer(t)
|
||||
|
||||
want := errors.New("failed")
|
||||
var inner context.Context
|
||||
err := Trace(context.Background(), "work", func(ctx context.Context) error {
|
||||
inner = ctx
|
||||
return want
|
||||
})
|
||||
if !errors.Is(err, want) {
|
||||
t.Fatalf("Trace returned %v", err)
|
||||
}
|
||||
if TraceID(inner) == "" {
|
||||
t.Error("fn context carries no span")
|
||||
}
|
||||
|
||||
spans := exp.GetSpans()
|
||||
if len(spans) != 1 || spans[0].Status.Code != codes.Error || len(spans[0].Events) != 1 {
|
||||
t.Errorf("unexpected spans: %+v", spans)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordError(t *testing.T) {
|
||||
prev := otel.GetTracerProvider()
|
||||
t.Cleanup(func() { otel.SetTracerProvider(prev) })
|
||||
exp := setupTestTracer(t)
|
||||
|
||||
ctx, span := StartSpan(context.Background(), "op")
|
||||
RecordError(ctx, nil)
|
||||
RecordError(ctx, errors.New("bad"))
|
||||
span.End()
|
||||
|
||||
s := exp.GetSpans()[0]
|
||||
if s.Status.Code != codes.Error || len(s.Events) != 1 {
|
||||
t.Errorf("unexpected span: status=%v events=%d", s.Status.Code, len(s.Events))
|
||||
}
|
||||
if TraceID(context.Background()) != "" {
|
||||
t.Error("TraceID without span must be empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupTracer_SetsPropagator(t *testing.T) {
|
||||
prevTP, prevProp := otel.GetTracerProvider(), otel.GetTextMapPropagator()
|
||||
t.Cleanup(func() {
|
||||
otel.SetTracerProvider(prevTP)
|
||||
otel.SetTextMapPropagator(prevProp)
|
||||
})
|
||||
|
||||
shutdown, err := SetupTracer(context.Background(), TracerConfig{Exporter: tracetest.NewInMemoryExporter()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer shutdown(context.Background())
|
||||
|
||||
fields := otel.GetTextMapPropagator().Fields()
|
||||
if !slices.Contains(fields, "traceparent") || !slices.Contains(fields, "baggage") {
|
||||
t.Errorf("propagator fields = %v, want traceparent and baggage", fields)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user