Documentation
¶
Overview ¶
Package otelcore holds the export plumbing shared by the observability signals: the Exporter that says where a signal goes, the service Resource, the typed per-signal Settings, OTLP/HTTP endpoint parsing, and the shared-plus-per-signal ResolveSettings merge. Callers build Settings in code or from configuration and hand them to the logs, metrics, and tracing packages.
Collector sends to an OpenTelemetry collector and is the only exporter configuration can describe. Slog prints each signal as slog records, for reading on a terminal or in a file with no collector running. Writer writes OTLP JSON lines to any io.Writer, for another tool to read. Long-lived callers can depend on SettingsSource to observe when a resolved settings snapshot changes without coupling to a particular configuration container.
Index ¶
Examples ¶
Constants ¶
const ( SignalTracing = "tracing" SignalMetrics = "metrics" SignalLogs = "logs" )
Signal names, used both as the per-signal config sub-key (telemetry.<signal>.*) and as the OTLP URL path suffix.
const MaxEndpointLength = 2048
MaxEndpointLength caps the length, in bytes, of an OTLP endpoint URL. Legitimate collector endpoints are well under 200 bytes; 2 KiB is generous for proxy configurations and far short of any pathological input.
const Root = "telemetry"
Root is the config key prefix shared by the analytics pipeline and the observability signals.
Variables ¶
var ErrInvalidEndpoint = errors.NewSentinel("observability.invalid_endpoint", "invalid OTLP endpoint")
ErrInvalidEndpoint is returned when an OTLP endpoint fails validation. Callers can distinguish validation failures from other errors via errors.Is.
Functions ¶
Types ¶
type Collector ¶ added in v0.6.0
Collector sends each signal to an OpenTelemetry collector over OTLP/HTTP. Endpoint is the collector's base URL, and the signal's path (/v1/metrics, /v1/traces, /v1/logs) is appended to it. An empty Endpoint lets the SDK read the OTEL_EXPORTER_OTLP_* environment variables, while Headers and Insecure still apply.
func (Collector) LogExporter ¶ added in v0.6.0
LogExporter builds an otlploghttp exporter for c.
func (Collector) MetricExporter ¶ added in v0.6.0
MetricExporter builds an otlpmetrichttp exporter for c.
func (Collector) SpanExporter ¶ added in v0.6.0
SpanExporter builds an otlptracehttp exporter for c.
type Config ¶
type Config struct {
Endpoint string `mapstructure:"endpoint" yaml:"endpoint" json:"endpoint"`
Headers map[string]string `mapstructure:"headers" yaml:"headers" json:"headers"`
Insecure bool `mapstructure:"insecure" yaml:"insecure" json:"insecure"`
}
Config holds shared OTLP settings that can be overlaid by each signal.
type Endpoint ¶
type Endpoint struct {
Host string // host:port, e.g. "collector:4318"
BasePath string // path prefix the per-signal suffix is appended to
Insecure bool // plaintext OTLP (http scheme, or an explicit insecure flag)
Headers map[string]string // exporter headers, e.g. an auth token
}
Endpoint is a parsed OTLP/HTTP base URL, split into the components every signal exporter needs. Each signal appends its own suffix to BasePath: "/v1/traces", "/v1/metrics" or "/v1/logs".
func ParseEndpoint ¶
ParseEndpoint splits an OTLP/HTTP base URL into exporter components. An http scheme, or insecure being true, marks the endpoint as plaintext — use that only for a local collector.
The endpoint is validated fail-fast, mirroring chat.ValidateBaseURL: an empty, over-long, control-character-bearing, unparseable, schemeless or hostless URL is rejected with an error wrapping ErrInvalidEndpoint, as is any URL carrying userinfo (`http://user:pass@host`) — credentials belong in headers, never the URL. Only http and https schemes are accepted (OTLP/HTTP commonly allows both; http is plaintext and marks the endpoint insecure). A malformed endpoint thus surfaces immediately rather than failing later or silently at export time.
type Exporter ¶ added in v0.6.0
type Exporter interface {
MetricExporter(ctx context.Context) (sdkmetric.Exporter, error)
SpanExporter(ctx context.Context) (sdktrace.SpanExporter, error)
LogExporter(ctx context.Context) (sdklog.Exporter, error)
}
Exporter is where a signal's telemetry goes. Each signal's NewProvider calls the method for its own signal, so an implementation builds the SDK exporter for each one. Collector, Slog and Writer are the three this module provides; an implementation with nothing for a signal returns an error there.
func Slog ¶ added in v0.6.0
Slog writes each signal as ordinary slog records through l: one record per metric data point, per ended span and span event, and per log record. It is for reading, so the record shape is documented but not a wire contract.
Don't pass the logs signal a logger whose handler is logs.Handler: each record would be exported back into itself.
Example ¶
Metrics printed as log lines, with no collector. The time is dropped only so the output below is stable.
package main
import (
"context"
"log/slog"
"os"
"gitlab.com/phpboyscout/go/observability/instrument"
"gitlab.com/phpboyscout/go/observability/metrics"
"gitlab.com/phpboyscout/go/observability/otelcore"
)
func main() {
ctx := context.Background()
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
},
}))
mp, err := metrics.NewProvider(ctx, otelcore.Resource("checkout", "0.1.0"),
otelcore.Settings{Enabled: true, Exporter: otelcore.Slog(logger)})
if err != nil {
panic(err)
}
cache, err := instrument.NewCache(mp.Meter("checkout"), "orders")
if err != nil {
panic(err)
}
cache.Hit(ctx)
cache.Hit(ctx)
cache.Miss(ctx)
cache.SetSize(2)
_ = mp.Shutdown(ctx)
}
Output: level=INFO msg=metric name=cache.operations unit={operation} kind=sum value=2 monotonic=true attrs.cache.name=orders attrs.cache.result=hit level=INFO msg=metric name=cache.operations unit={operation} kind=sum value=1 monotonic=true attrs.cache.name=orders attrs.cache.result=miss level=INFO msg=metric name=cache.size unit={entry} kind=gauge value=2 attrs.cache.name=orders level=INFO msg=metric name=cache.capacity unit={entry} kind=gauge value=0 attrs.cache.name=orders
type Settings ¶
type Settings struct {
// Enabled records the configured switch. No NewProvider reads it: a caller
// that wants a signal off doesn't build its provider.
Enabled bool
// Exporter is where the signal goes. Nil means Collector{}, so the SDK reads
// the OTEL_EXPORTER_OTLP_* environment variables.
Exporter Exporter
}
Settings is the resolved destination for a single signal.
func ResolveSettings ¶
func ResolveSettings(shared Config, signal SignalConfig, overrides SignalOverrides) Settings
ResolveSettings overlays per-signal settings on shared telemetry settings and returns them as a Collector, since config only describes a collector. Enabled is always per-signal only.
type SettingsSource ¶
SettingsSource exposes the latest resolved signal settings without coupling callers to a particular configuration container or adapter.
type SignalConfig ¶
type SignalConfig struct {
Enabled bool `mapstructure:"enabled" yaml:"enabled" json:"enabled"`
Endpoint string `mapstructure:"endpoint" yaml:"endpoint" json:"endpoint"`
Headers map[string]string `mapstructure:"headers" yaml:"headers" json:"headers"`
Insecure bool `mapstructure:"insecure" yaml:"insecure" json:"insecure"`
}
SignalConfig holds per-signal OTLP settings.
type SignalOverrides ¶
SignalOverrides records which per-signal fields were explicitly supplied by an adapter and should override shared config.