Documentation
¶
Index ¶
- func Counter(meter metric.Meter, name, description, unit string) (metric.Int64Counter, error)
- func ForceGC()
- func Gauge(meter metric.Meter, name, description, unit string) (metric.Int64UpDownCounter, error)
- func GetMemoryStats() runtime.MemStats
- func Histogram(meter metric.Meter, name, description, unit string, buckets []float64) (metric.Float64Histogram, error)
- func MemoryUsageMB() float64
- func NumGoroutines() int
- type CacheMetrics
- func (c *CacheMetrics) RecordDelete(ctx context.Context, duration time.Duration, success bool)
- func (c *CacheMetrics) RecordEviction(ctx context.Context, count int64)
- func (c *CacheMetrics) RecordGet(ctx context.Context, operation string, hit bool, duration time.Duration, ...)
- func (c *CacheMetrics) RecordSet(ctx context.Context, duration time.Duration, size int64, success bool)
- func (c *CacheMetrics) UpdateConnections(ctx context.Context, count int64)
- type DBMetrics
- type HTTPMetrics
- func (h *HTTPMetrics) DecrementActiveRequests(ctx context.Context, method string)
- func (h *HTTPMetrics) IncrementActiveRequests(ctx context.Context, method string)
- func (h *HTTPMetrics) Middleware() func(http.Handler) http.Handler
- func (h *HTTPMetrics) RecordRequest(ctx context.Context, method, route string, statusCode int, ...)
- type RuntimeMetrics
- type RuntimeMonitor
- type SystemMetrics
- type SystemMetricsConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Counter ¶
Counter creates a generic Int64 counter metric.
A counter represents a monotonically increasing value, typically used for tracking events, requests, or other counts that only go up.
Parameters: - meter: the OpenTelemetry Meter used to register the counter. - name: the metric name (should be globally unique). - description: human-readable description of the metric. - unit: the unit of measurement (e.g., "{request}", "By").
Returns an Int64Counter ready to be incremented via Add().
func ForceGC ¶
func ForceGC()
ForceGC triggers an explicit garbage collection cycle.
Use with caution in production systems, as it can introduce latency and performance overhead. Intended for testing, benchmarking, or forcing GC prior to critical memory operations.
func Gauge ¶
Gauge creates a generic Int64 up-down counter metric (used as a gauge).
Gauges represent values that can go up or down, such as current memory usage, queue length, or number of active sessions.
Parameters: - meter: the OpenTelemetry Meter used to register the gauge. - name: the metric name (should be globally unique). - description: human-readable description of the metric. - unit: the unit of measurement (e.g., "{session}", "By").
Returns an Int64UpDownCounter that can be incremented or decremented.
func GetMemoryStats ¶
GetMemoryStats returns the current Go runtime memory statistics.
It wraps runtime.ReadMemStats and provides an instantaneous snapshot of memory allocation and garbage collection state. This helper is primarily intended for debugging or manual instrumentation.
func Histogram ¶
func Histogram(meter metric.Meter, name, description, unit string, buckets []float64) (metric.Float64Histogram, error)
Histogram creates a generic Float64 histogram metric.
A histogram records the distribution of values over time, allowing observation of percentiles, min/max, and other statistical summaries.
Parameters: - meter: the OpenTelemetry Meter used to register the histogram. - name: the metric name (should be globally unique). - description: human-readable description of the metric. - unit: the unit of measurement (e.g., "ms", "By"). - buckets: optional explicit bucket boundaries for the histogram.
Returns a Float64Histogram ready to observe values.
func MemoryUsageMB ¶
func MemoryUsageMB() float64
MemoryUsageMB reports the current heap memory allocation in megabytes.
This provides a simplified and human-readable metric for dashboards, logs, or lightweight monitoring systems.
func NumGoroutines ¶
func NumGoroutines() int
NumGoroutines returns the number of currently active goroutines.
It wraps runtime.NumGoroutine() for convenience and can be used in lightweight monitoring scenarios.
Types ¶
type CacheMetrics ¶
type CacheMetrics struct {
// contains filtered or unexported fields
}
CacheMetrics provides strongly-typed OpenTelemetry instruments for monitoring cache performance and behavior across Redis, Memcached, or in-memory cache implementations.
It tracks operation counts, hit/miss ratios, latency distributions, item sizes, connection changes, eviction rates, and error occurrences. All metrics are pre-registered with semantic naming and recommended units for production-grade observability.
func NewCacheMetrics ¶
func NewCacheMetrics(meter metric.Meter) (*CacheMetrics, error)
NewCacheMetrics initializes and registers all cache-related metric instruments.
Each metric follows OpenTelemetry naming conventions and includes explicit bucket boundaries for latency and item size distributions.
The returned CacheMetrics instance can be safely reused across multiple cache clients or services, as all instruments are thread-safe.
Example:
meter := global.Meter("myapp/cache")
cacheMetrics, err := NewCacheMetrics(meter)
if err != nil {
log.Fatal("failed to initialize cache metrics", err)
}
Production recommendations:
- Instantiate this once per process to avoid redundant registration.
- Combine with tracing spans for full cache performance visibility.
- Use consistent `cache.operation` attributes for better aggregation.
func (*CacheMetrics) RecordDelete ¶
RecordDelete records a cache DELETE operation with its latency and success flag.
Errors during deletion increment the `cache.errors` counter. Duration is captured in seconds.
Example:
start := time.Now() ok := cache.Delete(key) cacheMetrics.RecordDelete(ctx, time.Since(start), ok)
Production recommendations:
- Use this in cleanup jobs and TTL-based eviction logic.
- Include `cache.operation="delete"` for unified metric labeling.
func (*CacheMetrics) RecordEviction ¶
func (c *CacheMetrics) RecordEviction(ctx context.Context, count int64)
RecordEviction increments the total eviction counter.
This should be called whenever an item is evicted by cache policy, e.g., LRU or TTL expiration.
Example:
cacheMetrics.RecordEviction(ctx, 1)
Production recommendations:
- Correlate with hit/miss ratio for cache efficiency analysis.
func (*CacheMetrics) RecordGet ¶
func (c *CacheMetrics) RecordGet(ctx context.Context, operation string, hit bool, duration time.Duration, size int64)
RecordGet records a cache GET operation with its latency, hit status, and item size when available.
It increments both the total operation count and the corresponding hit/miss counters. The operation duration is recorded in seconds.
Example:
start := time.Now() value, ok := cache.Get(key) cacheMetrics.RecordGet(ctx, "get", ok, time.Since(start), int64(len(value)))
Production recommendations:
- Always measure latency for GET operations.
- Include consistent `cache.operation` attributes across services.
func (*CacheMetrics) RecordSet ¶
func (c *CacheMetrics) RecordSet(ctx context.Context, duration time.Duration, size int64, success bool)
RecordSet records a cache SET operation, including latency, item size, and success state.
When a SET operation fails, the method increments the `cache.errors` counter. Size distributions and latency histograms are updated automatically.
Example:
start := time.Now() ok := cache.Set(key, value) cacheMetrics.RecordSet(ctx, time.Since(start), int64(len(value)), ok)
Production recommendations:
- Record both duration and success/failure status.
- For high-throughput caches, ensure histogram aggregation is optimized.
func (*CacheMetrics) UpdateConnections ¶
func (c *CacheMetrics) UpdateConnections(ctx context.Context, count int64)
UpdateConnections adjusts the number of active cache connections.
Use a positive value to increment, or a negative value to decrement the current active connection count.
Example:
cacheMetrics.UpdateConnections(ctx, +1) // on connect cacheMetrics.UpdateConnections(ctx, -1) // on disconnect
Production recommendations:
- Track connection churn to identify connection leaks or pool exhaustion.
- Combine with latency histograms for end-to-end performance insights.
type DBMetrics ¶
type DBMetrics struct {
// contains filtered or unexported fields
}
DBMetrics provides strongly-typed OpenTelemetry instruments for monitoring database client performance and reliability.
It tracks query durations, operation counts, connection usage, and error occurrences across any SQL or NoSQL backend. Metrics follow OpenTelemetry semantic conventions (`db.client.*`) and are suitable for production-grade observability pipelines.
func NewDBMetrics ¶
NewDBMetrics initializes and registers all database-related metrics.
Each metric is configured with explicit boundaries and semantic naming aligned with OpenTelemetry standards. The resulting DBMetrics instance can be safely reused across multiple database clients or connection pools.
Example:
meter := global.Meter("myapp/db")
dbMetrics, err := NewDBMetrics(meter)
if err != nil {
log.Fatal("failed to initialize DB metrics", err)
}
Production recommendations:
- Instantiate this once per process or connection pool.
- Record all queries, including read-only and transactional operations.
- Correlate query latency with tracing spans for end-to-end insight.
func (*DBMetrics) RecordQuery ¶
func (d *DBMetrics) RecordQuery( ctx context.Context, operation string, table string, duration time.Duration, success bool, )
RecordQuery records execution metrics for a single database query.
It captures latency (in seconds), total query count, and error occurrences. The method automatically attaches contextual attributes such as operation type and table (collection) name.
Example:
start := time.Now() rows, err := db.QueryContext(ctx, "SELECT * FROM users") dbMetrics.RecordQuery(ctx, "SELECT", "users", time.Since(start), err == nil)
Production recommendations:
- Call this after every database interaction.
- Maintain consistent `db.operation` and `db.collection.name` attributes.
- Use `success=false` for retries or failed queries to improve accuracy.
func (*DBMetrics) UpdateConnections ¶
UpdateConnections updates the number of active database connections.
This metric should be used to reflect connection pool activity. Increment by positive values when a connection is opened, and decrement when closed.
Example:
dbMetrics.UpdateConnections(ctx, +1) // on connection open dbMetrics.UpdateConnections(ctx, -1) // on connection close
Production recommendations:
- Use this in connection pool hooks or middleware.
- Monitor for connection leaks or saturation in long-lived services.
type HTTPMetrics ¶
type HTTPMetrics struct {
// contains filtered or unexported fields
}
HTTPMetrics provides production-ready OpenTelemetry instruments for HTTP server observability.
It tracks total request count, duration distributions, request and response sizes, and the number of active requests currently being processed. All metrics comply with the OpenTelemetry semantic conventions (`http.server.*`).
This struct is designed for high-throughput environments and can be safely shared across multiple HTTP handlers or middleware components.
func NewHTTPMetrics ¶
func NewHTTPMetrics(meter metric.Meter) (*HTTPMetrics, error)
NewHTTPMetrics initializes and registers a complete set of HTTP server metrics.
Each instrument is configured with explicit bucket boundaries suitable for web traffic latency and payload size analysis. The resulting HTTPMetrics instance can be reused safely across multiple servers or routes.
Example:
meter := global.Meter("myapp/http")
httpMetrics, err := NewHTTPMetrics(meter)
if err != nil {
log.Fatal("failed to initialize HTTP metrics", err)
}
Production recommendations:
- Instantiate once per service process to ensure consistent aggregation.
- Combine with tracing spans for end-to-end latency correlation.
- Follow OpenTelemetry's semantic naming to align with dashboards.
func (*HTTPMetrics) DecrementActiveRequests ¶
func (h *HTTPMetrics) DecrementActiveRequests(ctx context.Context, method string)
DecrementActiveRequests decrements the counter tracking active HTTP requests.
Call this when a request completes or is aborted.
Example:
defer httpMetrics.DecrementActiveRequests(ctx)
Production recommendations:
- Always ensure balanced increments and decrements.
- Combine with circuit breakers to detect overload conditions.
func (*HTTPMetrics) IncrementActiveRequests ¶
func (h *HTTPMetrics) IncrementActiveRequests(ctx context.Context, method string)
IncrementActiveRequests increments the counter tracking active HTTP requests.
Call this when a new request starts processing.
Example:
httpMetrics.IncrementActiveRequests(ctx)
Production recommendations:
- Use middleware to increment/decrement automatically.
- Useful for identifying overload or concurrency spikes.
func (*HTTPMetrics) Middleware ¶
func (h *HTTPMetrics) Middleware() func(http.Handler) http.Handler
Middleware returns a Chi-compatible middleware that automatically records HTTP metrics for all requests.
The middleware tracks:
- Total requests count
- Request duration
- Request and response sizes
- Active concurrent requests
Example usage with Chi router:
httpMetrics, _ := metrics.NewHTTPMetrics(meter)
router := chi.NewRouter()
router.Use(httpMetrics.Middleware())
router.Get("/api/users", handler)
The middleware extracts the route pattern from Chi's RouteContext, ensuring that metrics are grouped by route template (e.g., "/users/{id}") rather than individual paths (e.g., "/users/123").
Production recommendations:
- Mount early in the middleware chain for accurate timing.
- Combine with error handling middleware to capture all requests.
- Use Chi's route patterns for consistent metric labels.
func (*HTTPMetrics) RecordRequest ¶
func (h *HTTPMetrics) RecordRequest( ctx context.Context, method, route string, statusCode int, duration time.Duration, requestSize, responseSize int64, )
RecordRequest records all relevant metrics for a completed HTTP request.
It updates the total request count, duration histogram, and size distributions for both request and response payloads. Attributes include method, route, and status code for fine-grained observability.
Example:
start := time.Now()
resp, err := handler(req)
httpMetrics.RecordRequest(
ctx,
req.Method,
"/api/v1/users",
resp.StatusCode,
time.Since(start),
req.ContentLength,
resp.ContentLength,
)
Production recommendations:
- Invoke this after each request completes.
- Ensure route labels are normalized (avoid user-specific paths).
- Correlate request duration with error rate to detect latency regressions.
type RuntimeMetrics ¶
type RuntimeMetrics struct {
// contains filtered or unexported fields
}
RuntimeMetrics provides a comprehensive set of metrics that describe the Go process state in real time.
It includes CPU user/system time, memory allocation statistics, garbage collection behavior, number of active goroutines, system threads, and cgo call counts. Metrics are gathered using OpenTelemetry asynchronous instruments and reported automatically through a registered callback.
This type is thread-safe and optimized for low-overhead collection.
func NewRuntimeMetrics ¶
func NewRuntimeMetrics(meter metric.Meter) (*RuntimeMetrics, error)
NewRuntimeMetrics creates and registers all standard runtime metrics for the current Go process using the provided OpenTelemetry Meter.
Metrics include CPU (user/system), heap memory, stack usage, garbage collection, goroutines, threads, and cgo calls.
The function registers an internal callback to collect metrics periodically. Once created, no further manual updates are required.
Returns an initialized *RuntimeMetrics or an error if any metric instrument fails to be registered.
type RuntimeMonitor ¶
type RuntimeMonitor struct {
// contains filtered or unexported fields
}
RuntimeMonitor manages a background monitoring loop for runtime metrics.
Although runtime metrics are collected asynchronously by OpenTelemetry, this structure can be used to trigger additional tasks at a fixed interval, such as structured logging or system health verification.
The monitor can be safely started and stopped using its lifecycle methods.
func NewRuntimeMonitor ¶
func NewRuntimeMonitor(metrics *RuntimeMetrics, interval time.Duration) *RuntimeMonitor
NewRuntimeMonitor creates a new RuntimeMonitor that operates at the specified interval. If the interval is set to zero, a default of 10 seconds is applied.
The monitor requires an initialized RuntimeMetrics instance to operate.
func (*RuntimeMonitor) Start ¶
func (rm *RuntimeMonitor) Start(ctx context.Context)
Start launches the monitoring loop.
The loop runs until either Stop() is called or the provided context is cancelled. While metrics are automatically collected via OpenTelemetry callbacks, this loop can be extended to perform additional diagnostics or custom periodic actions.
func (*RuntimeMonitor) Stop ¶
func (rm *RuntimeMonitor) Stop()
Stop gracefully terminates the monitoring loop started by Start.
It ensures a clean shutdown of background operations.
type SystemMetrics ¶
type SystemMetrics struct {
// contains filtered or unexported fields
}
SystemMetrics encapsulates all system-level observables.
It maintains OpenTelemetry gauges and counters for every supported metric category, as well as internal state for delta calculation on counters (disk I/O and network).
func NewSystemMetrics ¶
func NewSystemMetrics(meter metric.Meter, config SystemMetricsConfig) (*SystemMetrics, error)
NewSystemMetrics initializes a SystemMetrics instance and registers all OpenTelemetry observables with the provided meter.
All metrics are automatically updated via a callback. This function returns a fully initialized SystemMetrics ready for integration with monitoring pipelines.
Example usage:
meter := otel.Meter("example")
sm, err := NewSystemMetrics(meter, SystemMetricsConfig{DiskPath: "/"})
if err != nil {
log.Fatal(err)
}
Notes: - Disk and network counters use delta calculations between observations. - Metrics are safe for concurrent collection.
type SystemMetricsConfig ¶
type SystemMetricsConfig struct {
DiskPath string // Path to monitor disk usage (default: "/")
}
SystemMetricsConfig configures which system metrics to monitor.
DiskPath specifies the mount point for disk metrics (default: "/").