o11y

package module
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2026 License: MIT Imports: 46 Imported by: 3

README

o11y: A Standardized Observability Toolkit for Go

Go Report Card

中文 | English

o11y is a zero-configuration, convention-over-configuration observability framework for Go. It aims to provide a unified solution for logs, traces, and metrics for all Go services through an extremely simple API, minimizing cognitive load for developers.

Our Philosophy: Achieve complete observability for any piece of business logic with a single line of code.

Features

  • Flagship o11y.Run() Function: Wrap any business logic to automatically gain logging, tracing, and metrics capabilities.
  • Seamless Log Enhancement: Inside o11y.Run, your existing zerolog code will automatically be enriched with trace_id and span_id.
  • Full Stack Instrumentation:
    • HTTP: Middleware for Server (http.Handler) and Client (o11y.NewHTTPClient).
    • gRPC: Interceptors for Server and Client with panic recovery and context propagation.
    • Database: Drop-in replacement for sql.Open with o11y.OpenSQL (powered by otelsql and SQLCommenter).
  • Automated Tracing & Metrics: Automatically creates a Trace Span for the wrapped code block and records core metrics like latency, call count, and error rate.
  • Context Propagation (Baggage): Easily propagate metadata (like Tenant ID) across microservice boundaries using the State object.
  • Configuration-Driven: All features are configured via a simple YAML file.

Quick Start

Integrating o11y into your project is extremely simple.

1. Add Configuration File (config.yaml)

Create a config.yaml file in your project's root directory.

o11y:
  enabled: true
  service: "order-service"
  version: "1.2.0"
  environment: "production"
  instrumentation_scope: "o11y"

  log:
    level: "info"
    console: false # Console logging is typically disabled in production
    file: true
    rotation:
      filename: "logs/app.log"
      max_size: 100
      max_backups: 5
      max_age: 30
      compress: true

  trace:
    enabled: true
    exporter: "otlp-grpc"
    endpoint: "otel-collector:4317"
    sample_ratio: 1.0

  metric:
    enabled: true
    exporter: "prometheus"
    prometheus_path: "/metrics"
    enable_host_metrics: true
2. Initialize in main.go

Call o11y.Init() at startup and ensure shutdown is called before exit.

package main

import (
	"context"
	"net/http"
	"github.com/oy3o/o11y"
)

func main() {
	// 1. Load configuration
	cfg, _ := LoadConfig[Config]("config.yaml")

	// 2. Initialize o11y
	shutdown, _ := o11y.Init(cfg)
	defer shutdown(context.Background()) 

	// 3. Set up HTTP routes and apply the o11y middleware
	mux := http.NewServeMux()
	mux.HandleFunc("/orders", orderHandler)
	
    // Wrap the mux with observability middleware
	handler := o11y.Handler(cfg)(mux)

	http.ListenAndServe(":8080", handler)
}
3. Full Stack Instrumentation

o11y now covers your entire stack:

Database (SQL)

Drop-in replacement for sql.Open. Automatically adds Tracing (with SQL parameters) and Metrics.

// Use o11y.OpenSQL instead of sql.Open
db, err := o11y.OpenSQL("postgres", "dsn...")

// Or with a Connector (e.g., for pgx)
db := o11y.OpenDBWithConnector("pgx", connector)

// Register Connection Pool Metrics
o11y.RegisterDBStatsMetrics(db, "primary-db")
gRPC

Client and Server interceptors with panic recovery and context propagation.

// Server
s := grpc.NewServer(o11y.GRPCServerOptions()...)

// Client
conn, err := grpc.Dial(target, o11y.WithGRPCClientInstrumentation()...)
HTTP

Standard Middleware and Client wrappers.

// Server Middleware
mux = o11y.Handler(cfg)(mux)

// Client
client := o11y.NewHTTPClient(nil)
4. Empower Your Business Logic with o11y.Run()

Wrap your business code to get all observability features for free.

func processOrder(ctx context.Context, orderID string) error {
    // Wrap your logic with o11y.Run.
    // "process_order" becomes the Span name and Operation name for metrics.
    return o11y.Run(ctx, "process_order", func(ctx context.Context, s o11y.State) error {
        // s.Log already includes trace_id and span_id automatically
        log := s.Log

        // s.Log already includes trace_id and span_id automatically
        log.Info().Str("order_id", orderID).Msg("Starting to process order")

        // Simulate DB call (automatically traced via o11y.OpenSQL)
        if err := db.ExecContext(ctx, "UPDATE orders SET status = ?", "PROCESSING"); err != nil {
            return err // o11y auto-records error and updates Span status
        }

        // Manually record a custom business metric on success
        s.IncCounter("orders_processed_total")
        log.Info().Msg("Order processed successfully")
        return nil
    })
}

Advanced Usage: State Object

The State object provided by o11y.Run allows you to add rich business context and propagate baggage.

o11y.Run(ctx, "find_product", func(ctx context.Context, s o11y.State) error {
    // 1. Add attributes to the current Span (for Tracing search)
    s.SetAttributes(attribute.String("product_id", productID))
    
    // 2. Propagate Context (Baggage)
    // Adds "tier=gold" to the context, propagated to downstream services via HTTP/gRPC headers.
    // IMPORTANT: You must use the returned 'ctx' for subsequent calls.
    ctx = s.SetBaggage(ctx, "user_tier", "gold")
    
    // 3. Record Metrics (Histogram for duration/values)
    s.RecordHistogram("custom.operation.latency", 0.123)
    
    // 4. Add Timeline Event (Logs event to Trace)
    s.AddEvent("cache_miss")
    
    return nil
})

📈 Out-of-the-Box Metrics

o11y automatically collects the following standard metrics:

HTTP Server
  • http.server.request.total: Total number of requests (labels: method, route, status_code).
  • http.server.request.duration: Request latency distribution.
  • http.server.active_requests: Number of currently active requests.
Database
  • db.client.query.duration: Duration of database queries.
  • sql.db.stats.connections.open: Total number of open connections.
  • sql.db.stats.connections.idle: Number of idle connections.
  • sql.db.stats.connections.in_use: Number of connections currently in use.
Business Logic (o11y.Run)
  • biz.operation.duration: Execution duration of the business logic block.
  • biz.operation.error.total: Total number of errors in the business logic block.

Overall Architecture

o11y produces data. We recommend using the OpenTelemetry Collector to gather it, storing it in Prometheus (metrics), Loki (logs), and Jaeger/Tempo (traces), and visualizing it with Grafana.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// Tracer is the application-wide tracer, initialized by Init.
	Tracer trace.Tracer
	// Meter is the application-wide meter, initialized by Init.
	Meter metric.Meter
)
View Source
var DefaultLogIgnore = []string{
	"runtime/panic.go",
	"runtime/debug/stack.go",
	"github.com/rs/zerolog.",
	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp.",
	"net/http/server.go",

	"o11y.(*Middleware).serveHTTP",
	"o11y.initialization.PanicHook",
}

DefaultLogIgnore defines a list of common function/file path prefixes to be filtered out from panic stack traces. This significantly reduces noise, allowing developers to focus on their application's code.

Functions

func AddToInt64UpDownCounter

func AddToInt64UpDownCounter(ctx context.Context, name string, value int64, attributes ...attribute.KeyValue)

AddToInt64UpDownCounter finds a pre-registered Int64UpDownCounter and adds a value to it.

func AddToIntCounter

func AddToIntCounter(ctx context.Context, name string, value int64, attributes ...attribute.KeyValue)

AddToIntCounter finds a pre-registered Int64Counter and adds a value to it. This is the underlying implementation for the Helper's `IncCounter`.

func FilterStackTrace

func FilterStackTrace(stack string, ignore []string) string

FilterStackTrace cleans a raw stack trace string by removing irrelevant frames. It takes the raw stack and a slice of prefixes to ignore. It works by processing the stack trace in pairs of lines (function call and file path).

func GRPCClientOptions added in v1.4.0

func GRPCClientOptions() []grpc.DialOption

GRPCClientOptions 返回一组推荐的 gRPC DialOption,用于客户端集成。 包含 OTel StatsHandler。

func GRPCServerOptions added in v1.4.0

func GRPCServerOptions() []grpc.ServerOption

GRPCServerOptions 返回一组推荐的 gRPC ServerOption。 包含: 1. OpenTelemetry StatsHandler (处理 Tracing 和 Metrics) 2. Unary & Stream Interceptors (处理 Logger 注入、Panic 恢复和访问日志)

用法:

s := grpc.NewServer(o11y.GRPCServerOptions()...)

func GetLoggerFromContext

func GetLoggerFromContext(ctx context.Context) *zerolog.Logger

GetLoggerFromContext is a helper function to safely retrieve a zerolog.Logger from a context. If no logger is found in the context, it returns the global default logger.

func GetMetricValue added in v1.4.4

func GetMetricValue(name string) int64

GetMetricValue returns the current value of a registered counter. This is useful for internal dashboards/APIs that need to display current stats.

func GetTraceID added in v1.1.0

func GetTraceID(ctx context.Context) string

GetTraceID extracts the TraceID of the OpenTelemetry from the Context. If there is no valid Span in the current Context, it returns an empty string.

func Handler

func Handler(cfg Config) func(http.Handler) http.Handler

Handler is a factory function that creates a new o11y HTTP middleware. This single middleware wraps the provided handler with a complete suite of observability tools.

Usage:

mux := http.NewServeMux()
mux.HandleFunc("/", myHandler)
o11yMiddleware := o11y.Handler(cfg)
server := &http.Server{
    Addr:    ":8080",
    Handler: o11yMiddleware(mux),
}

func InitStandardMetrics

func InitStandardMetrics(meter metric.Meter)

InitStandardMetrics creates and registers all standard metrics that the o11y library provides. This function is called once by o11y.Init to populate the registry. {Namespace}.{Subsystem}.{Target}.{Suffix}

func NewHTTPClient

func NewHTTPClient(transport http.RoundTripper) *http.Client

NewHTTPClient returns a new `*http.Client` that is automatically instrumented for OpenTelemetry tracing. All requests made with this client will generate trace spans and automatically propagate the trace context.

If the `transport` argument is nil, `http.DefaultTransport` will be used.

Usage:

httpClient := o11y.NewHTTPClient(nil)
resp, err := httpClient.Get("https://api.example.com/v1/users")

func OpenDBWithConnector

func OpenDBWithConnector(driverName string, connector driver.Connector) *sql.DB

OpenDBWithConnector wraps a standard `driver.Connector` with OpenTelemetry instrumentation and returns an instrumented `*sql.DB`. This is the preferred method for integrating database observability in modern Go applications, especially when using connection pools. It automatically records trace spans, latency metrics, and connection pool status.

`driverName` should be the name of the underlying driver (e.g., "pgx", "mysql") and is used to set telemetry attributes.

Usage:

pgxConfig, _ := pgx.ParseConfig("...")
rawConnector := pgx.NewConnector(*pgxConfig)
db := o11y.OpenDBWithConnector("pgx", rawConnector)

func OpenPGXPool added in v1.4.2

func OpenPGXPool(ctx context.Context, connString string, opts ...PGXOption) (*pgxpool.Pool, error)

OpenPGXPool creates a new PostgreSQL connection pool with sane defaults and OpenTelemetry tracing.

func OpenSQL

func OpenSQL(driverName, dsn string) (*sql.DB, error)

OpenSQL is a drop-in replacement for `sql.Open` that is instrumented with OpenTelemetry. It internally calls `otelsql.Open`, automatically creating trace spans and metrics for all database operations (queries, executions, transactions, etc.). This is the easiest way to integrate o11y observability into a new database connection.

`driverName` should be the name of the underlying driver (e.g., "postgres", "mysql"). `dsn` is the data source name string.

Usage:

db, err := o11y.OpenSQL("postgres", "user=... password=... dbname=... sslmode=disable")
if err != nil {
    log.Fatal().Err(err).Msg("Failed to connect to database")
}

func PanicHook

func PanicHook(ignore []string) zerolog.Hook

PanicHook creates a zerolog.Hook that, when a panic-level event is logged, captures the current goroutine's stack trace, filters it for clarity, and adds it to the log event under the "stack" key.

func RecordInFloat64Histogram

func RecordInFloat64Histogram(ctx context.Context, name string, value float64, attributes ...attribute.KeyValue)

RecordInFloat64Histogram finds a pre-registered Float64Histogram and records a value.

func RegisterDBStatsMetrics

func RegisterDBStatsMetrics(db *sql.DB, instanceName string)

RegisterDBStatsMetrics registers callbacks to collect database connection pool statistics from a *sql.DB instance. It should be called once per database instance after it has been created. The `instanceName` is a logical identifier for the database instance (e.g., "primary-writer", "read-replica-1") and will be added as a "db.instance.id" attribute to the metrics for differentiation. This function uses the underlying otelsql.RegisterDBStatsMetrics functionality.

func RegisterFloat64Histogram added in v1.4.0

func RegisterFloat64Histogram(name, description, unit string)

RegisterFloat64Histogram creates and registers a new Float64Histogram.

func RegisterInt64Counter added in v1.4.0

func RegisterInt64Counter(name, description, unit string)

RegisterInt64Counter creates and registers a new Int64Counter. It is safe to call this concurrently after o11y.Init.

func RegisterInt64UpDownCounter added in v1.4.0

func RegisterInt64UpDownCounter(name, description, unit string)

RegisterInt64UpDownCounter creates and registers a new Int64UpDownCounter.

func Run

func Run(
	ctx context.Context,
	name string,
	fn func(ctx context.Context, s State) error,
) (err error)

Run is the flagship function of the o11y package. It wraps a block of business logic, automatically providing it with comprehensive observability: tracing, context-aware logging, and metrics for latency, calls, and errors.

func StartHostMetrics

func StartHostMetrics() error

StartHostMetrics initializes the collection of host metrics. It starts a background goroutine that periodically scrapes metrics like CPU utilization and memory usage, reporting them via the globally configured MeterProvider.

This function should be called once during application startup. It is non-blocking.

func StartRuntimeMetrics

func StartRuntimeMetrics() error

StartRuntimeMetrics initializes the collection of Go runtime metrics. It starts a background goroutine that periodically scrapes metrics like goroutine count, GC stats, and memory usage, and reports them via the globally configured MeterProvider.

This function should be called once during application startup after the global MeterProvider has been configured. It is non-blocking.

func WithGRPCClientInstrumentation

func WithGRPCClientInstrumentation() grpc.DialOption

WithGRPCClientInstrumentation returns a `grpc.DialOption` that enables OpenTelemetry instrumentation for a gRPC client via a `stats.Handler`. This is the standard, recommended method for the `otelgrpc` library.

This option automatically handles tracing and metrics for all outbound gRPC calls.

Usage:

conn, err := grpc.NewClient(
    target,
    o11y.WithGRPCClientInstrumentation(),
    grpc.WithTransportCredentials(insecure.NewCredentials()),
)

Types

type Config

type Config struct {
	// Enabled is a global switch. If set to false, o11y.Init will immediately return a no-operation shutdown function,
	// and will not initialize any logs, traces, or metrics components. This is very useful in local development or testing environments.
	Enabled bool `yaml:"enabled" mapstructure:"enabled"`

	// Service is your service name (e.g., "user-service", "order-api").
	// This name will serve as the core identifier for all telemetry data (logs, traces, metrics).
	// It is recommended to use the `service.name` format from the OpenTelemetry semantics convention.
	Service string `yaml:"service" mapstructure:"service"`

	// Version is the current version number of your service (e.g., "v1.2.3", "2025.11.18").
	// This will be appended to the telemetry data to track performance and bugs across different versions.
	Version string `yaml:"version" mapstructure:"version"`

	// Environment is the environment in which the service runs (e.g., "development", "staging", "production").
	// This tag helps filter and isolate data from different environments in the backend system.
	Environment string `yaml:"environment" mapstructure:"environment"`

	// InstrumentationScope is the name of the tracer and meter used by the library.
	// It's a logical unit of instrumentation. Defaults to "o11y".
	InstrumentationScope string `yaml:"instrumentation_scope" mapstructure:"instrumentation_scope"`

	// Log contains all configurations related to logging.
	Log LogConfig `yaml:"log" mapstructure:"log"`

	// Trace contains all configurations related to distributed tracing.
	Trace TraceConfig `yaml:"trace" mapstructure:"trace"`

	// Metric contains all configurations related to metric statistics.
	Metric MetricConfig `yaml:"metric" mapstructure:"metric"`
}

Config is the only configuration struct in the o11y package. It aggregates all configurable items for logs, traces, and metrics, and provides global metadata.

type FileRotationConfig

type FileRotationConfig struct {
	// Filename is the full path to the log file to be written.
	Filename string `yaml:"filename" mapstructure:"filename"`

	// MaxSize is the maximum size of a single log file before rotation, in MB.
	MaxSize int `yaml:"max_size" mapstructure:"max_size"`

	// MaxBackups is the maximum number of old log files to retain.
	MaxBackups int `yaml:"max_backups" mapstructure:"max_backups"`

	// MaxAge is the maximum number of days old log files are retained before deletion.
	MaxAge int `yaml:"max_age" mapstructure:"max_age"`

	// Compress controls whether to use gzip compression for rotated old log files.
	Compress bool `yaml:"compress" mapstructure:"compress"`
}

FileRotationConfig defines the file rotation configuration for the Lumberjack library.

type LogConfig

type LogConfig struct {
	// Level defines the global minimum log level.
	// Optional values are "debug", "info", "warn", "error", "fatal", "panic".
	// If set to empty or invalid value, it will default to "info".
	Level string `yaml:"level" mapstructure:"level"`

	// TimePrecision defines the format and precision of the timestamps in the log.
	// Optional values:
	// "s": Unix timestamp in seconds (e.g., 1678886400)
	// "ms": Unix timestamp in milliseconds (e.g., 1678886400123)
	// "us": Unix timestamp in microseconds (e.g., 1678886400123456)
	// "ns": Unix timestamp in nanoseconds (e.g., 1678886400123456789)
	// Defaults to "ms", which is a good balance between performance and precision.
	TimePrecision string `yaml:"time_precision" mapstructure:"time_precision"`

	// EnableCaller controls whether the caller's filename and line number are included in log entries.
	// Enabling this option incurs a slight performance overhead; it is recommended to enable it in development environments for debugging purposes.
	EnableCaller bool `yaml:"caller" mapstructure:"caller"`

	// EnableConsole controls whether logs are output to standard output (stdout).
	// Logs output to the console are typically colored and in a human-readable format.
	EnableConsole bool `yaml:"console" mapstructure:"console"`

	// EnableFile controls whether logs are output to a file.
	// Logs output to a file are always in JSON format for easy machine parsing.
	EnableFile bool `yaml:"file" mapstructure:"file"`

	// FileRotation defines the log file rotation strategy; it only takes effect when EnableFile is true.
	FileRotation FileRotationConfig `yaml:"rotation" mapstructure:"rotation"`

	// StackFilters is a list of string prefixes used to filter out irrelevant stack frames in a panic hook.
	// This helps clean up panic logs, allowing developers to focus on the application code itself.
	// For example: "runtime/", "net/http".
	StackFilters []string `yaml:"stack_filters" mapstructure:"stack_filters"`
}

LogConfig defines the detailed behavior of logging.

type MetricConfig

type MetricConfig struct {
	// Enabled controls whether metric statistics are enabled.
	Enabled bool `yaml:"enabled" mapstructure:"enabled"`

	// Exporter defines the method for exporting metrics.
	// Optional values:
	// "prometheus": Exposes an HTTP endpoint for the Prometheus service to pull data (recommended).
	// "none": Enables the metrics API but discards all data.
	Exporter string `yaml:"exporter" mapstructure:"exporter"`

	// PrometheusPath is the HTTP path exposed by the Prometheus Exporter, used only when the Exporter is "prometheus".
	// The default and common value is "/metrics".
	PrometheusPath string `yaml:"prometheus_path" mapstructure:"prometheus_path"`

	// PrometheusAddr is the address (host:port) on which the Prometheus metrics server will listen.
	// Defaults to ":2222".
	PrometheusAddr string `yaml:"prometheus_addr" mapstructure:"prometheus_addr"`

	// EnableHostMetrics controls whether to automatically collect host metrics (e.g., CPU, memory).
	// If true, the library will start a collector for host metrics upon initialization.
	EnableHostMetrics bool `yaml:"enable_host_metrics" mapstructure:"enable_host_metrics"`
}

MetricConfig defines the configuration for metric statistics.

type MetricInstrument

type MetricInstrument struct {
	Int64Counter       metric.Int64Counter
	Float64Histogram   metric.Float64Histogram
	Int64UpDownCounter metric.Int64UpDownCounter
}

MetricInstrument holds a generic OpenTelemetry instrument. Using a struct allows us to store different instrument types (Counter, Histogram, etc.) under a single map entry, providing type safety when we retrieve them.

type PGXOption added in v1.4.3

type PGXOption func(*pgxpool.Config)

PGXOption defines a function that modifies the pgxpool configuration.

func WithPoolLimits added in v1.4.3

func WithPoolLimits(min, max int) PGXOption

WithPoolLimits sets the connection pool size constraints.

func WithTimeouts added in v1.4.3

func WithTimeouts(maxLifetime, maxIdleTime time.Duration) PGXOption

WithTimeouts sets the connection lifecycle timeouts.

type Provider added in v1.4.1

type Provider struct {
	Tracer trace.Tracer
	Meter  metric.Meter
	Logger zerolog.Logger
	// contains filtered or unexported fields
}

func New added in v1.4.1

func New(cfg Config,
	setupLogging func(cfg LogConfig) (zerolog.Logger, ShutdownFunc),
	setupTracing func(cfg TraceConfig, res *resource.Resource) (trace.TracerProvider, ShutdownFunc, error),
	setupMetrics func(cfg MetricConfig, res *resource.Resource) (metric.MeterProvider, ShutdownFunc, error),
) (*Provider, error)

func (*Provider) Shutdown added in v1.4.1

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

Shutdown 关闭 Provider

type ShutdownFunc

type ShutdownFunc func(ctx context.Context) error

ShutdownFunc is a function signature for gracefully shutting down an observability component. Applications should use `defer` to call the shutdown function returned by Init before main exits.

func Init

func Init(cfg Config) (ShutdownFunc, error)

Init initializes all observability components (logging, tracing, metrics) based on the provided configuration. It is the primary entry point for the o11y library. It will panic on critical setup failures. It returns a single aggregate ShutdownFunc that must be called to ensure all components are closed gracefully.

type State

type State struct {

	// Log is a zerolog.Logger instance pre-configured with the correct trace_id and span_id.
	// Developers should use this for all logging within the o11y.Run block to ensure
	// logs are automatically correlated with traces.
	Log zerolog.Logger
	// contains filtered or unexported fields
}

State is the primary interaction object provided within the o11y.Run closure. It encapsulates logging, tracing, and metric functionalities tied to the current operation, providing a simplified and consistent API for all observability needs.

func (State) AddEvent

func (s State) AddEvent(name string, attributes ...attribute.KeyValue)

AddEvent records a timestamped event on the current span's timeline.

func (State) IncCounter

func (s State) IncCounter(name string, attributes ...attribute.KeyValue)

IncCounter increments a pre-registered counter metric by 1. This is the standard way to count occurrences of an event, such as a cache hit or a login attempt. The metric name must correspond to a counter pre-registered in the metric_registry.

Example:

s.IncCounter("cache.client.operation.total", attribute.String("result", "hit"))

func (State) RecordHistogram

func (s State) RecordHistogram(name string, value float64, attributes ...attribute.KeyValue)

RecordHistogram records a value in a pre-registered histogram metric. This is ideal for measuring the distribution of values, most commonly for timing and latency. The value is typically a duration converted to a float64. The metric name must correspond to a histogram pre-registered in the metric_registry.

Example:

startTime := time.Now()
// ... perform a database operation ...
duration := time.Since(startTime).Seconds()
s.RecordHistogram("db.client.query.duration", duration, attribute.String("db.table", "users"))

func (State) SetAttributes

func (s State) SetAttributes(attributes ...attribute.KeyValue)

SetAttributes adds key-value attributes to the current trace span. This is equivalent to adding a "tag" or "label" to the span, which is invaluable for filtering, searching, and analyzing traces in backends like Jaeger or Tempo. The value can be of any standard type (string, int, bool, float, etc.).

Example:

s.SetAttributes(attribute.Int("user_id", 12345), attribute.Int("http.request.content_length", 512))

func (State) SetBaggage added in v0.2.0

func (s State) SetBaggage(ctx context.Context, key, value string) context.Context

SetBaggage adds a key-value pair to the OpenTelemetry Baggage. Baggage is used to propagate context across process boundaries (e.g., to downstream services).

IMPORTANT: Unlike SetAttributes, Baggage is stored in the Context. This method returns a NEW Context containing the updated Baggage. You MUST use the returned Context for subsequent calls (like HTTP requests) if you want the baggage to propagate.

Example:

ctx = s.SetBaggage(ctx, "tenant_id", "1001")
http.NewRequestWithContext(ctx, ...)

type TraceConfig

type TraceConfig struct {
	// Enabled controls whether distributed tracing is enabled.
	Enabled bool `yaml:"enabled" mapstructure:"enabled"`

	// Exporter defines where to send tracing data.
	// Optional values:
	// "otlp-grpc": Sends data to the OpenTelemetry Collector via gRPC (recommended).
	// "stdout": Prints tracing data to standard output in a human-readable format for debugging.
	// "none": Enables the tracing API but discards all data for testing.
	Exporter string `yaml:"exporter" mapstructure:"exporter"`

	// Endpoint is the target address of the OTLP Exporter, used only when the Exporter is "otlp-grpc".
	// The format is usually "hostname:port", for example, "otel-collector:4317".
	Endpoint string `yaml:"endpoint" mapstructure:"endpoint"`

	// OtlpInsecure controls whether the OTLP gRPC client connection should be insecure.
	// Set to true for local development when TLS is not available. Defaults to false.
	OtlpInsecure bool `yaml:"otlp_insecure" mapstructure:"otlp_insecure"`

	// SampleRatio defines the sampling rate of the traces, with values between 0.0 and 1.0.
	// 1.0 means sampling all traces.
	// 0.5 means sampling 50% of the traces.
	// 0.0 means not sampling any traces.
	SampleRatio float64 `yaml:"sample_ratio" mapstructure:"sample_ratio" validate:"min=0,max=1"`
}

TraceConfig defines the configuration for distributed tracing.

Directories

Path Synopsis
example
grpc_server command
log-agent command
server command

Jump to

Keyboard shortcuts

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