observops

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2026 License: MIT Imports: 34 Imported by: 2

README

observops

General service observability (metrics, traces, logs) on OpenTelemetry, with two entry points.

One call wires every signal and returns native OpenTelemetry handles — you instrument with the standard OTel API and keep full ecosystem interop. observops owns only the wiring: exporters, resource detection, propagation, batch processors, the slog bridge, and shutdown.

tel, err := observops.Setup(ctx,
    observops.WithServiceName("my-service"),
    observops.WithPrometheus(),               // pull: tel.MetricsHandler
    observops.WithEndpoint("localhost:4317"), // push: OTLP gRPC
    observops.WithInsecure(),
)
if err != nil {
    log.Fatal(err)
}
defer tel.Shutdown(context.Background())

reqs, _ := tel.Meter.Int64Counter("requests.total")
reqs.Add(ctx, 1)

ctx, span := tel.Tracer.Start(ctx, "handle-request")
defer span.End()

tel.Logger.InfoContext(ctx, "request processed", "user_id", "123")

mux.Handle("/metrics", tel.MetricsHandler)
handler = tel.Middleware("api")(handler)

Metrics, traces, and logs are on by default; disable with WithMetrics/WithTraces/WithLogs. Export targets compose: Prometheus pull (WithPrometheus), OTLP push over gRPC or HTTP (WithEndpoint, WithOTLPOverHTTP), and stdout (WithStdout).

See docs/providers/setup.md for the full reference.

Driver registry (vendor-neutral abstraction)

Open(name) returns a provider whose own interfaces wrap OpenTelemetry, for switching vendors through one call. It exposes an OTel subset; prefer Setup unless you specifically want the vendor switch.

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

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

Registered drivers: otlp, datadog, newrelic, dynatrace.

Documentation

Overview

Package observops provides general service observability (metrics, traces, and logs) built on OpenTelemetry. It offers two entry points:

  • Setup (recommended): a one-call bootstrap that wires every signal and its exporters and returns native OpenTelemetry handles. Consumers instrument with the standard OTel API and keep full ecosystem interop (otelhttp, gRPC interceptors, database instrumentation, and so on). The boilerplate — exporters, resource detection, propagation, batch processors, the slog bridge, and graceful shutdown — lives here.

  • The driver registry (Open): a vendor-neutral abstraction whose own Provider/Meter/ Tracer/Span/Logger interfaces sit in front of OpenTelemetry. Useful when you want to switch vendors through a single Open("otlp"|"datadog"|"newrelic"|"dynatrace") call and are content with an OTel subset. Most services should prefer Setup.

This package complements the llmops package (which handles LLM-specific observability).

Quick Start (Setup)

tel, err := observops.Setup(ctx,
	observops.WithServiceName("my-service"),
	observops.WithServiceVersion("1.2.3"),
	observops.WithPrometheus(),                 // pull: expose tel.MetricsHandler
	observops.WithEndpoint("localhost:4317"),   // push: OTLP gRPC collector
	observops.WithInsecure(),
)
if err != nil {
	log.Fatal(err)
}
defer tel.Shutdown(context.Background())

// Native OpenTelemetry handles:
ctx, span := tel.Tracer.Start(ctx, "ProcessRequest")
defer span.End()

reqs, _ := tel.Meter.Int64Counter("requests.total")
reqs.Add(ctx, 1)

tel.Logger.Info("request processed", "user_id", "123")

// Serve Prometheus metrics and instrument HTTP in one line each:
mux.Handle("/metrics", tel.MetricsHandler)
handler = tel.Middleware("api")(handler)

Metrics, traces, and logs are enabled by default; disable any with WithMetrics, WithTraces, or WithLogs. Export targets compose: Prometheus pull (WithPrometheus), OTLP push over gRPC or HTTP (WithEndpoint, WithOTLPOverHTTP), and stdout (WithStdout).

Vendor-neutral driver registry (Open)

import (
	"github.com/plexusone/omniobserve/observops"
	_ "github.com/plexusone/omniobserve/observops/otlp"
)

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

Index

Examples

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 NoopSlogHandler added in v0.8.0

func NoopSlogHandler() slog.Handler

NoopSlogHandler returns an slog.Handler that discards all logs.

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 WithLogs added in v0.12.0

func WithLogs(enabled bool) ClientOption

WithLogs enables or disables the logs signal (enabled by default).

func WithMetrics added in v0.12.0

func WithMetrics(enabled bool) ClientOption

WithMetrics enables or disables the metrics signal (enabled by default).

func WithOTLPOverHTTP added in v0.12.0

func WithOTLPOverHTTP() ClientOption

WithOTLPOverHTTP uses OTLP over HTTP instead of gRPC for push export.

func WithPrometheus added in v0.12.0

func WithPrometheus() ClientOption

WithPrometheus adds a Prometheus pull exporter; the handler is exposed as Telemetry.MetricsHandler.

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.

func WithStdout added in v0.12.0

func WithStdout() ClientOption

WithStdout mirrors telemetry to stdout for local debugging.

func WithTraceSampleRatio added in v0.12.0

func WithTraceSampleRatio(ratio float64) ClientOption

WithTraceSampleRatio sets the head sampling ratio for traces (0..1).

func WithTraces added in v0.12.0

func WithTraces(enabled bool) ClientOption

WithTraces enables or disables the traces signal (enabled by default).

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 //nolint:gosec // G117: APIKey is intentionally stored for backend authentication

	// 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

	// EnableMetrics enables the metrics signal (default true in Setup).
	EnableMetrics bool
	// EnableTraces enables the traces signal (default true in Setup).
	EnableTraces bool
	// EnableLogs enables the logs signal (default true in Setup).
	EnableLogs bool
	// EnablePrometheus adds a Prometheus pull exporter and exposes a /metrics handler.
	EnablePrometheus bool
	// EnableStdout mirrors telemetry to stdout (for local debugging).
	EnableStdout bool
	// OverHTTP uses OTLP over HTTP instead of gRPC for push export.
	OverHTTP bool
	// TraceSampleRatio is the head sampling ratio for traces (0..1, default 1.0).
	TraceSampleRatio float64
}

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 LoggerSlogHandler added in v0.8.0

type LoggerSlogHandler struct {
	// contains filtered or unexported fields
}

LoggerSlogHandler wraps an observops.Logger as an slog.Handler. This allows using observops.Logger as the remote backend for sloghandler.

func NewLoggerSlogHandler added in v0.8.0

func NewLoggerSlogHandler(logger Logger, cfg *SlogConfig) *LoggerSlogHandler

NewLoggerSlogHandler creates an slog.Handler that wraps an observops.Logger.

func (*LoggerSlogHandler) Enabled added in v0.8.0

func (h *LoggerSlogHandler) Enabled(ctx context.Context, level slog.Level) bool

Enabled implements slog.Handler.

func (*LoggerSlogHandler) Handle added in v0.8.0

func (h *LoggerSlogHandler) Handle(ctx context.Context, r slog.Record) error

Handle implements slog.Handler.

func (*LoggerSlogHandler) WithAttrs added in v0.8.0

func (h *LoggerSlogHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs implements slog.Handler.

func (*LoggerSlogHandler) WithGroup added in v0.8.0

func (h *LoggerSlogHandler) WithGroup(name string) slog.Handler

WithGroup implements slog.Handler.

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

	// SlogHandler returns an slog.Handler that integrates with this provider.
	// The handler automatically correlates logs with active traces.
	// Options can be used to configure local output and filtering.
	SlogHandler(opts ...SlogOption) slog.Handler

	// 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/plexusone/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 SlogConfig added in v0.8.0

type SlogConfig struct {
	// LocalHandler is the handler for local output (console, file).
	// If nil, logs are only sent to the observability backend.
	LocalHandler interface{} // slog.Handler, using interface{} to avoid import cycle

	// RemoteLevel is the minimum level for remote export.
	// Defaults to slog.LevelInfo.
	RemoteLevel int // slog.Level value

	// IncludeTraceContext enables automatic trace_id/span_id injection.
	// Defaults to true.
	IncludeTraceContext bool

	// TraceIDKey is the attribute key for trace ID.
	// Defaults to "trace_id".
	TraceIDKey string

	// SpanIDKey is the attribute key for span ID.
	// Defaults to "span_id".
	SpanIDKey string

	// Disabled disables the handler (returns a noop handler).
	Disabled bool
}

SlogConfig holds configuration for slog.Handler integration.

func ApplySlogOptions added in v0.8.0

func ApplySlogOptions(opts ...SlogOption) *SlogConfig

ApplySlogOptions applies slog options to a config.

func DefaultSlogConfig added in v0.8.0

func DefaultSlogConfig() *SlogConfig

DefaultSlogConfig returns a SlogConfig with sensible defaults.

type SlogOption added in v0.8.0

type SlogOption func(*SlogConfig)

SlogOption configures slog.Handler integration.

func WithSlogDisableTraceContext added in v0.8.0

func WithSlogDisableTraceContext() SlogOption

WithSlogDisableTraceContext disables automatic trace context injection.

func WithSlogDisabled added in v0.8.0

func WithSlogDisabled() SlogOption

WithSlogDisabled disables the slog handler.

func WithSlogLocalHandler added in v0.8.0

func WithSlogLocalHandler(h interface{}) SlogOption

WithSlogLocalHandler sets the local output handler.

func WithSlogRemoteLevel added in v0.8.0

func WithSlogRemoteLevel(level int) SlogOption

WithSlogRemoteLevel sets the minimum level for remote export. Use slog.LevelDebug, slog.LevelInfo, slog.LevelWarn, slog.LevelError.

func WithSlogSpanIDKey added in v0.8.0

func WithSlogSpanIDKey(key string) SlogOption

WithSlogSpanIDKey sets the attribute key for span ID.

func WithSlogTraceIDKey added in v0.8.0

func WithSlogTraceIDKey(key string) SlogOption

WithSlogTraceIDKey sets the attribute key for trace ID.

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 Telemetry added in v0.12.0

type Telemetry struct {
	// Tracer is a ready-to-use tracer named after the service.
	Tracer trace.Tracer
	// Meter is a ready-to-use meter named after the service.
	Meter metric.Meter
	// Logger is an slog.Logger fanning out to the console and, when logs are enabled, to
	// the OpenTelemetry log pipeline. It is also installed as slog.Default().
	Logger *slog.Logger
	// MetricsHandler serves Prometheus metrics when WithPrometheus is set, else nil.
	MetricsHandler http.Handler

	// Providers are exposed for advanced use (custom instruments, registration).
	TracerProvider *sdktrace.TracerProvider
	MeterProvider  *sdkmetric.MeterProvider
	LoggerProvider *sdklog.LoggerProvider
	// contains filtered or unexported fields
}

Telemetry holds initialized OpenTelemetry handles for direct use with the standard OTel API. Setup wires every enabled signal and their exporters; callers then instrument with vanilla OTel (trace.Tracer, metric.Meter, slog) and retain full ecosystem interop.

func Setup added in v0.12.0

func Setup(ctx context.Context, opts ...ClientOption) (*Telemetry, error)

Setup bootstraps OpenTelemetry from options and returns native handles. Metrics, traces, and logs are enabled by default; disable any with WithMetrics/WithTraces/WithLogs(false). Push export to an OTLP collector is active when WithEndpoint is set; WithPrometheus adds a pull endpoint; WithStdout mirrors to stdout for debugging.

Example

ExampleSetup shows the recommended bootstrap: one call wires metrics, traces, and logs, and returns native OpenTelemetry handles plus a Prometheus handler and HTTP middleware.

package main

import (
	"context"
	"log"
	"net/http"

	"github.com/plexusone/omniobserve/observops"
)

func main() {
	ctx := context.Background()

	tel, err := observops.Setup(ctx,
		observops.WithServiceName("my-service"),
		observops.WithServiceVersion("1.2.3"),
		observops.WithPrometheus(),               // pull endpoint (tel.MetricsHandler)
		observops.WithEndpoint("localhost:4317"), // OTLP push
		observops.WithInsecure(),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = tel.Shutdown(ctx) }()

	// Metrics with the native OTel meter.
	requests, _ := tel.Meter.Int64Counter("requests.total")
	requests.Add(ctx, 1)

	// Tracing with the native OTel tracer.
	ctx, span := tel.Tracer.Start(ctx, "handle-request")
	defer span.End()

	// Structured logging exported via OpenTelemetry and echoed to the console.
	tel.Logger.InfoContext(ctx, "request processed", "user_id", "123")

	// Expose Prometheus metrics and instrument an HTTP handler.
	mux := http.NewServeMux()
	mux.Handle("/metrics", tel.MetricsHandler)
	mux.Handle("/api/", tel.Middleware("api")(http.NotFoundHandler()))
}

func (*Telemetry) Middleware added in v0.12.0

func (t *Telemetry) Middleware(operation string) func(http.Handler) http.Handler

Middleware wraps an http.Handler with OpenTelemetry server instrumentation: a span per request (with context extracted from inbound headers) plus HTTP server metrics. Use it on the serving side.

func (*Telemetry) Shutdown added in v0.12.0

func (t *Telemetry) Shutdown(ctx context.Context) error

Shutdown flushes and stops every initialized signal provider in reverse order. It returns the first error but always attempts them all.

func (*Telemetry) Transport added in v0.12.0

func (t *Telemetry) Transport(base http.RoundTripper) http.RoundTripper

Transport wraps an http.RoundTripper with OpenTelemetry client instrumentation: a span per outbound request plus trace-context propagation to the upstream. Pass nil to wrap http.DefaultTransport.

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 dynatrace provides a Dynatrace observability provider for observops.
Package dynatrace provides a Dynatrace 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