otelcore

package
v0.6.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 31 Imported by: 1

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

View Source
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.

View Source
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.

View Source
const Root = "telemetry"

Root is the config key prefix shared by the analytics pipeline and the observability signals.

Variables

View Source
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

func Resource

func Resource(name, version string) *resource.Resource

Resource builds the OTel resource that identifies the emitting service. name and version populate the service.name and service.version semantic-convention attributes that appear as labels on every signal in the backend.

Types

type Collector added in v0.6.0

type Collector struct {
	Endpoint string
	Headers  map[string]string
	Insecure bool
}

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

func (c Collector) LogExporter(ctx context.Context) (sdklog.Exporter, error)

LogExporter builds an otlploghttp exporter for c.

func (Collector) MetricExporter added in v0.6.0

func (c Collector) MetricExporter(ctx context.Context) (sdkmetric.Exporter, error)

MetricExporter builds an otlpmetrichttp exporter for c.

func (Collector) SpanExporter added in v0.6.0

func (c Collector) SpanExporter(ctx context.Context) (sdktrace.SpanExporter, error)

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

func ParseEndpoint(rawURL string, insecure bool, headers map[string]string) (Endpoint, error)

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

func Slog(l *slog.Logger) Exporter

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

func Writer added in v0.6.0

func Writer(w io.Writer) Exporter

Writer writes each export to w as one line of the OTLP File Exporter format: OTLP JSON, readable by the collector's otlpjsonfile receiver. The format allows one signal per file, so give each signal its own Writer.

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

type SettingsSource interface {
	Current() *Settings
	Version() uint64
}

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

type SignalOverrides struct {
	Endpoint bool
	Headers  bool
	Insecure bool
}

SignalOverrides records which per-signal fields were explicitly supplied by an adapter and should override shared config.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL