observops

package
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Jan 19, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package observops provides a unified interface for general service observability platforms. It abstracts common functionality across providers using OpenTelemetry as the core instrumentation layer.

This package complements the llmops package (which handles LLM-specific observability) by providing general service observability for:

  • Metrics (counters, gauges, histograms)
  • Traces (distributed tracing with spans)
  • Logs (structured logging correlated with traces)

Supported backends include:

  • OTLP (OpenTelemetry Protocol) - vendor-agnostic
  • New Relic
  • Datadog
  • Prometheus (metrics only)
  • Jaeger (traces only)

Quick Start

Import the provider you want to use:

import (
	"github.com/agentplexus/omniobserve/observops"
	_ "github.com/agentplexus/omniobserve/observops/otlp"     // OTLP exporter
	// or
	_ "github.com/agentplexus/omniobserve/observops/newrelic" // New Relic
	// or
	_ "github.com/agentplexus/omniobserve/observops/datadog"  // Datadog
)

Then open a provider:

provider, err := observops.Open("otlp",
	observops.WithEndpoint("localhost:4317"),
	observops.WithServiceName("my-service"),
)
if err != nil {
	log.Fatal(err)
}
defer provider.Shutdown(context.Background())

Use metrics:

counter, _ := provider.Meter().Counter("requests_total",
	observops.WithDescription("Total number of requests"),
)
counter.Add(ctx, 1, observops.WithAttributes(
	observops.Attribute("method", "GET"),
	observops.Attribute("path", "/api/users"),
))

Use tracing:

ctx, span := provider.Tracer().Start(ctx, "ProcessRequest")
defer span.End()
span.SetAttributes(observops.Attribute("user.id", "123"))

Use structured logging:

provider.Logger().Info(ctx, "Request processed",
	observops.LogAttribute("user_id", "123"),
	observops.LogAttribute("duration_ms", 45),
)

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrProviderDisabled indicates the provider is disabled.
	ErrProviderDisabled = errors.New("observops: provider is disabled")

	// ErrMissingServiceName indicates a service name is required but not provided.
	ErrMissingServiceName = errors.New("observops: service name is required")

	// ErrMissingEndpoint indicates an endpoint is required but not provided.
	ErrMissingEndpoint = errors.New("observops: endpoint is required")

	// ErrMissingAPIKey indicates an API key is required but not provided.
	ErrMissingAPIKey = errors.New("observops: API key is required")

	// ErrShutdown indicates the provider has been shut down.
	ErrShutdown = errors.New("observops: provider has been shut down")

	// ErrNotSupported indicates the operation is not supported by this provider.
	ErrNotSupported = errors.New("observops: operation not supported")
)

Sentinel errors for common failure cases.

Functions

func ApplyEventOptions

func ApplyEventOptions(opts ...EventOption) *eventConfig

ApplyEventOptions applies event options and returns the config.

func ApplyMetricOptions

func ApplyMetricOptions(opts ...MetricOption) *metricConfig

ApplyMetricOptions applies metric options and returns the config.

func ApplyRecordOptions

func ApplyRecordOptions(opts ...RecordOption) *recordConfig

ApplyRecordOptions applies record options and returns the config.

func ApplySpanEndOptions

func ApplySpanEndOptions(opts ...SpanEndOption) *spanEndConfig

ApplySpanEndOptions applies span end options and returns the config.

func ApplySpanOptions

func ApplySpanOptions(opts ...SpanOption) *spanConfig

ApplySpanOptions applies span options and returns the config.

func GetDescription

func GetDescription(opts ...MetricOption) string

GetDescription returns the description from metric options.

func GetEndTimestamp

func GetEndTimestamp(opts ...SpanEndOption) *time.Time

GetEndTimestamp returns the timestamp from span end options.

func GetEventTimestamp

func GetEventTimestamp(opts ...EventOption) *time.Time

GetEventTimestamp returns the timestamp from event options.

func GetUnit

func GetUnit(opts ...MetricOption) string

GetUnit returns the unit from metric options.

func Providers

func Providers() []string

Providers returns a sorted list of the names of the registered providers.

func Register

func Register(name string, factory ProviderFactory)

Register makes a provider available by the provided name. If Register is called twice with the same name or if factory is nil, it panics.

func RegisterInfo

func RegisterInfo(info ProviderInfo)

RegisterInfo registers metadata about a provider. This is optional and used for discovery/documentation.

func Unregister

func Unregister(name string)

Unregister removes a provider from the registry. This is primarily useful for testing.

func UnregisterAll

func UnregisterAll()

UnregisterAll removes all providers from the registry. This is primarily useful for testing.

func WrapError

func WrapError(provider, op string, err error) error

WrapError wraps an error with provider context.

func WrapNotSupported

func WrapNotSupported(provider, feature string) error

WrapNotSupported wraps an error indicating a feature is not supported.

Types

type Capability

type Capability string

Capability represents a specific feature a provider may support.

const (
	// CapabilityMetrics indicates support for metrics.
	CapabilityMetrics Capability = "metrics"
	// CapabilityTraces indicates support for distributed tracing.
	CapabilityTraces Capability = "traces"
	// CapabilityLogs indicates support for structured logging.
	CapabilityLogs Capability = "logs"
	// CapabilityExemplars indicates support for metric exemplars.
	CapabilityExemplars Capability = "exemplars"
	// CapabilityResourceDetection indicates support for automatic resource detection.
	CapabilityResourceDetection Capability = "resource_detection"
	// CapabilityBatching indicates support for telemetry batching.
	CapabilityBatching Capability = "batching"
	// CapabilitySampling indicates support for trace sampling.
	CapabilitySampling Capability = "sampling"
)

type CapabilityChecker

type CapabilityChecker interface {
	// HasCapability checks if the provider supports a given capability.
	HasCapability(cap Capability) bool

	// Capabilities returns all supported capabilities.
	Capabilities() []Capability
}

CapabilityChecker allows querying provider capabilities.

type ClientOption

type ClientOption func(*Config)

ClientOption configures a provider client.

func WithAPIKey

func WithAPIKey(apiKey string) ClientOption

WithAPIKey sets the API key for authentication.

func WithBatchSize

func WithBatchSize(size int) ClientOption

WithBatchSize sets the maximum number of items per batch.

func WithBatchTimeout

func WithBatchTimeout(timeout time.Duration) ClientOption

WithBatchTimeout sets the maximum time to wait before exporting.

func WithDebug

func WithDebug() ClientOption

WithDebug enables debug logging.

func WithDisabled

func WithDisabled() ClientOption

WithDisabled disables telemetry collection.

func WithEndpoint

func WithEndpoint(endpoint string) ClientOption

WithEndpoint sets the backend endpoint.

func WithHeaders

func WithHeaders(headers map[string]string) ClientOption

WithHeaders sets additional headers to send with requests.

func WithInsecure

func WithInsecure() ClientOption

WithInsecure disables TLS for the connection.

func WithResource

func WithResource(resource *Resource) ClientOption

WithResource sets the resource describing the service.

func WithServiceName

func WithServiceName(name string) ClientOption

WithServiceName sets the service name.

func WithServiceVersion

func WithServiceVersion(version string) ClientOption

WithServiceVersion sets the service version.

type Config

type Config struct {
	// ServiceName is the name of the service.
	ServiceName string

	// ServiceVersion is the version of the service.
	ServiceVersion string

	// Endpoint is the backend endpoint.
	Endpoint string

	// APIKey is the API key for authentication.
	APIKey string

	// Insecure disables TLS.
	Insecure bool

	// Headers are additional headers to send.
	Headers map[string]string

	// Resource is the resource describing the service.
	Resource *Resource

	// BatchTimeout is the maximum time to wait before exporting.
	BatchTimeout time.Duration

	// BatchSize is the maximum number of items per batch.
	BatchSize int

	// Disabled disables telemetry collection.
	Disabled bool

	// Debug enables debug logging.
	Debug bool
}

Config holds common configuration for providers.

func ApplyOptions

func ApplyOptions(opts ...ClientOption) *Config

ApplyOptions applies the given options to a config.

type ConfigError

type ConfigError struct {
	Field   string
	Message string
}

ConfigError represents a configuration error.

func (*ConfigError) Error

func (e *ConfigError) Error() string

type Counter

type Counter interface {
	// Add increments the counter by the given value.
	Add(ctx context.Context, value float64, opts ...RecordOption)
}

Counter is a metric that only increases.

type EventOption

type EventOption func(*eventConfig)

EventOption configures a span event.

func WithEventAttributes

func WithEventAttributes(attrs ...KeyValue) EventOption

WithEventAttributes sets event attributes.

func WithEventTimestamp

func WithEventTimestamp(t time.Time) EventOption

WithEventTimestamp sets a custom event timestamp.

type ExportError

type ExportError struct {
	Signal  string // "metrics", "traces", or "logs"
	Count   int    // Number of items that failed to export
	Details string
	Err     error
}

ExportError represents an error during telemetry export.

func (*ExportError) Error

func (e *ExportError) Error() string

func (*ExportError) Unwrap

func (e *ExportError) Unwrap() error

type Gauge

type Gauge interface {
	// Record records the current gauge value.
	Record(ctx context.Context, value float64, opts ...RecordOption)
}

Gauge records a current value that can go up or down.

type Histogram

type Histogram interface {
	// Record records a value in the histogram.
	Record(ctx context.Context, value float64, opts ...RecordOption)
}

Histogram records a distribution of values.

type KeyValue

type KeyValue struct {
	Key   string
	Value any
}

KeyValue represents a key-value pair for span/metric attributes.

func Attribute

func Attribute(key string, value any) KeyValue

Attribute creates a key-value attribute.

func GetAttributes

func GetAttributes(opts ...RecordOption) []KeyValue

GetAttributes returns the attributes from record options.

func GetEventAttributes

func GetEventAttributes(opts ...EventOption) []KeyValue

GetEventAttributes returns the attributes from event options.

func GetSpanAttributes

func GetSpanAttributes(opts ...SpanOption) []KeyValue

GetSpanAttributes returns the attributes from span options.

type LogAttribute

type LogAttribute struct {
	Key   string
	Value any
}

LogAttribute represents a key-value pair for log entries.

func LogAttr

func LogAttr(key string, value any) LogAttribute

LogAttr creates a log attribute.

type Logger

type Logger interface {
	// Debug logs a debug message.
	Debug(ctx context.Context, msg string, attrs ...LogAttribute)

	// Info logs an info message.
	Info(ctx context.Context, msg string, attrs ...LogAttribute)

	// Warn logs a warning message.
	Warn(ctx context.Context, msg string, attrs ...LogAttribute)

	// Error logs an error message.
	Error(ctx context.Context, msg string, attrs ...LogAttribute)
}

Logger provides structured logging methods.

type Meter

type Meter interface {
	// Counter creates a counter metric (monotonically increasing).
	Counter(name string, opts ...MetricOption) (Counter, error)

	// UpDownCounter creates a counter that can increase or decrease.
	UpDownCounter(name string, opts ...MetricOption) (UpDownCounter, error)

	// Histogram creates a histogram for recording value distributions.
	Histogram(name string, opts ...MetricOption) (Histogram, error)

	// Gauge creates a gauge metric for recording current values.
	Gauge(name string, opts ...MetricOption) (Gauge, error)
}

Meter provides methods for creating metric instruments.

type MetricOption

type MetricOption func(*metricConfig)

MetricOption configures a metric instrument.

func WithDescription

func WithDescription(desc string) MetricOption

WithDescription sets the metric description.

func WithUnit

func WithUnit(unit string) MetricOption

WithUnit sets the metric unit.

type Provider

type Provider interface {
	// Name returns the provider name (e.g., "otlp", "newrelic", "datadog").
	Name() string

	// Meter returns a metric meter for creating and recording metrics.
	Meter() Meter

	// Tracer returns a tracer for creating spans.
	Tracer() Tracer

	// Logger returns a structured logger.
	Logger() Logger

	// Shutdown gracefully shuts down the provider, flushing any buffered data.
	Shutdown(ctx context.Context) error

	// ForceFlush forces any buffered telemetry to be exported.
	ForceFlush(ctx context.Context) error
}

Provider is the main interface for general observability backends. It provides access to metrics, traces, and logs.

func MustOpen

func MustOpen(name string, opts ...ClientOption) Provider

MustOpen is like Open but panics on error.

func Open

func Open(name string, opts ...ClientOption) (Provider, error)

Open opens a provider specified by its name.

Most users will use a specific provider package import like:

import _ "github.com/agentplexus/omniobserve/observops/otlp"

And then open it with:

provider, err := observops.Open("otlp",
	observops.WithEndpoint("localhost:4317"),
	observops.WithServiceName("my-service"),
)

type ProviderError

type ProviderError struct {
	Provider string
	Op       string
	Err      error
}

ProviderError wraps errors from a specific provider.

func (*ProviderError) Error

func (e *ProviderError) Error() string

func (*ProviderError) Unwrap

func (e *ProviderError) Unwrap() error

type ProviderFactory

type ProviderFactory func(opts ...ClientOption) (Provider, error)

ProviderFactory creates a new Provider instance with the given options.

type ProviderInfo

type ProviderInfo struct {
	Name         string
	Description  string
	Website      string
	OpenSource   bool
	SelfHosted   bool
	Capabilities []Capability
}

ProviderInfo contains metadata about a registered provider.

func AllProviderInfo

func AllProviderInfo() []ProviderInfo

AllProviderInfo returns metadata for all registered providers.

func GetProviderInfo

func GetProviderInfo(name string) (ProviderInfo, bool)

GetProviderInfo returns metadata about a registered provider.

type RecordOption

type RecordOption func(*recordConfig)

RecordOption configures a metric recording.

func WithAttributes

func WithAttributes(attrs ...KeyValue) RecordOption

WithAttributes sets attributes for a metric recording.

type Resource

type Resource struct {
	ServiceName      string
	ServiceVersion   string
	ServiceNamespace string
	DeploymentEnv    string
	Attributes       map[string]string
}

Resource represents the entity producing telemetry.

type SeverityLevel

type SeverityLevel int

SeverityLevel represents log severity.

const (
	SeverityDebug SeverityLevel = iota
	SeverityInfo
	SeverityWarn
	SeverityError
)

type Span

type Span interface {
	// End marks the span as finished.
	End(opts ...SpanEndOption)

	// SetAttributes sets attributes on the span.
	SetAttributes(attrs ...KeyValue)

	// SetStatus sets the span status.
	SetStatus(code StatusCode, description string)

	// RecordError records an error on the span.
	RecordError(err error, opts ...EventOption)

	// AddEvent adds an event to the span.
	AddEvent(name string, opts ...EventOption)

	// SpanContext returns the span's context.
	SpanContext() SpanContext

	// IsRecording returns true if the span is recording.
	IsRecording() bool
}

Span represents a unit of work in a trace.

type SpanContext

type SpanContext struct {
	TraceID    string
	SpanID     string
	TraceFlags byte
	Remote     bool
}

SpanContext contains identifying trace information about a span.

func GetSpanLinks(opts ...SpanOption) []SpanContext

GetSpanLinks returns the links from span options.

type SpanEndOption

type SpanEndOption func(*spanEndConfig)

SpanEndOption configures span end behavior.

func WithEndTimestamp

func WithEndTimestamp(t time.Time) SpanEndOption

WithEndTimestamp sets a custom end timestamp.

type SpanKind

type SpanKind int

SpanKind represents the type of span.

const (
	SpanKindInternal SpanKind = iota
	SpanKindServer
	SpanKindClient
	SpanKindProducer
	SpanKindConsumer
)

func GetSpanKind

func GetSpanKind(opts ...SpanOption) SpanKind

GetSpanKind returns the span kind from options.

type SpanOption

type SpanOption func(*spanConfig)

SpanOption configures span creation.

func WithSpanAttributes

func WithSpanAttributes(attrs ...KeyValue) SpanOption

WithSpanAttributes sets initial span attributes.

func WithSpanKind

func WithSpanKind(kind SpanKind) SpanOption

WithSpanKind sets the span kind.

func WithSpanLinks(links ...SpanContext) SpanOption

WithSpanLinks sets span links.

type StatusCode

type StatusCode int

StatusCode represents the status of a span.

const (
	StatusCodeUnset StatusCode = iota
	StatusCodeOK
	StatusCodeError
)

type Tracer

type Tracer interface {
	// Start creates a new span with the given name.
	Start(ctx context.Context, name string, opts ...SpanOption) (context.Context, Span)

	// SpanFromContext retrieves the current span from context.
	SpanFromContext(ctx context.Context) Span
}

Tracer provides methods for creating spans.

type UpDownCounter

type UpDownCounter interface {
	// Add adds the given value (can be negative).
	Add(ctx context.Context, value float64, opts ...RecordOption)
}

UpDownCounter is a metric that can increase or decrease.

Directories

Path Synopsis
Package datadog provides a Datadog observability provider for observops.
Package datadog provides a Datadog observability provider for observops.
Package newrelic provides a New Relic observability provider for observops.
Package newrelic provides a New Relic observability provider for observops.
Package otlp provides an OpenTelemetry Protocol (OTLP) exporter for observops.
Package otlp provides an OpenTelemetry Protocol (OTLP) exporter for observops.

Jump to

Keyboard shortcuts

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