strata

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2024 License: Apache-2.0 Imports: 17 Imported by: 0

README

Strata - Prometheus Client unit tests

The Strata Go package provides a wrapper around the prometheus client to automatically register and collect metrics.

Install

go get ctx.sh/strata

Usage

Initialize

Initialize the metrics collectors using the strata.New function. There are several options available. As an example:

metrics := strata.New(strata.MetricsOpts{
	ConstantLabels: []string{"role", "server"},
	Separator:    ':',
	PanicOnError: false,
})
MetricOpts
Option Default Description
ConstantLabels empty An array of label/value pairs that will be constant across all metrics.
HistogramBuckets []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10} Buckets used for histogram observation counts
Logger nil Provide a logger that implements the Logger interface. A valid logger must have the following methods defined: Info(msg string, keysAndValues ...any) and Error(err error, msg string, keysAndValues ...any)
PanicOnError false Maintain the default behavior of prometheus to panic on errors. If this value is set to false, the library attempts to recover from any panics and emits an internally managed metric strata_errors_panic_recovery to inform the operator that visibility is degraded. If set to true the original behavior is maintained and all errors are treated as panics.
Prefix empty An array of strings that represent the base prefix for the metric.
Separator _ The seperator that will be used to join the metric name components.
SummaryOpts see below Options used for configuring summary metrics
SummaryOpts
Option Default Description
AgeBuckets 5 AgeBuckets is the number of buckets used to exclude observations that are older than MaxAge from the summary.
MaxAge 10 minutes MaxAge defines the duration for which an observation stays relevant for the summary.
Objectives map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001} Objectives defines the quantile rank estimates with their respective absolute error.

Starting and Stopping the collection endpoints

Starting

There are two options for starting the collection endpoint. You can start the built in HTTP(S) server or retrieve the handler to register the metrics route in an existing multiplexer/request router.

To start a standard http server:

err := metrics.Start(ctx, strata.ServerOpts{
	Port: 9090,
	TerminationGracePeriod: 10 * time.Second
})

To start an http server with TLS support, at minimum you must provide the key and the certificate:

err := metrics.Start(ctx, strata.ServerOpts{
	Port: 9090,
	TLS: &strata.TLSOpts{
		CertFile: *certFile,
		KeyFile:  *keyFile,
	},
})

To retrieve the handler for use in an existing router:

mux := http.NewServeMux()
mux.Handle("/metrics", metrics.Handler())
ServerOpts
Option Default Description
BindAddr 0.0.0.0 The address the promethus collector will listen on for connections
TerminationGracePeriod 0
Path /metrics The path used by the HTTP server.
Port 9090 The port used by the HTTP server.
TLS see below Options used to configure TLS for the collection endpoint
TLS
Option Default Description
CertFile - The path to the file containing the certificate or the certificate bundle.
InsecureSkipVerify false controls whether a client verifies the server's certificate chain and host name.
KeyFile - The path to the private key file.
MinVersion TLS 1.3 The minimum TLS version that the server will accept.
Shutdown the collection endpoint

The metrics http collection endpoint will shutdown automatically when the context is closed. You can control the shutdown time by setting a grace period for the collection endpoint to remain active before shutting down to ensure that the final metrics are scraped.

metrics := strata.New(strata.MetricsOpts{})

var obs sync.WaitGroup
obs.Add(1)
go func() {
	defer obs.Done()
	_ = metrics.Start(ctx, strata.ServerOpts{})
}

var wg sync.WaitGroup
wg.Add(1)
go func() {
	defer wg.Done()
	myApp.Start()
}
wg.Wait()
obs.Wait()

API

Prefixes and Labels
WithLabels(...string)

The WithLabels function adds labels to the metrics. If labels are added to metrics, the subsequent metrics must include the label values. Each metric function includes a variadic parameter that is used to pass in the values in the order that the labels were previously passed.

m := strata.New(strata.MetricsOpts{})
n := m.WithLabels("label1", "label2")
n.CounterInc("a_total", "value1", "value2")
WithPrefix(...string)

The WithPrefix function appends additional prefix values to the metric name. By default metrics are created without prefixes unless added in MetricOpts. For example:

m := strata.New(strata.MetricsOpts{})
// prefix: ""
m.WithPrefix("strata", "example")
// prefix: "strata_example"
m.CounterInc("a_total")
// metric: "strata_example_a_total"
n := m.WithPrefix("component")
// prefix: "strata_example_component"
n.CounterInc("b_total")
// metric: "strata_example_component_b_total"
m.CounterInc("c_total")
// metric: "strata_example_c_total"
Counter

A counter is a cumulative metric whose value can only increase or be reset to zero on restart. Counters are often used to represent the number of requests served, tasks completed, or errors.

CounterInc(string, ...string)

Increment a counter metric by one.

// Without labels
metrics.CounterInc("my_counter")

// With labels
metrics = metrics.WithValues("label1", "label2")
metrics.CounterInc("my_counter", "value1", "value2")
CounterAdd(string, float64, ...string)

Add a float64 value to the counter metric.

// Without labels
metrics.CounterAdd("my_counter", 2.0)

// With labels
metrics = metrics.WithValues("label1", "label2")
metrics.CounterAdd("my_counter", 2.0, "value1", "value2")
Gauge

A gauge represents a numerical value that can be arbitrarily increased or decreased. Gauges are typically used for measured values like temperatures or current memory usage, but also "counts" that can go up and down. Gauges are often used to represent things like disk and memory usage and concurrent requests.

GaugeSet(string, float64, ...string)

Set a gauge to the value that is passed.

// Without labels
metrics.GaugeSet("my_gauge", 2.0)

// With labels
metrics = metrics.WithValues("label1", "label2")
metrics.GaugeSet("gauge_with_values", 2.0, "value1", "value2")
GaugeInc(string, ...string)

Increment a gauge by one.

// Without labels
metrics.GaugeInc("my_gauge")

// With labels
metrics = metrics.WithValues("label1", "label2")
metrics.GaugeInc("gauge_with_values", "value1", "value2")
GaugeDec(string, ...string)

Decrement a gauge by one.

// Without labels
metrics.GaugeDec("my_gauge")

// With labels
metrics = metrics.WithValues("label1", "label2")
metrics.GaugeDec("gauge_with_values", "value1", "value2")
GaugeAdd(string, float64, ...string)

Adds the value that is passed to a gauge.

// Without labels
metrics.GaugeAdd("my_gauge", 2.0)

// With labels
metrics = metrics.WithValues("label1", "label2")
metrics.GaugeAdd("gauge_with_values", 2.0, "value1", "value2")
GaugeSub(string, float64, ...string)

Subtract the value that is passed to a gauge.

// Without labels
metrics.GaugeSub("my_gauge", 2.0)

// With labels
metrics = metrics.WithValues("label1", "label2")
metrics.GaugeSub("gauge_with_values", 2.0, "value1", "value2")
Histogram

A histogram samples observations and counts them in configurable buckets. Most often histograms are used to measure durations or sizes. Histograms expose multiple measurements during a scrape. These include bucket measurements in the format <name>_bucket{le="<upper_bound>"}, the total sum of observed values as <name>_sum, and the number of observered events in the format of <name>_count. Histograms buckets are configurable through HistogramBuckets in MetricsOpts which allow overrides the time buckets into which observations are counted. Values must be sorted in increasing order. The +inf bucket is automatically added to catch values.

HistogramObserve(string, float64, ...string)

Add a single observation to the histogram.

m := strata.New(strata.MetricsOpts{
	HistogramBuckets: []float{0.01, 0.5, 0.1, 1, 5, 10}
})

// Without labels
metrics.HistogramObserve("my_histogram", response_time)

// With labels
metrics = metrics.WithValues("label1", "label2")
metrics.HistogramObserve("my_histogram", response_time, "value1", "value2")
Histogram Timer(string, ...string)

Create a histogram timer.

m := strata.New(strata.MetricsOpts{
	HistogramBuckets: strata.ExponentialBuckets(100, 1.2, 3)
})

// Without labels
timer := m.HistogramTimer("response")
defer timer.ObserveDuration()

// With labels
metrics = metrics.WithValues("label1", "label2")
timer := m.HistogramTimer("response", "value1", "value2")
defer timer.ObserveDuration()
Summary

A summary samples observations and calculates quantiles over a sliding time windo. Like histograms, they are used to measure durations or sizes. Summaries expose multiple measurements during a scrape. Thiese include quantiles in the form of <name>{quantile="φ"}, , the total sum of observed values as <name>_sum, and the number of observered events in the format of <name>_count. Summaries are configurable through the SummaryOpts struct which allow overrides of the following attributes:

  • Objectives: The quantile rank estimates with their respective absolute error defined as a map[float64]float64.
  • MaxAge: The duration that observations stay relevant as time.Duration.
  • AgeBuckets: Number of buckets used to calculate the age of observations as a uint32.
SummaryObserve(string, float64, ...string)

Add a single observations to the summary

m := strata.New(strata.MetricsOpts{
	SummaryOpts: &strata.SummaryOpts{
		MaxAge:     10 * time.Minute,
		Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
		AgeBuckets: 5,
	}
})

// Without labels
metrics.SummaryObserve("test_summary", response)

// With labels
metrics = metrics.WithValues("label1", "label2")
metrics.SummaryObserve("test_summary", response, "value1", "value2")
SummaryTimer(string, ...string)

Create a summary timer.

m := strata.New(strata.MetricsOpts{
	SummaryOpts: &strata.SummaryOpts{
		MaxAge:     10 * time.Minute,
		Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
		AgeBuckets: 5,
	}
})

// Without labels
timer := m.SummaryTimer("response")
defer timer.ObserveDuration()

// With labels
metrics = metrics.WithValues("label1", "label2")
timer := m.SummaryTimer("response", "value1", "value2")
defer timer.ObserveDuration()

Documentation

Index

Constants

View Source
const (
	DefaultTimeout                  = 5 * time.Second
	DefaultMaxAge     time.Duration = 10 * time.Minute
	DefaultAgeBuckets uint32        = 5
)
View Source
const (
	// ErrInvalidMetricName is returned when a metric name contains other
	// characters other than [a-zA-Z_-].
	ErrInvalidMetricName = StrataError("Invalid metric name")
	// ErrRegistrationFailed is returned if prometheus is unable to register
	// the collector.
	ErrRegistrationFailed = StrataError("Unable to register collector")
	// ErrAlreadyRegistered is returned if prometheus has already registered
	// a collector.
	ErrAlreadyRegistered = StrataError("metric is already registered")
	// ErrNoMetrics is returned if the context does not contain the metrics
	// key.
	ErrNoMetrics = StrataError("no metrics found in context")
	// ErrNilContext is returned if the context is nil.
	ErrNilContext = StrataError("context is nil")
)
View Source
const (
	// CounterType represents an strata wrapper around the prometheus CounterVec
	// type.
	CounterType MetricType = "counter"
	// GaugeType represents an strata wrapper around the prometheus GaugeVec
	// type.
	GaugeType MetricType = "gauge"
	// SummaryType represents an strata wrapper around the prometheus SummaryVec
	// type.
	SummaryType MetricType = "summary"
	// HistogramType represents an strata wrapper around the prometheus HistogramVec
	// type.
	HistogramType MetricType = "histogram"
	// Defines the metrics help string.  This is currently not settable.
	DefaultHelpString string = "created automagically by strata"
)

Variables

View Source
var (
	// DefBuckets are the default Histogram buckets.
	DefBuckets = prometheus.DefBuckets //nolint:gochecknoglobals
)
View Source
var (
	DefaultObjectives = map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001} //nolint:gochecknoglobals
)

Functions

func CollectAndCompare

func CollectAndCompare(
	t *testing.T,
	vec MetricVec,
	name string,
	mtype string,
	labels map[string]string,
	value float64,
)

CollectAndCompare is a helper function for testing. It creates prometheus strings and compares them with the collector using the CollectAndCompare test utility.

func ExponentialBucketRange

func ExponentialBucketRange(min, max float64, count int) []float64

ExponentialBucketsRange creates 'count' buckets, where the lowest bucket is 'min' and the highest bucket is 'max'. The final +Inf bucket is not counted and not included in the returned slice. The returned slice is meant to be used for the Buckets field of HistogramOpts. (from prometheus docs)

The function panics if 'count' is 0 or negative, if 'min' is 0 or negative.

func ExponentialBuckets

func ExponentialBuckets(start, factor float64, count int) []float64

ExponentialBuckets creates 'count' buckets, where the lowest bucket has an upper bound of 'start' and each following bucket's upper bound is 'factor' times the previous bucket's upper bound. The final +Inf bucket is not counted and not included in the returned slice. The returned slice is meant to be used for the Buckets field of HistogramOpts. (from prometheus docs)

The function panics if 'count' is 0 or negative, if 'start' is 0 or negative, or if 'factor' is less than or equal 1.

func HandlerFor

func HandlerFor(metrics *Metrics) http.Handler

HandlerFor returns the handler for the metrics registry.

func IntoContext added in v0.4.2

func IntoContext(ctx context.Context, metrics *Metrics) context.Context

IntoContext returns a new context derived from the provided context which carries the provided Metrics.

func LinearBuckets

func LinearBuckets(start, width float64, count int) []float64

LinearBuckets creates 'count' buckets, each 'width' wide, where the lowest bucket has an upper bound of 'start'. The final +Inf bucket is not counted and not included in the returned slice. The returned slice is meant to be used for the Buckets field of HistogramOpts. (from prometheus docs)

The function panics if 'count' is zero or negative.

func Register

func Register(reg prometheus.Registerer, metric prometheus.Collector) error

Register registers a collector with prometheus.

func SlicePairsToMap

func SlicePairsToMap(pairs []string) map[string]string

SlicePairsToMap copies key value pairs to a map.

Types

type ApexInternalErrorMetrics

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

ApexInternalErrorMetrics provides internal counters for recovered errors from the prometheus collector when PanicOnError is false.

func NewApexInternalErrorMetrics

func NewApexInternalErrorMetrics(prefixes []string, sep rune) *ApexInternalErrorMetrics

NewApexInternalErrorMetrics defines and registers the internal collectors and returns a new ApexInternalErrorMetrics struct.

func (*ApexInternalErrorMetrics) AlreadyRegistered

func (a *ApexInternalErrorMetrics) AlreadyRegistered(name string, t string)

AlreadyRegistered provides a helper function for incrementing the errAlreadyRegistered collector.

func (*ApexInternalErrorMetrics) InvalidMetricName

func (a *ApexInternalErrorMetrics) InvalidMetricName(name string, t string)

InvalidMeticName provides a helper function for incrementing the errInvalidMetricName collector.

func (*ApexInternalErrorMetrics) PanicRecovery

func (a *ApexInternalErrorMetrics) PanicRecovery(name string, t string)

PanicRecovery provides a helper function for incrementing the errPanicRecovery collector.

func (*ApexInternalErrorMetrics) RegistrationFailed

func (a *ApexInternalErrorMetrics) RegistrationFailed(name string, t string)

RegistrationFailed provides a helper function for incrementing the errRegistrationFailed collector.

type CounterVec

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

CounterVec is a wrapper around the prometheus CounterVec.

It bundles a set of Counters that all share the same Desc, but have different values for their variable labels. This is used if you want to count the same thing partitioned by various dimensions (e.g. number of HTTP requests, partitioned by response code and method).

func NewCounterVec

func NewCounterVec(registerer prometheus.Registerer, name string, labels ...string) (*CounterVec, error)

NewCounterVec creates, registers, and returns a new CounterVec.

func (*CounterVec) Add

func (c *CounterVec) Add(v float64, lv ...string)

Add increases the counter by the given float value with the label values in the order that the labels were defined in NewCounterVec.

func (*CounterVec) Inc

func (c *CounterVec) Inc(lv ...string)

Inc increments the counter by 1 with the label values in the order that the labels were defined in NewCounterVec.

func (*CounterVec) Name

func (c *CounterVec) Name() string

Name returns the name of the CounterVec.

func (*CounterVec) Type

func (c *CounterVec) Type() MetricType

Type returns the metric type.

func (*CounterVec) Vec

func (c *CounterVec) Vec() prometheus.Collector

Vec returns the prometheus CounterVec.

type GaugeVec

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

GaugeVec is a wrapper around the prometheus GaugeVec.

It bundles a set of Gauges that all share the same Desc, but have different values for their variable labels. This is used if you want to count the same thing partitioned by various dimensions (e.g. number of operations queued, partitioned by user and operation type). Create instances with NewGaugeVec.

A gauge represents a numerical value that can be arbitrarily increased or decreased. Gauges are typically used for measured values like temperatures or current memory usage, but also "counts" that can go up and down. Gauges are often used to represent things like disk and memory usage and concurrent requests.

func NewGaugeVec

func NewGaugeVec(registerer prometheus.Registerer, name string, labels ...string) (*GaugeVec, error)

NewGaugeVec creates, registers, and returns a new GaugeVec.

func (*GaugeVec) Add

func (g *GaugeVec) Add(v float64, lv ...string)

Add increases the counter by the given float value with the label values in the order that the labels were defined in NewGaugeVec.

func (*GaugeVec) Dec

func (g *GaugeVec) Dec(lv ...string)

Dec decrements the Gauge by 1 using the label values in the order that the labels were defined in NewGaugeVec.

func (*GaugeVec) Inc

func (g *GaugeVec) Inc(lv ...string)

Inc increments the Gauge by 1 using the label values in the order that the labels were defined in NewGaugeVec.

func (*GaugeVec) Name

func (g *GaugeVec) Name() string

Name returns the name of the GaugeVec.

func (*GaugeVec) Set

func (g *GaugeVec) Set(v float64, lv ...string)

Set sets the Gauge to an arbitrary value using the label values in the order that the labels were defined in NewGaugeVec.

func (*GaugeVec) Sub

func (g *GaugeVec) Sub(v float64, lv ...string)

Add subtracts the counter by the given float value with the label values in the order that the labels were defined in NewGaugeVec.

func (*GaugeVec) Type

func (g *GaugeVec) Type() MetricType

Type returns the metric type.

func (*GaugeVec) Vec

func (g *GaugeVec) Vec() prometheus.Collector

Vec returns the prometheus GaugeVec.

type HistogramOpts

type HistogramOpts struct {
	// Buckets defines the observation buckets for the histogram.  Each float
	// value is the upper inclusive bound of the bucket with +Inf added implicitly.
	// the default is
	Buckets []float64
}

HistogramOpts defines options that are available to the HistogramVec collectors.

type HistogramVec

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

HistogramVec is a wrapper around the prometheus HistogramVec.

It bundles a set of histograms used if you want to count the same thing partitioned by various dimensions.

func NewHistogramVec

func NewHistogramVec(registerer prometheus.Registerer, name string, buckets []float64, labels ...string) (*HistogramVec, error)

NewHistogramVec creates, registers, and returns a new HistogramVec.

func (*HistogramVec) Name

func (g *HistogramVec) Name() string

Name returns the name of the HistogramVec.

func (*HistogramVec) Observe

func (h *HistogramVec) Observe(v float64, lv ...string)

func (*HistogramVec) Timer

func (h *HistogramVec) Timer(lv ...string) *Timer

func (*HistogramVec) Type

func (g *HistogramVec) Type() MetricType

Type returns the metric type.

func (*HistogramVec) Vec

Vec returns the prometheus HistogramVec.

type Logger

type Logger interface {
	Info(msg string, keysAndValues ...any)
	Error(err error, msg string, keysAndValues ...any)
}

type MetricType

type MetricType string

type MetricVec

type MetricVec interface {
	Name() string
	Type() MetricType
	Vec() prometheus.Collector
}

MetricVec defines the interface for strata metrics collector wrappers.

type Metrics

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

Metrics provides a wrapper around the prometheus client to automatically register and collect metrics.

func FromContext added in v0.4.2

func FromContext(ctx context.Context, prefix ...string) (*Metrics, error)

FromContext extracts and returns the Metrics from the context. An error is returned if the context does not contain Metrics or the context is nil.

func New

func New(opts MetricsOpts) *Metrics

New creates a new Apex metrics store using the options that have been provided.

func (*Metrics) CounterAdd

func (m *Metrics) CounterAdd(name string, v float64, lv ...string)

CounterAdd increments a counter by the provided value.

func (*Metrics) CounterInc

func (m *Metrics) CounterInc(name string, lv ...string)

CounterInc increments a counter by 1.

func (*Metrics) GaugeAdd

func (m *Metrics) GaugeAdd(name string, v float64, lv ...string)

GaugeAdd adds an arbitrary value to the gauge.

func (*Metrics) GaugeDec

func (m *Metrics) GaugeDec(name string, lv ...string)

GaugeDec decrements a gauge by 1.

func (*Metrics) GaugeInc

func (m *Metrics) GaugeInc(name string, lv ...string)

GaugeInc increments a gauge by 1.

func (*Metrics) GaugeSet

func (m *Metrics) GaugeSet(name string, v float64, lv ...string)

GaugeSet sets a gauge to an arbitrary value.

func (*Metrics) GaugeSub

func (m *Metrics) GaugeSub(name string, v float64, lv ...string)

GaugeSub subtracts an arbitrary value to the gauge.

func (*Metrics) HistogramObserve

func (m *Metrics) HistogramObserve(name string, v float64, lv ...string)

HistogramObserve adds a single observation to the histogram.

func (*Metrics) HistogramTimer

func (m *Metrics) HistogramTimer(name string, lv ...string) *Timer

HistogramTimer returns a Timer helper to measure duration. ObserveDuration is used to measure the time. Example:

timer := m.HistogramTimer("response")
defer timer.ObserveDuration()

func (*Metrics) Start

func (m *Metrics) Start(ctx context.Context, opts ServerOpts) error

Start starts the HTTP server. It blocks until Stop is called.

func (*Metrics) Stop

func (m *Metrics) Stop()

Stop shuts down the HTTP server gracefully.

func (*Metrics) SummaryObserve

func (m *Metrics) SummaryObserve(name string, v float64, lv ...string)

SummaryObserve adds a single observation to the summary.

func (*Metrics) SummaryTimer

func (m *Metrics) SummaryTimer(name string, lv ...string) *Timer

SummaryTimer returns a Timer helper to measure duration. ObserveDuration is used to measure the time. Example:

timer := m.SummaryTimer("response")
defer timer.ObserveDuration()

func (*Metrics) WithLabels

func (m *Metrics) WithLabels(labels ...string) *Metrics

WithLabels creates a new metric with the provided labels. Example:

metrics = metrics.WithValues("label1", "label2")
metrics.GaugeAdd("gauge_with_values", 2.0, "value1", "value2")

func (*Metrics) WithPrefix

func (m *Metrics) WithPrefix(prefix ...string) *Metrics

WithPrefix appends additional values to the metric name to prefix any new metric names that are added. By default metrics are created without prefixes unless added in MetricOpts. For example:

m := strata.New(strata.MetricsOpts{})
// prefix: ""
m.WithPrefix("strata", "example")
// prefix: "strata_example"
m.CounterInc("a_total")
// metric: "strata_example_a_total"
n := m.WithPrefix("component")
// prefix: "strata_example_component"
n.CounterInc("b_total")
// metric: "strata_example_component_b_total"
m.CounterInc("c_total")
// metric: "strata_example_c_total"

type MetricsOpts

type MetricsOpts struct {
	// ConstantLabels is an array of label/value pairs that will be constant
	// across all metrics.
	ConstantLabels []string
	// HistogramBuckets are buckets used for histogram observation counts.
	HistogramBuckets []float64
	// SummaryOpts defines the options available to summary collectors.
	SummaryOpts *SummaryOpts
	// Registry is the prometheus registry that will be used to register
	// collectors.
	Registry *prometheus.Registry
	// Separator is the separator that will be used to join the metric name
	// components.
	Separator rune
	// PanicOnError maintains the default behavior of prometheus to panic on
	// errors. If this value is set to false, the library attempts to recover
	// from any panics and emits an internally managed metric
	// strata_errors_panic_recovery to inform the operator that visibility is
	// degraded. If set to true the original behavior is maintained and all
	// errors are treated as panics.
	PanicOnError bool
	// Prefix is an array of prefixes that will be appended to the metric name.
	Prefix []string
	// Logger takes a value that matches the Logger interface and is used for
	// log output of errors and other debug information.
	Logger Logger
}

MetricsOpts defines options that are available for the metrics wrapper.

type Server

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

func (*Server) Start

func (s *Server) Start(ctx context.Context, reg *prometheus.Registry) error

Start creates a new http server which listens on the TCP address addr and port.

func (*Server) Stop

func (s *Server) Stop()

Stop closes the stop channel which initiates the shutdown of the HTTP server.

func (*Server) WithLogger

func (s *Server) WithLogger(logger Logger) *Server

WithLogger defines the logger that will be used with the server.

type ServerOpts

type ServerOpts struct {
	// BindAddr is the address the promethus collector will listen on for
	// connections.
	BindAddr string
	// BaseContext
	// Path is the path used by the HTTP server.
	Path string
	// Port is the path used by the HTTP server.
	Port int
	// TLS
	TLS *TLSOpts
	// TerminationGracePeriod is the amount of time that the server will wait
	// before stopping the HTTP server.  This grace period allows any prometheus
	// scrapers time to scrape.
	TerminationGracePeriod time.Duration
}

type Store

type Store struct {

	// TODO: part of the issue with the race condition was that we were
	// setting the metric store value to nil and not revisiting.  This will
	// pretty much address the double register race that caused the nil, but
	// I need to come back through this and make the check/get more resilient
	// so I can shrink the footprint of the lock.
	sync.Mutex
	// contains filtered or unexported fields
}

Store manages all of the prometheus collectors.

type StrataError added in v0.4.2

type StrataError string

func (StrataError) Error added in v0.4.2

func (e StrataError) Error() string

Error implements the error interface for StrataError.

type SummaryOpts

type SummaryOpts struct {
	// Objectives defines the quantile rank estimates with their respective
	// absolute error.
	Objectives map[float64]float64
	// MaxAge defines the duration for which an observation stays relevant
	// for the summary.
	MaxAge time.Duration
	// AgeBuckets is the number of buckets used to exclude observations that
	// are older than MaxAge from the summary.
	AgeBuckets uint32
}

type SummaryVec

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

SummaryVec is a wrapper around the prometheus SummaryVec.

It bundles a set of summaries used if you want to count the same thing partitioned by various dimensions.

func NewSummaryVec

func NewSummaryVec(registerer prometheus.Registerer, name string, opts SummaryOpts, labels ...string) (*SummaryVec, error)

func (*SummaryVec) Name

func (s *SummaryVec) Name() string

Name returns the name of the SummaryVec.

func (*SummaryVec) Observe

func (s *SummaryVec) Observe(v float64, lv ...string)

Observe adds a single observation to the summary.

func (*SummaryVec) Timer

func (s *SummaryVec) Timer(lv ...string) *Timer

Timer returns a new summary timer.

func (*SummaryVec) Type

func (s *SummaryVec) Type() MetricType

Type returns the metric type.

func (*SummaryVec) Vec

func (s *SummaryVec) Vec() prometheus.Collector

Vec returns the prometheus SummaryVec.

type TLSOpts

type TLSOpts struct {
	// CertFile is the path to the file containing the SSL certificate or
	// certificate bundle.
	CertFile string
	// Keyfile is the path containing the certificate key.
	KeyFile string
	// InsecureSkipVerify controls whether a client verifies the server's
	// certificate chain and host name.
	InsecureSkipVerify bool
	// MinVersion contains the minimum TLS version that is acceptable.  By
	// default TLS 1.3 is used.
	MinVersion uint16
}

type Timer

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

Timer is a helper type to time functions.

func NewTimer

func NewTimer(collector prometheus.Collector, lv ...string) *Timer

NewTimer creates a new Timer.

func (*Timer) Func

func (t *Timer) Func(name string, fn func(float64)) *Timer

Func allows the use of ordinary functions as Observers.

func (*Timer) ObserveDuration

func (t *Timer) ObserveDuration()

ObserveDuration records the duration that has passed between the time that the Timer was created.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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