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
2c83b28342
commit
022db31878
7 files changed
+572
-55
No files matched your search
@@ -2,90 +2,207 @@ 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"
|
||||
)
|
||||
|
||||
// Supported OTLP protocols for TracerConfig.Protocol.
|
||||
const (
|
||||
ProtocolGRPC = "grpc"
|
||||
ProtocolHTTP = "http"
|
||||
)
|
||||
|
||||
// TracerConfig configures the OpenTelemetry tracer.
|
||||
type TracerConfig struct {
|
||||
ServiceName string
|
||||
ServiceVersion string
|
||||
// Endpoint is the OTLP gRPC endpoint, e.g. "localhost:4317". When empty,
|
||||
// the standard OTEL_EXPORTER_OTLP_* environment variables apply.
|
||||
// Environment is the deployment.environment resource attribute, e.g. "production".
|
||||
Environment string
|
||||
// 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 is ProtocolGRPC (default) or ProtocolHTTP.
|
||||
Protocol string
|
||||
// Insecure disables TLS for the OTLP connection (local collectors, sidecars).
|
||||
Insecure bool
|
||||
// TLS is a custom TLS configuration for the OTLP connection; nil uses the
|
||||
// system defaults. Ignored when Insecure is set.
|
||||
TLS *tls.Config
|
||||
// Headers are sent with every export request, e.g. for authentication.
|
||||
Headers map[string]string
|
||||
// Sampler is the ratio of root traces to sample, default: 1.0 (everything).
|
||||
// Child spans always follow the decision of their parent.
|
||||
Sampler float64
|
||||
// Attributes are extra resource attributes, e.g. deployment environment.
|
||||
// Disabled installs a no-op provider: no spans are recorded or propagated.
|
||||
Disabled bool
|
||||
// Attributes are extra resource attributes.
|
||||
Attributes []attribute.KeyValue
|
||||
// Exporter overrides the OTLP exporter (e.g. stdouttrace or an in-memory
|
||||
// exporter in tests). Endpoint, Protocol, Insecure, 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 an OTLP gRPC
|
||||
// SetupTracer initializes an OpenTelemetry tracer provider with an OTLP
|
||||
// exporter and installs it, together with W3C TraceContext and Baggage
|
||||
// propagators, as the OpenTelemetry globals.
|
||||
// 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) {
|
||||
cfg.defaults()
|
||||
|
||||
var opts []otlptracegrpc.Option
|
||||
if cfg.Endpoint != "" {
|
||||
opts = append(opts, otlptracegrpc.WithEndpoint(cfg.Endpoint))
|
||||
}
|
||||
if cfg.Insecure {
|
||||
opts = append(opts, otlptracegrpc.WithInsecure())
|
||||
}
|
||||
if len(cfg.Headers) > 0 {
|
||||
opts = append(opts, otlptracegrpc.WithHeaders(cfg.Headers))
|
||||
}
|
||||
exporter, err := otlptracegrpc.New(ctx, opts...)
|
||||
tp, shutdown, err := newTracerProvider(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
attrs := append([]attribute.KeyValue{semconv.ServiceName(cfg.ServiceName)}, cfg.Attributes...)
|
||||
if cfg.ServiceVersion != "" {
|
||||
attrs = append(attrs, semconv.ServiceVersion(cfg.ServiceVersion))
|
||||
}
|
||||
res, err := resource.New(ctx,
|
||||
resource.WithFromEnv(), // OTEL_RESOURCE_ATTRIBUTES; config below wins
|
||||
resource.WithTelemetrySDK(),
|
||||
resource.WithAttributes(attrs...),
|
||||
)
|
||||
if err != nil {
|
||||
_ = exporter.Shutdown(ctx)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tp := sdktrace.NewTracerProvider(
|
||||
sdktrace.WithBatcher(exporter),
|
||||
sdktrace.WithResource(res),
|
||||
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(cfg.Sampler))),
|
||||
)
|
||||
|
||||
otel.SetTracerProvider(tp)
|
||||
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
|
||||
propagation.TraceContext{}, propagation.Baggage{},
|
||||
))
|
||||
return shutdown, nil
|
||||
}
|
||||
|
||||
return tp.Shutdown, nil
|
||||
func newTracerProvider(ctx context.Context, cfg TracerConfig) (trace.TracerProvider, func(context.Context) error, error) {
|
||||
cfg.defaults()
|
||||
|
||||
if cfg.Disabled {
|
||||
return noop.NewTracerProvider(), func(context.Context) error { return nil }, nil
|
||||
}
|
||||
|
||||
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 {
|
||||
if exporter != nil {
|
||||
_ = exporter.Shutdown(ctx)
|
||||
}
|
||||
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.Insecure:
|
||||
opts = append(opts, otlptracegrpc.WithInsecure())
|
||||
case cfg.TLS != nil:
|
||||
opts = append(opts, otlptracegrpc.WithTLSCredentials(credentials.NewTLS(cfg.TLS)))
|
||||
}
|
||||
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.Insecure:
|
||||
opts = append(opts, otlptracehttp.WithInsecure())
|
||||
case cfg.TLS != nil:
|
||||
opts = append(opts, otlptracehttp.WithTLSClientConfig(cfg.TLS))
|
||||
}
|
||||
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, 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))
|
||||
}
|
||||
attrs = append(attrs, cfg.Attributes...)
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
const tracerName = "git.codelab.vc/pkg/obsx"
|
||||
@@ -94,3 +211,40 @@ const tracerName = "git.codelab.vc/pkg/obsx"
|
||||
func StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span) {
|
||||
return otel.Tracer(tracerName).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