zpm

package module
v0.0.0-...-89f2390 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2025 License: MIT Imports: 11 Imported by: 0

README

zeroprom - zerolog-inspired High-Performance Prometheus Metrics Wrapper

zpm is a minimalistic and efficient Prometheus metrics wrapper for Go, designed for high-performance applications. It simplifies counter and histogram metric handling while ensuring concurrency safety.

Features

Simplicity – Easy-to-use API with minimal setup
🚀 Efficiency – Optimized for high-performance applications
🔒 Thread-Safe – Designed for concurrent access in multithreaded applications
🔖 Labeled – Supports labeled counters and histograms for better observability
📡 Compatible – Exposes metrics in a Prometheus-friendly format
🛠 Customizable – Supports different output formats using expfmt

Installation

go get github.com/xakepp35/zpm

Examples

// measure and perform your call
startedAt := time.Now()
res, err := PerformMyRequest()
latencyMs := time.Since(startedAt).Seconds()/1000

// zerolog example, for visual comparison:
log.Info().
    Err(err).
    Any("res", res).
    Str("func", zpm.RuntimeFunctionName(0)).
    Msg("request")

// counter example:
zpm.Counter("http_requests_total").
    Help("http requests counter").
    Label("method", r.Method).
    Label("path", r.URL.Path).
    Inc(1)

// gauge example:
zpm.Gauge("http_requests_gauge").
    Help("http requests latency gauge").
    Label("method", r.Method).
    Label("path", r.URL.Path).
    Set(latencyMs)

// histogrtam example:
zpm.Histogram("http_duration_milliseconds").
    Help("http requests duration histogram").
    Buckets(1, 10, 100, 1000).
    Label("method", r.Method).
    Label("path", r.URL.Path).
    Observe(latencyMs)

// summary example:
zpm.Summary("http_duration_summary_milliseconds").
    Help("http requests duration summary").
    Quantiles(0, 0.1, 0.5, 0.9, 1).
    Label("method", r.Method).
    Label("path", r.URL.Path).
    Observe(latencyMs)

License

This project is licensed under the MIT License.

Documentation

Overview

@host localhost:8080 @BasePath /metrics

Index

Constants

This section is empty.

Variables

View Source
var (
	FmtTextPlain = expfmt.NewFormat(expfmt.TypeTextPlain)
)
View Source
var Srv = NewServer()

singletone

Functions

func Bytes

func Bytes(format expfmt.Format, opts ...expfmt.EncoderOption) (string, error)

Bytes ➕

@Summary Exports metrics as raw bytes in the specified format.
@Description This function exports the metrics as raw bytes in a specified format, allowing for further processing or transport.
@Tags metrics
@Produce application/octet-stream
@Param format query string true "The format to export the metrics in (e.g., 'text/plain')"
@Param options query string false "Additional encoding options"
@Usage Export metrics for machine-to-machine communication or internal processing.

func Counter

func Counter(name string) *counter

Counter ➕

@Summary Creates a new counter metric.
@Description This function creates a counter, a cumulative metric that only increases. Suitable for tracking things like requests served, errors, etc.
@Tags metrics
@Produce text/plain
@Param name query string true "Name of the counter metric"
@Usage Tracking events such as processed jobs or HTTP requests.
@Misuse ❌ Using for fluctuating values (use Gauge instead).
@Misuse ❌ Decreasing a counter (use Gauge for that).
@Pros ✅ Ideal for cumulative data.
@Pros ✅ Works seamlessly with `rate()` and `increase()` Prometheus functions.
@Cons ⚠️ Cannot be decremented.
@Tricks 🔍 Use `rate()` for trend analysis over time.

func Export

func Export(w io.Writer, expFormat expfmt.Format, opts ...expfmt.EncoderOption) error

Export ➕

@Summary Exports metrics in a specified format.
@Description This function exports cumulative metrics, such as counters, in a desired format. Common use cases include exporting metrics for Prometheus scraping.
@Tags metrics
@Produce text/plain
@Param format query string true "The format to export the metrics in, e.g., 'text/plain'"
@Param options query string false "Additional encoding options"
@Usage Export metrics like processed jobs, HTTP request counts, etc.
@Misuse ❌ Using for fluctuating values (use Gauge for that).
@Misuse ❌ Attempting to decrease a counter (use Gauge instead).
@Pros ✅ Efficient for tracking incremental data.
@Pros ✅ Works well with `rate()` and `increase()` for Prometheus queries.
@Cons ⚠️ Cannot be decremented, reset is needed on restart.
@Tricks 🔍 Use `rate()` to track trends over time.

func Gauge

func Gauge(name string) *gauge

Gauge ⚖️

@Summary Creates a new gauge metric.
@Description This function creates a gauge, a metric that can increase or decrease. Suitable for tracking values like temperature, memory usage, or concurrent requests.
@Tags metrics
@Produce text/plain
@Param name query string true "Name of the gauge metric"
@Usage Tracking instantaneous values like RAM usage, active users.
@Misuse ❌ Using for cumulative counts (use Counter instead).
@Pros ✅ Works well for instantaneous values.
@Pros ✅ Can both increase and decrease over time.
@Cons ⚠️ Quick fluctuations may make trend analysis challenging.
@Tricks 📊 Use `avg_over_time()` to smooth out variations and identify trends.

func Histogram

func Histogram(name string) *histogram

Histogram 📊

@Summary Creates a histogram metric for sampling observations.
@Description This function creates a histogram, which samples observations and categorizes them into configurable buckets. Useful for tracking durations or distributions.
@Tags metrics
@Produce text/plain
@Param name query string true "Name of the histogram metric"
@Usage Tracking response times, request sizes, or latencies.
@Misuse ❌ Too many buckets can lead to excessive memory usage.
@Pros ✅ Captures both the count and sum of observations.
@Pros ✅ Useful for estimating quantiles and understanding distributions.
@Cons ⚠️ Requires predefined bucket configuration.
@Cons ⚠️ `histogram_quantile()` can produce misleading results with small samples.
@Tricks ⚡ Use the `le` label (`le="+Inf"`) to track total count. 🛠️ Use `rate()` on `_bucket` metrics for percentile estimations.

func NewStorage

func NewStorage() *storage

func RuntimeFuncName

func RuntimeFuncName(skip int) string

func String

func String(format expfmt.Format, opts ...expfmt.EncoderOption) (string, error)

String ➕

@Summary Exports metrics as a string in the specified format.
@Description This function exports the metrics as a string, supporting formats such as text/plain for Prometheus scraping or others as specified.
@Tags metrics
@Produce text/plain
@Param format query string true "The format to export the metrics in (e.g., 'text/plain')"
@Param options query string false "Additional encoding options"
@Usage Export metrics in a human-readable format or for Prometheus scraping.
@Misuse ❌ Using for non-cumulative metrics (use appropriate types).
@Tricks 📊 Use `rate()` in Prometheus queries for trend analysis.

func Summary

func Summary(name string) *summary

Summary 💡

@Summary Creates a summary metric for tracking dynamic quantiles.
@Description This function creates a summary, a metric that calculates quantiles and total observations on the client side. Ideal for latency tracking where dynamic quantiles are needed.
@Tags metrics
@Produce text/plain
@Param name query string true "Name of the summary metric"
@Usage Tracking request durations with precomputed quantiles, useful for latency analysis.
@Misuse ❌ Hard to aggregate across multiple instances (unlike Histograms).
@Pros ✅ Provides dynamic quantiles without predefined buckets.
@Cons ⚠️ Requires more memory than Histograms.
@Tricks 🎯 Use `quantile(0.95, rate(my_summary{quantile!=""}[5m]))` to estimate the 95th percentile of request durations.

Types

type LabelPair

type LabelPair = dto.LabelPair

type LabelPairs

type LabelPairs = []*LabelPair

func NewLabelPairs

func NewLabelPairs(keyValues ...string) LabelPairs

NewLabelPairs param keyValues is an interleaved key-value-key-value... slice.

type Metric

type Metric = dto.Metric

type Server

type Server struct {
	// contains filtered or unexported fields
}

func NewServer

func NewServer() *Server

func SortNames

func SortNames(sortNames bool) *Server

SortNames sets whether metric names should be ordered predictably during export.

@Summary Sets sorting behavior for metric names during export.
@Tags configuration
@Param sortNames query bool true "Whether to sort metric names predictably during export."
@Usage Enables deterministic ordering in exported metrics to facilitate easier comparisons.

func (*Server) Bytes

func (c *Server) Bytes(format expfmt.Format, opts ...expfmt.EncoderOption) ([]byte, error)

String renders the Prometheus texp/plain formatted metrics to string

func (*Server) Counter

func (s *Server) Counter(name string) *counter

func (*Server) Export

func (s *Server) Export(w io.Writer, expFormat expfmt.Format, opts ...expfmt.EncoderOption) error

func (*Server) Gauge

func (s *Server) Gauge(name string) *gauge

func (*Server) Histogram

func (s *Server) Histogram(name string) *histogram

func (*Server) OptSortNames

func (s *Server) OptSortNames(sortNames bool) *Server

func (*Server) SortNames

func (s *Server) SortNames(sortNames bool) *Server

func (*Server) String

func (c *Server) String(format expfmt.Format, opts ...expfmt.EncoderOption) (string, error)

String renders the Prometheus texp/plain formatted metrics to string

func (*Server) Summary

func (s *Server) Summary(name string) *summary

type ServerConfig

type ServerConfig struct {
	SortNames bool `json:"sort_names"`
}

type StateInitFunc

type StateInitFunc = func(metricState *state)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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