Documentation
¶
Index ¶
- Variables
- func AddToInt64UpDownCounter(ctx context.Context, name string, value int64, ...)
- func AddToIntCounter(ctx context.Context, name string, value int64, ...)
- func FilterStackTrace(stack string, ignore []string) string
- func GRPCClientOptions() []grpc.DialOption
- func GRPCServerOptions() []grpc.ServerOption
- func GetLoggerFromContext(ctx context.Context) *zerolog.Logger
- func GetMetricValue(name string) int64
- func GetTraceID(ctx context.Context) string
- func Handler(cfg Config) func(http.Handler) http.Handler
- func InitStandardMetrics(meter metric.Meter)
- func NewHTTPClient(transport http.RoundTripper) *http.Client
- func OpenDBWithConnector(driverName string, connector driver.Connector) *sql.DB
- func OpenPGXPool(ctx context.Context, connString string, opts ...PGXOption) (*pgxpool.Pool, error)
- func OpenSQL(driverName, dsn string) (*sql.DB, error)
- func PanicHook(ignore []string) zerolog.Hook
- func RecordInFloat64Histogram(ctx context.Context, name string, value float64, ...)
- func RegisterDBStatsMetrics(db *sql.DB, instanceName string)
- func RegisterFloat64Histogram(name, description, unit string)
- func RegisterInt64Counter(name, description, unit string)
- func RegisterInt64UpDownCounter(name, description, unit string)
- func Run(ctx context.Context, name string, fn func(ctx context.Context, s State) error) (err error)
- func StartHostMetrics() error
- func StartRuntimeMetrics() error
- func WithGRPCClientInstrumentation() grpc.DialOption
- type Config
- type FileRotationConfig
- type LogConfig
- type MetricConfig
- type MetricInstrument
- type PGXOption
- type Provider
- type ShutdownFunc
- type State
- func (s State) AddEvent(name string, attributes ...attribute.KeyValue)
- func (s State) IncCounter(name string, attributes ...attribute.KeyValue)
- func (s State) RecordHistogram(name string, value float64, attributes ...attribute.KeyValue)
- func (s State) SetAttributes(attributes ...attribute.KeyValue)
- func (s State) SetBaggage(ctx context.Context, key, value string) context.Context
- type TraceConfig
Constants ¶
This section is empty.
Variables ¶
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 )
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 ¶
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 ¶
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
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
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 ¶
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 ¶
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 ¶
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
OpenPGXPool creates a new PostgreSQL connection pool with sane defaults and OpenTelemetry tracing.
func OpenSQL ¶
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 ¶
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 ¶
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
PGXOption defines a function that modifies the pgxpool configuration.
func WithPoolLimits ¶ added in v1.4.3
WithPoolLimits sets the connection pool size constraints.
func WithTimeouts ¶ added in v1.4.3
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)
type ShutdownFunc ¶
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) IncCounter ¶
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 ¶
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 ¶
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
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.