Documentation
¶
Index ¶
- Constants
- Variables
- func BoolPtr(v bool) *bool
- func CreateCounter(meter metric.Meter, name, description string, ...) (metric.Int64Counter, error)
- func CreateHistogram(meter metric.Meter, name, description string, ...) (metric.Float64Histogram, error)
- func CreateUpDownCounter(meter metric.Meter, name, description string, ...) (metric.Int64UpDownCounter, error)
- func Float64Ptr(v float64) *float64
- func MustShutdown(provider Provider, timeout time.Duration)
- func Shutdown(provider Provider, timeout time.Duration) error
- type BatchConfig
- type Config
- type ExportConfig
- type MaxBatchConfig
- type MaxConfig
- type MetricsConfig
- type MetricsExportConfig
- type Provider
- type QueueConfig
- type SampleConfig
- type ServiceConfig
- type TraceConfig
Constants ¶
const ( // EndpointStdout is a special endpoint value that outputs to stdout (for local development). EndpointStdout = "stdout" // ProtocolHTTP specifies OTLP over HTTP/protobuf. ProtocolHTTP = "http" // ProtocolGRPC specifies OTLP over gRPC. ProtocolGRPC = "grpc" )
const ( // DefaultShutdownTimeout is the default timeout for graceful shutdown. DefaultShutdownTimeout = 10 * time.Second )
Variables ¶
var ErrAlreadyInitialized = errors.New("observability: provider already initialized")
ErrAlreadyInitialized is returned when attempting to initialize an already initialized provider.
var ErrInvalidProtocol = errors.New("observability: protocol must be either 'http' or 'grpc'")
ErrInvalidProtocol is returned when the protocol (trace or metrics) is not "http" or "grpc".
var ErrInvalidSampleRate = errors.New("observability: trace sample rate must be between 0.0 and 1.0")
ErrInvalidSampleRate is returned when the trace sample rate is outside the valid range [0.0, 1.0].
var ErrMissingServiceName = errors.New("observability: service name is required when observability is enabled")
ErrMissingServiceName is returned when observability is enabled but no service name is configured.
var ErrNilConfig = errors.New("observability: config is nil")
ErrNilConfig is returned when Validate is called on a nil Config pointer.
var ErrNotInitialized = errors.New("observability: provider not initialized")
ErrNotInitialized is returned when attempting to use an uninitialized provider.
var ErrShutdownTimeout = errors.New("observability: shutdown timeout exceeded")
ErrShutdownTimeout is returned when graceful shutdown exceeds the timeout.
Functions ¶
func BoolPtr ¶
BoolPtr returns a pointer to the provided bool value. Helpful when optional boolean configuration fields are used.
func CreateCounter ¶
func CreateCounter(meter metric.Meter, name, description string, opts ...metric.Int64CounterOption) (metric.Int64Counter, error)
CreateCounter creates a new counter metric instrument. Counters are monotonically increasing values (e.g., request count, error count).
Example:
counter, err := CreateCounter(meter, "http.requests.total", "Total HTTP requests")
if err != nil {
return err
}
counter.Add(ctx, 1, metric.WithAttributes(
attribute.String("method", "GET"),
attribute.Int("status", 200),
))
func CreateHistogram ¶
func CreateHistogram(meter metric.Meter, name, description string, opts ...metric.Float64HistogramOption) (metric.Float64Histogram, error)
CreateHistogram creates a new histogram metric instrument. Histograms record distributions of values (e.g., request duration, response size).
Example:
histogram, err := CreateHistogram(meter, "http.request.duration", "HTTP request duration in milliseconds")
if err != nil {
return err
}
histogram.Record(ctx, 123.45, metric.WithAttributes(
attribute.String("method", "GET"),
attribute.String("path", "/users"),
))
func CreateUpDownCounter ¶
func CreateUpDownCounter(meter metric.Meter, name, description string, opts ...metric.Int64UpDownCounterOption) (metric.Int64UpDownCounter, error)
CreateUpDownCounter creates a new up-down counter metric instrument. Up-down counters can increase or decrease (e.g., active connections, queue size).
Example:
upDownCounter, err := CreateUpDownCounter(meter, "db.connections.active", "Active database connections")
if err != nil {
return err
}
upDownCounter.Add(ctx, 1) // Connection opened
upDownCounter.Add(ctx, -1) // Connection closed
func Float64Ptr ¶
Float64Ptr returns a pointer to the provided float64 value. Helpful when optional float64 configuration fields are used.
func MustShutdown ¶
MustShutdown is like Shutdown but panics on error. Useful for cleanup in defer statements where error handling is not possible.
Types ¶
type BatchConfig ¶
type BatchConfig struct {
// Timeout specifies how long to wait before sending a batch of spans.
// Lower values reduce latency but increase network overhead.
Timeout time.Duration `mapstructure:"timeout"`
// Size limits the number of spans per export batch.
// Smaller batches reduce latency, larger batches reduce overhead.
Size int `mapstructure:"size"`
}
BatchConfig defines batch processing configuration for traces.
type Config ¶
type Config struct {
// Enabled controls whether observability is active.
// When false, all observability operations become no-ops.
Enabled bool `mapstructure:"enabled"`
// Service contains service identification metadata.
Service ServiceConfig `mapstructure:"service"`
// Environment indicates the deployment environment (e.g., production, staging, development).
Environment string `mapstructure:"environment"`
// Trace contains tracing-specific configuration.
Trace TraceConfig `mapstructure:"trace"`
// Metrics contains metrics-specific configuration.
Metrics MetricsConfig `mapstructure:"metrics"`
}
Config defines the configuration for observability features. It supports automatic unmarshaling via the GoBricks config system using mapstructure tags.
func (*Config) ApplyDefaults ¶
func (c *Config) ApplyDefaults()
ApplyDefaults sets default values for any config fields that are not specified. This is called after unmarshaling to ensure all fields have sensible defaults.
type ExportConfig ¶
type ExportConfig struct {
// Timeout specifies the maximum time to wait for span export.
// Prevents slow backends from blocking the application.
Timeout time.Duration `mapstructure:"timeout"`
}
ExportConfig defines export timeout configuration.
type MaxBatchConfig ¶
type MaxBatchConfig struct {
// Size limits the number of spans per export batch.
// Smaller batches reduce latency, larger batches reduce overhead.
Size int `mapstructure:"size"`
}
MaxBatchConfig defines batch size configuration.
type MaxConfig ¶
type MaxConfig struct {
// Queue contains queue size configuration.
Queue QueueConfig `mapstructure:"queue"`
// Batch contains batch size configuration.
Batch MaxBatchConfig `mapstructure:"batch"`
}
MaxConfig defines maximum queue and batch size limits.
type MetricsConfig ¶
type MetricsConfig struct {
// Enabled controls whether metrics collection is active.
// Can be used to disable metrics while keeping tracing enabled.
// nil = apply default (true when observability is enabled), false = explicitly disabled.
Enabled *bool `mapstructure:"enabled"`
// Endpoint specifies where to send metric data.
// Special value "stdout" enables console logging for local development.
// For production, use OTLP endpoint (e.g., "http://localhost:4318").
Endpoint string `mapstructure:"endpoint"`
// Protocol specifies the OTLP protocol to use: "http" or "grpc".
// If empty, metrics inherit the trace protocol.
Protocol string `mapstructure:"protocol"`
// Insecure controls whether to use insecure connections (no TLS).
// Only applicable for OTLP endpoints (http/grpc). Falls back to trace setting when unset.
Insecure *bool `mapstructure:"insecure"`
// Headers allows custom headers for OTLP exporters (e.g., DataDog API keys).
// If nil or empty, metrics inherit trace headers.
Headers map[string]string `mapstructure:"headers"`
// Interval specifies how often to export metrics.
// Shorter intervals provide more real-time data but increase overhead.
Interval time.Duration `mapstructure:"interval"`
// Export contains export timeout configuration.
Export MetricsExportConfig `mapstructure:"export"`
}
MetricsConfig defines configuration for metrics collection.
type MetricsExportConfig ¶
type MetricsExportConfig struct {
// Timeout specifies the maximum time to wait for metric export.
// Prevents slow backends from blocking the application.
Timeout time.Duration `mapstructure:"timeout"`
}
MetricsExportConfig defines export timeout configuration for metrics.
type Provider ¶
type Provider interface {
// TracerProvider returns the configured trace provider.
TracerProvider() trace.TracerProvider
// MeterProvider returns the configured meter provider.
MeterProvider() metric.MeterProvider
// Shutdown gracefully shuts down the provider, flushing any pending data.
// It should be called during application shutdown.
Shutdown(ctx context.Context) error
// ForceFlush immediately flushes any pending telemetry data.
// Useful before critical operations or shutdown.
ForceFlush(ctx context.Context) error
}
Provider is the interface for observability providers. It manages the lifecycle of tracing and metrics providers.
func MustNewProvider ¶
MustNewProvider creates a new observability provider and panics on error. This is useful for initialization where provider creation must succeed or fail fast.
func NewProvider ¶
NewProvider creates a new observability provider based on the configuration. If observability is disabled, returns a no-op provider. If enabled, initializes OpenTelemetry with the configured exporters.
IMPORTANT: This function applies default values before validation to ensure safe configuration (e.g., sample rate defaults to 1.0). Callers do NOT need to call ApplyDefaults() first - it's handled internally.
type QueueConfig ¶
type QueueConfig struct {
// Size limits the number of spans buffered for export.
// Prevents memory exhaustion under high load.
Size int `mapstructure:"size"`
}
QueueConfig defines queue size configuration.
type SampleConfig ¶
type SampleConfig struct {
// Rate controls what fraction of traces to collect (0.0 to 1.0).
// 1.0 means collect all traces, 0.1 means collect 10% of traces, 0.0 means collect nothing.
// Lower values reduce overhead and costs.
// nil = apply default (1.0), explicit value = use that value (including 0.0).
Rate *float64 `mapstructure:"rate"`
}
SampleConfig defines sampling configuration for traces.
type ServiceConfig ¶
type ServiceConfig struct {
// Name identifies the service in traces and metrics.
// This is required when observability is enabled.
Name string `mapstructure:"name"`
// Version specifies the version of the service.
// Used for filtering and grouping in observability backends.
Version string `mapstructure:"version"`
}
ServiceConfig contains service identification metadata.
type TraceConfig ¶
type TraceConfig struct {
// Enabled controls whether tracing is active.
// Can be used to disable tracing while keeping metrics enabled.
// nil = apply default (true when observability is enabled), false = explicitly disabled.
Enabled *bool `mapstructure:"enabled"`
// Endpoint specifies where to send trace data.
// Special value "stdout" enables console logging for local development.
// For production, use OTLP endpoint (e.g., "http://localhost:4318" for HTTP or "localhost:4317" for gRPC).
Endpoint string `mapstructure:"endpoint"`
// Protocol specifies the OTLP protocol to use: "http" or "grpc".
// Only used when Endpoint is not "stdout".
// HTTP uses OTLP/HTTP protocol (default port 4318).
// gRPC uses OTLP/gRPC protocol (default port 4317).
Protocol string `mapstructure:"protocol"`
// Insecure controls whether to use insecure connections (no TLS).
// Only applicable for OTLP endpoints (http/grpc).
// Set to true for local development without TLS.
Insecure bool `mapstructure:"insecure"`
// Headers allows custom HTTP headers for OTLP exporters.
// Useful for authentication tokens or API keys.
// Format: map of header name to header value.
Headers map[string]string `mapstructure:"headers"`
// Sample contains sampling configuration.
Sample SampleConfig `mapstructure:"sample"`
// Batch contains batch processing configuration.
Batch BatchConfig `mapstructure:"batch"`
// Export contains export timeout configuration.
Export ExportConfig `mapstructure:"export"`
// Max contains maximum queue and batch size limits.
Max MaxConfig `mapstructure:"max"`
}
TraceConfig defines configuration for distributed tracing.