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
@@ -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())
|
||||
}
|
||||
Reference in new issue
Block a user