observability

package
v0.20.0 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2025 License: MIT Imports: 35 Imported by: 0

README

Observability Package

The observability package provides production-ready distributed tracing using OpenTelemetry with support for multiple exporters including OTLP (HTTP/gRPC) and stdout.

Features

  • Flexible Exporters: stdout for development, OTLP for production
  • Protocol Support: Both OTLP/HTTP and OTLP/gRPC protocols
  • Configurable Sampling: Control trace collection rate (0.0 - 1.0)
  • Custom Headers: Support for authentication tokens and custom headers
  • Independent Pipelines: Configure tracing and metrics with separate transports and credentials
  • Resource Attributes: Automatic service name, version, and environment tagging
  • Graceful Shutdown: Proper flushing of pending telemetry data
  • No-op Mode: Zero overhead when observability is disabled

Quick Start

Development with stdout Exporter
# config.yaml
observability:
  enabled: true
  service:
    name: "my-service"
    version: "1.0.0"
  environment: "development"
  trace:
    enabled: true
    endpoint: "stdout"
    sample:
      rate: 1.0
package main

import (
    "context"
    "github.com/gaborage/go-bricks/config"
    "github.com/gaborage/go-bricks/observability"
)

func main() {
    // Load configuration
    cfg := config.New()
    var obsCfg observability.Config
    if err := cfg.InjectInto(&obsCfg); err != nil {
        panic(err)
    }

    // Initialize observability provider
    provider, err := observability.NewProvider(&obsCfg)
    if err != nil {
        panic(err)
    }
    defer observability.Shutdown(provider, 5)

    // Create tracer
    tracer := provider.TracerProvider().Tracer("my-service")

    // Create span
    ctx, span := tracer.Start(context.Background(), "operation")
    defer span.End()

    // Your business logic here
}

Production Configuration

OTLP HTTP Exporter

OTLP/HTTP is recommended for production environments with HTTP-based observability backends like Grafana Cloud, Honeycomb, or self-hosted collectors.

# config.production.yaml
observability:
  enabled: true
  service:
    name: "my-service"
    version: "1.2.3"
  environment: "production"
  trace:
    enabled: true
    endpoint: "otel-collector.monitoring.svc.cluster.local:4318"
    protocol: "http"
    insecure: false  # Use TLS in production
    headers:
      Authorization: "Bearer ${OTEL_API_KEY}"
    sample:
      rate: 0.1  # Sample 10% of traces
    batch:
      timeout: "5s"
    export:
      timeout: "30s"
    max:
      queue:
        size: 2048
      batch:
        size: 512

Environment variables:

export OTEL_API_KEY="your-api-key-here"
OTLP gRPC Exporter

OTLP/gRPC provides better performance and is ideal for high-throughput services.

# config.production.yaml
observability:
  enabled: true
  service:
    name: "my-service"
    version: "1.2.3"
  environment: "production"
  trace:
    enabled: true
    endpoint: "otel-collector.monitoring.svc.cluster.local:4317"
    protocol: "grpc"
    insecure: false  # Use TLS in production
    headers:
      x-api-key: "${OTEL_API_KEY}"
    sample:
      rate: 0.25  # Sample 25% of traces
Cloud Provider Examples
DataDog (traces via agent, metrics direct ingest)
observability:
  trace:
    endpoint: "localhost:4317"
    protocol: "grpc"
    insecure: true           # OTLP gRPC to the local Datadog agent
  metrics:
    enabled: true
    endpoint: "https://api.datadoghq.com"
    protocol: "http"
    insecure: false
    headers:
      DD-API-KEY: "${DATADOG_API_KEY}"
Grafana Cloud
observability:
  trace:
    endpoint: "otlp-gateway-prod-us-central-0.grafana.net:443"
    protocol: "grpc"
    insecure: false
    headers:
      authorization: "Basic ${GRAFANA_CLOUD_TOKEN}"
Honeycomb
observability:
  trace:
    endpoint: "api.honeycomb.io:443"
    protocol: "grpc"
    insecure: false
    headers:
      x-honeycomb-team: "${HONEYCOMB_API_KEY}"
Jaeger (self-hosted)
observability:
  trace:
    endpoint: "jaeger-collector:4318"
    protocol: "http"
    insecure: true  # Or false with TLS

Configuration Reference

Top-Level Configuration
Field Type Default Description
enabled bool false Enable/disable observability (no-op when false)
service.name string (required) Service name for trace identification
service.version string "unknown" Service version for filtering/grouping
environment string "development" Deployment environment (production, staging, etc.)
Trace Configuration
Field Type Default Description
trace.enabled bool true Enable/disable tracing
trace.endpoint string "stdout" Endpoint for trace export (stdout, http, grpc)
trace.protocol string "http" OTLP protocol: "http" or "grpc"
trace.insecure bool true Use insecure connection (no TLS)
trace.headers map[string]string - Custom headers for authentication
trace.sample.rate float64 1.0 Sampling rate (0.0 = none, 1.0 = all)
trace.batch.timeout duration 5s Time to wait before sending batch
trace.export.timeout duration 30s Maximum time for export operation
trace.max.queue.size int 2048 Maximum buffered spans
trace.max.batch.size int 512 Maximum spans per batch
Metrics Configuration
Field Type Default Description
metrics.enabled bool true Enable/disable metrics
metrics.endpoint string "stdout" Endpoint for metric export (stdout, http, grpc)
metrics.protocol string Fallback to trace.protocol or "http" OTLP protocol for metrics transport
metrics.insecure bool Fallback to trace.insecure Use insecure connection (no TLS)
metrics.headers map[string]string Fallback to trace.headers Custom headers for metrics authentication
metrics.interval duration 10s Metric export interval
metrics.export.timeout duration 30s Maximum time for metric export operation

Advanced Usage

Custom Provider Configuration
import "github.com/gaborage/go-bricks/observability"

// Create custom configuration
cfg := &observability.Config{
    Enabled:     true,
    ServiceName: "my-service",
    ServiceVersion: "1.0.0",
    Environment: "production",
    Trace: observability.TraceConfig{
        Enabled:  true,
        Endpoint: "localhost:4318",
        Protocol: "http",
        Insecure: true,
        Headers: map[string]string{
            "Authorization": "Bearer token",
        },
        SampleRate:    0.1,
        BatchTimeout:  5 * time.Second,
        ExportTimeout: 30 * time.Second,
        MaxQueueSize:  2048,
        MaxBatchSize:  512,
    },
    Metrics: observability.MetricsConfig{
        Enabled:  true,
        Endpoint: "https://api.datadoghq.com",
        Protocol: "http",
        Insecure: observability.BoolPtr(false),
        Headers: map[string]string{
            "DD-API-KEY": "your-api-key",
        },
        Interval:      15 * time.Second,
        ExportTimeout: 45 * time.Second,
    },
}

// Initialize provider
provider, err := observability.NewProvider(cfg)
if err != nil {
    panic(err)
}
defer observability.Shutdown(provider, 5)
Graceful Shutdown
import "github.com/gaborage/go-bricks/observability"

// Shutdown with custom timeout (in seconds)
observability.Shutdown(provider, 10)

// Or panic on shutdown failure
observability.MustShutdown(provider, 10)

// Manual shutdown with context
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := provider.Shutdown(ctx); err != nil {
    log.Printf("Failed to shutdown observability: %v", err)
}
Force Flush
// Flush pending telemetry before critical operations
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := provider.ForceFlush(ctx); err != nil {
    log.Printf("Failed to flush telemetry: %v", err)
}

Performance Tuning

High-Throughput Services

For services with high request rates, reduce overhead:

observability:
  trace:
    sample:
      rate: 0.01  # Sample 1% of traces
    batch:
      timeout: "10s"  # Larger batches
    max:
      batch:
        size: 2048  # More spans per batch
Low-Latency Services

For latency-sensitive services, reduce export latency:

observability:
  trace:
    batch:
      timeout: "1s"  # Faster export
    max:
      batch:
        size: 128  # Smaller batches

Troubleshooting

No Traces Appearing
  1. Check observability is enabled: observability.enabled: true
  2. Verify service name: observability.service.name is set
  3. Check sampling rate: trace.sample.rate > 0.0
  4. Verify endpoint: OTLP collector is reachable
  5. Check logs: Look for initialization or export errors
Connection Errors
Error: failed to initialize trace provider: failed to create trace exporter

Solutions:

  • Verify endpoint is correct (hostname:port)
  • Check protocol matches endpoint (HTTP=4318, gRPC=4317)
  • Ensure firewall allows outbound connections
  • For TLS, verify certificates or set insecure: true for testing
Memory Issues

If observability consumes too much memory:

observability:
  trace:
    max:
      queue:
        size: 512  # Reduce buffer size
    sample:
      rate: 0.05  # Lower sampling rate

Best Practices

  1. Use stdout in development - Easy debugging without external dependencies
  2. Use OTLP in production - Industry standard with broad backend support
  3. Sample in production - Reduce costs while maintaining visibility
  4. Set proper service.name - Makes filtering and grouping easier
  5. Use environment tags - Differentiate prod/staging/dev traces
  6. Implement graceful shutdown - Ensure all traces are exported
  7. Monitor export errors - Set up alerts for failed exports
  8. Secure credentials - Use environment variables for API keys

Integration with GoBricks

The observability package integrates seamlessly with other GoBricks components:

  • HTTP Server: Automatic trace propagation via W3C traceparent headers
  • Database: Database query spans (when using instrumented drivers)
  • Messaging: AMQP message tracing (when configured)
  • Configuration: Full support for config injection via InjectInto()

See the go-bricks-demo-project for complete examples.

Documentation

Index

Constants

View Source
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"
)
View Source
const (
	// DefaultShutdownTimeout is the default timeout for graceful shutdown.
	DefaultShutdownTimeout = 10 * time.Second
)

Variables

View Source
var ErrAlreadyInitialized = errors.New("observability: provider already initialized")

ErrAlreadyInitialized is returned when attempting to initialize an already initialized provider.

View Source
var ErrInvalidCompression = errors.New("observability: compression must be either 'gzip' or 'none'")

ErrInvalidCompression is returned when the compression value is not "gzip" or "none".

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

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

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

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

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

View Source
var ErrInvalidTemporality = errors.New("observability: temporality must be either 'delta' or 'cumulative'")

ErrInvalidTemporality is returned when the temporality value is not "delta" or "cumulative".

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

View Source
var ErrNilConfig = errors.New("observability: config is nil")

ErrNilConfig is returned when Validate is called on a nil Config pointer.

View Source
var ErrNotInitialized = errors.New("observability: provider not initialized")

ErrNotInitialized is returned when attempting to use an uninitialized provider.

View Source
var ErrShutdownTimeout = errors.New("observability: shutdown timeout exceeded")

ErrShutdownTimeout is returned when graceful shutdown exceeds the timeout.

Functions

func BoolPtr

func BoolPtr(v bool) *bool

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

func Float64Ptr(v float64) *float64

Float64Ptr returns a pointer to the provided float64 value. Helpful when optional float64 configuration fields are used.

func MustShutdown

func MustShutdown(provider Provider, timeout time.Duration)

MustShutdown is like Shutdown but panics on error. Useful for cleanup in defer statements where error handling is not possible.

func Shutdown

func Shutdown(provider Provider, timeout time.Duration) error

Shutdown is a convenience function for gracefully shutting down an observability provider. It creates a context with timeout and calls the provider's Shutdown method. Returns an error if shutdown fails or times out.

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.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks the configuration for common errors. Returns an error if the configuration is invalid.

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

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.

func (*DualModeLogProcessor) OnEmit added in v0.13.0

func (p *DualModeLogProcessor) OnEmit(ctx context.Context, rec *sdklog.Record) error

OnEmit routes the log record to the appropriate processor based on log.type attribute.

func (*DualModeLogProcessor) Shutdown added in v0.13.0

func (p *DualModeLogProcessor) Shutdown(ctx context.Context) error

Shutdown shuts down 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). Falls back to trace setting when unset.
	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:"disable_stdout"`

	// 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:"slow_request_threshold"`

	// 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:"sampling_rate"`
}

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:"histogram_aggregation"`

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

func MustNewProvider(cfg *Config) Provider

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

func NewProvider(cfg *Config) (Provider, error)

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"`

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

Directories

Path Synopsis
Package testing provides utilities for testing OpenTelemetry instrumentation in GoBricks applications.
Package testing provides utilities for testing OpenTelemetry instrumentation in GoBricks applications.

Jump to

Keyboard shortcuts

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