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 DualModeLogProcessor
- func (p *DualModeLogProcessor) Enabled(_ context.Context, param sdklog.EnabledParameters) bool
- func (p *DualModeLogProcessor) ForceFlush(ctx context.Context) error
- func (p *DualModeLogProcessor) OnEmit(ctx context.Context, rec *sdklog.Record) error
- func (p *DualModeLogProcessor) Shutdown(ctx context.Context) error
- type ExportConfig
- type LogsConfig
- 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" // CompressionGzip specifies gzip compression for OTLP export. CompressionGzip = "gzip" // CompressionNone specifies no compression for OTLP export. CompressionNone = "none" // TemporalityDelta specifies delta temporality for metrics (recommended by New Relic). // Delta temporality reports the change in value since the last export. TemporalityDelta = "delta" // TemporalityCumulative specifies cumulative temporality for metrics. // Cumulative temporality reports the total value since the start of the measurement. TemporalityCumulative = "cumulative" // HistogramAggregationExponential specifies exponential histogram aggregation (recommended by New Relic). // Provides better precision for a wide range of values with lower memory overhead. HistogramAggregationExponential = "exponential" // HistogramAggregationExplicit specifies explicit bucket histogram aggregation. // Uses fixed bucket boundaries defined by the application. HistogramAggregationExplicit = "explicit" // EnvironmentDevelopment is the default environment name for development mode. EnvironmentDevelopment = "development" )
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 ErrInvalidCompression = errors.New("observability: compression must be either 'gzip' or 'none'")
ErrInvalidCompression is returned when the compression value is not "gzip" or "none".
var ErrInvalidEndpointFormat = errors.New("observability: invalid endpoint format for protocol")
ErrInvalidEndpointFormat is returned when the endpoint format doesn't match the protocol. gRPC endpoints must NOT include http:// or https:// scheme (use "host:port" format). HTTP endpoints MUST include http:// or https:// scheme.
var ErrInvalidHistogramAggregation = errors.New("observability: histogram aggregation must be either 'exponential' or 'explicit'")
ErrInvalidHistogramAggregation is returned when the histogram aggregation is not "exponential" or "explicit".
var ErrInvalidLogSamplingRate = errors.New("observability: log sampling rate must be between 0.0 and 1.0")
ErrInvalidLogSamplingRate is returned when the log sampling rate is outside the valid range [0.0, 1.0].
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 ErrInvalidTemporality = errors.New("observability: temporality must be either 'delta' or 'cumulative'")
ErrInvalidTemporality is returned when the temporality value is not "delta" or "cumulative".
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"`
// Logs contains logging-specific configuration.
Logs LogsConfig `mapstructure:"logs"`
}
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 DualModeLogProcessor ¶ added in v0.13.0
type DualModeLogProcessor struct {
// contains filtered or unexported fields
}
DualModeLogProcessor routes log records to different processors based on log.type attribute. It implements the dual-mode logging architecture where:
- Action logs (log.type="action") are exported with all severities (100% sampling)
- Trace logs (log.type="trace"): ERROR/WARN always exported, INFO/DEBUG sampled by rate
func NewDualModeLogProcessor ¶ added in v0.13.0
func NewDualModeLogProcessor(actionProcessor, traceProcessor sdklog.Processor, samplingRate float64) *DualModeLogProcessor
NewDualModeLogProcessor creates a new dual-mode log processor. samplingRate controls what fraction of INFO/DEBUG trace logs to export (0.0 to 1.0). ERROR/WARN logs and action logs are always exported at 100%.
func (*DualModeLogProcessor) Enabled ¶ added in v0.13.0
func (p *DualModeLogProcessor) Enabled(_ context.Context, param sdklog.EnabledParameters) bool
Enabled checks if the processor should process logs with the given parameters. The EnabledParameters only provides severity and scope (not full record attributes), so we use severity-based pre-filtering. Full routing (action vs trace logs) happens in OnEmit where we have access to the complete record.
func (*DualModeLogProcessor) ForceFlush ¶ added in v0.13.0
func (p *DualModeLogProcessor) ForceFlush(ctx context.Context) error
ForceFlush flushes both processors.
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 LogsConfig ¶ added in v0.13.0
type LogsConfig struct {
// Enabled controls whether OTLP log export is active.
// Can be used to disable log export while keeping traces/metrics enabled.
// nil = apply default (true when observability is enabled), false = explicitly disabled.
Enabled *bool `mapstructure:"enabled"`
// Endpoint specifies where to send log 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".
// If empty, logs inherit the trace protocol.
Protocol string `mapstructure:"protocol"`
// Insecure controls whether to use insecure connections (no TLS).
// Only applicable for OTLP endpoints (http/grpc). Independent of Trace.Insecure:
// when unset, defaults to false (TLS-secure) via applyLogsDefaults — it does NOT
// inherit from the trace setting. Operators running a plaintext local OTLP
// collector for logs must opt in by setting logs.insecure: true explicitly.
Insecure *bool `mapstructure:"insecure"`
// DisableStdout controls whether to disable stdout logging when OTLP is enabled.
// When false (default), logs go to both stdout and OTLP (useful for development).
// When true, logs only go to OTLP (production efficiency).
DisableStdout bool `mapstructure:"disablestdout"`
// Headers allows custom HTTP headers for OTLP exporters.
// Useful for authentication tokens or API keys.
// If nil or empty, logs inherit trace headers.
Headers map[string]string `mapstructure:"headers"`
// Compression specifies the compression algorithm for OTLP export.
// Supported values: "gzip", "none".
// Default: "gzip" (recommended by New Relic for bandwidth reduction).
Compression string `mapstructure:"compression"`
// Batch contains batch processing configuration (reused from TraceConfig pattern).
Batch BatchConfig `mapstructure:"batch"`
// Export contains export timeout configuration (reused from TraceConfig pattern).
Export ExportConfig `mapstructure:"export"`
// Max contains maximum queue and batch size limits (reused from TraceConfig pattern).
Max MaxConfig `mapstructure:"max"`
// SlowRequestThreshold defines the latency threshold for marking HTTP requests as slow.
// Requests exceeding this duration are logged with result_code="WARN" in action logs.
// This is a system-wide threshold (no per-route overrides).
// Default: 1 second.
SlowRequestThreshold time.Duration `mapstructure:"slowrequestthreshold"`
// SamplingRate controls what fraction of INFO/DEBUG trace logs to export (0.0 to 1.0).
// ERROR/WARN logs and action logs are always exported at 100%.
// Sampling is deterministic per trace (all logs in a trace are sampled together).
// 1.0 means export all INFO/DEBUG logs, 0.0 means export none (default).
// nil = apply default (0.0 for backward compatibility).
SamplingRate *float64 `mapstructure:"samplingrate"`
}
LogsConfig defines configuration for log export via OTLP.
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"`
// Compression specifies the compression algorithm for OTLP export.
// Supported values: "gzip", "none".
// Default: "gzip" (recommended by New Relic for bandwidth reduction).
Compression string `mapstructure:"compression"`
// Temporality specifies the aggregation temporality for metrics.
// Supported values: "delta", "cumulative".
// Default: "cumulative" (OTEL SDK default).
// New Relic recommends "delta" for better performance and lower memory usage.
Temporality string `mapstructure:"temporality"`
// HistogramAggregation specifies the histogram aggregation method.
// Supported values: "exponential", "explicit".
// Default: "explicit" (OTEL SDK default).
// New Relic recommends "exponential" for better precision and lower memory overhead.
HistogramAggregation string `mapstructure:"histogramaggregation"`
// 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
// LoggerProvider returns the configured logger provider.
// Returns nil if logging is disabled.
LoggerProvider() *sdklog.LoggerProvider
// ShouldDisableStdout returns true if stdout should be disabled when OTLP is enabled.
// This method provides configuration access for logger integration.
ShouldDisableStdout() bool
// 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, metrics, and logging 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.
NewProvider uses a context.Background() for construction. Use NewProviderWithContext to bound resource detection and exporter setup by a deadline (e.g. an app.startup.observability budget).
func NewProviderWithContext ¶ added in v0.43.0
NewProviderWithContext creates a new observability provider, threading ctx through resource detection (resource.New) and OTLP exporter construction so the caller can bound those steps with a deadline.
What the context bounds: the synchronous setup work performed here — resource attribute detection and the OTLP exporter constructors (otlptracehttp/grpc, otlpmetrichttp/grpc, otlploghttp/grpc). It does NOT bound steady-state telemetry export, which the SDK governs via its own per-export timeouts.
Note: OTLP gRPC dialing is lazy (the connection is established on first export, not at construction), so for the gRPC transports the deadline mainly bounds resource detection and exporter object setup rather than any network round-trip. The HTTP transports likewise connect lazily.
Like NewProvider, this applies defaults before validation; callers do NOT need to call ApplyDefaults() first. If observability is disabled, a no-op provider is returned regardless of ctx.
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"`
// Compression specifies the compression algorithm for OTLP export.
// Supported values: "gzip", "none".
// Default: "gzip" (recommended by New Relic for bandwidth reduction).
Compression string `mapstructure:"compression"`
// 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.