openmetrics

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2023 License: Apache-2.0 Imports: 14 Imported by: 5

README

OpenMetrics

Go Reference Test License

OpenMetrics is a standalone, dependency-free implementation of OpenMetrics v1.0 specification for Go.

Example

To expose metrics on a HTTP server endpoint and to instrument HTTP servers, please see examples in the omhttp package.

import(
	"bytes"
	"fmt"

	"github.com/bsm/openmetrics"
)

func main() {
	reg := openmetrics.NewConsistentRegistry(mockNow)	// or, openmetrics.DefaultRegistry()
	requestCount := reg.Counter(openmetrics.Desc{
		Name:	"http_request",
		Help:	"A counter example",
		Labels:	[]string{"status"},
	})
	responseTime := reg.Histogram(openmetrics.Desc{
		Name:	"http_request",
		Unit:	"seconds",
		Help:	"A histogram example",
		Labels:	[]string{"status"},
	}, .005, .01, .05, .1, .5, 1, 5, 10)

	requestCount.With("200").Add(1)
	responseTime.With("200").Observe(0.56)

	var buf bytes.Buffer
	if _, err := reg.WriteTo(&buf); err != nil {
		panic(err)
	}
	fmt.Print(buf.String())

}

License

Copyright 2021 Black Square Media Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Documentation

Overview

Example
reg := openmetrics.NewConsistentRegistry(mockNow) // or, openmetrics.DefaultRegistry()
requestCount := reg.Counter(openmetrics.Desc{
	Name:   "http_request",
	Help:   "A counter example",
	Labels: []string{"status"},
})
responseTime := reg.Histogram(openmetrics.Desc{
	Name:   "http_request",
	Unit:   "seconds",
	Help:   "A histogram example",
	Labels: []string{"status"},
}, []float64{.005, .01, .05, .1, .5, 1, 5, 10})

requestCount.With("200").Add(1)
responseTime.With("200").Observe(0.56)

var buf bytes.Buffer
if _, err := reg.WriteTo(&buf); err != nil {
	panic(err)
}
fmt.Print(buf.String())
Output:

# TYPE http_request counter
# HELP http_request A counter example
http_request_total{status="200"} 1
http_request_created{status="200"} 1515151515.757576
# TYPE http_request_seconds histogram
# UNIT http_request_seconds seconds
# HELP http_request_seconds A histogram example
http_request_seconds_bucket{status="200",le="0.005"} 0
http_request_seconds_bucket{status="200",le="0.01"} 0
http_request_seconds_bucket{status="200",le="0.05"} 0
http_request_seconds_bucket{status="200",le="0.1"} 0
http_request_seconds_bucket{status="200",le="0.5"} 0
http_request_seconds_bucket{status="200",le="1"} 1
http_request_seconds_bucket{status="200",le="5"} 1
http_request_seconds_bucket{status="200",le="10"} 1
http_request_seconds_bucket{status="200",le="+Inf"} 1
http_request_seconds_count{status="200"} 1
http_request_seconds_sum{status="200"} 0.56
http_request_seconds_created{status="200"} 1515151515.757576
# EOF

Index

Examples

Constants

View Source
const ContentType = "application/openmetrics-text; version=1.0.0; charset=utf-8"

ContentType is the official content type of an openmetrics document.

Variables

This section is empty.

Functions

func PanicOnError

func PanicOnError(err error)

PanicOnError implements the ErrorHandler interface and panics on errors.

func WarnOnError

func WarnOnError(err error)

WarnOnError implements the ErrorHandler interface and writes warnings to os.Stderr.

Types

type Counter

type Counter interface {
	Metric

	// Add increments the total. Total MUST be monotonically non-decreasing over
	// time. Attempts to pass negative, NaN or infinity values will result in
	// errors.
	Add(val float64)

	// AddExemplar increments the total using an exemplar. Attempts to pass
	// negative, NaN or infinity values will result in an error. Invalid exemplars
	// will be silently discarded.
	AddExemplar(ex *Exemplar)

	// Reset resets the created time to now and the total to 0.
	Reset(CounterOptions)

	// Created returns the created time.
	Created() time.Time
	// Total returns the current total.
	Total() float64
	// Exemplar returns the most recent Exemplar.
	Exemplar() *Exemplar
}

Counter is an Metric.

func NewCounter

func NewCounter(opts CounterOptions) Counter

NewCounter inits a new counter.

type CounterFamily

type CounterFamily interface {
	MetricFamily

	// With returns a Counter for the given label values.
	With(labelValues ...string) Counter
}

CounterFamily is a metric family of counters.

type CounterOptions

type CounterOptions struct {
	CreatedAt time.Time    // defaults to time.Now()
	OnError   ErrorHandler // defaults to WarnOnError
}

CounterOptions configure Counter instances.

type Desc

type Desc struct {
	// Name of the metric (required).
	Name string
	// Unit specifies MetricFamily units.
	Unit string
	// Help is a string and SHOULD be non-empty. It is used to give a brief
	// description of the MetricFamily for human consumption and SHOULD be short
	// enough to be used as a tooltip.
	Help string
	// Names of the labels that will be used with this metric (optional).
	Labels []string
}

Desc contains the metric family description.

func (*Desc) FullName

func (d *Desc) FullName() string

FullName returns the full metric family name.

func (*Desc) Validate

func (d *Desc) Validate() error

Validate validates the description.

type ErrAlreadyRegistered

type ErrAlreadyRegistered struct {
	Existing MetricFamily
}

ErrAlreadyRegistered is returned when a metric is already registered.

func (ErrAlreadyRegistered) Error

func (e ErrAlreadyRegistered) Error() string

type ErrorHandler

type ErrorHandler func(error)

ErrorHandler handles errors.

type Exemplar

type Exemplar struct {
	Value     float64
	Timestamp time.Time
	Labels    LabelSet
}

Examplar value.

Example
reg := openmetrics.NewConsistentRegistry(mockNow) // or, openmetrics.DefaultRegistry()
internalError := reg.Counter(openmetrics.Desc{
	Name: "internal_error",
	Help: "A counter example",
})

_, err := os.Stat("/.dockerenv")
if err != nil {
	// the combined length of label names and values of MUST NOT exceed 128 characters
	errmsg := err.Error()
	if len(errmsg) > 120 {
		errmsg = errmsg[:120]
	}

	internalError.With().AddExemplar(&openmetrics.Exemplar{
		Value:  1,
		Labels: openmetrics.Labels("error", errmsg),
	})
}
Output:

func (*Exemplar) AddLabel added in v0.2.0

func (x *Exemplar) AddLabel(name, value string)

AddLabel adds a label to the exemplar.

func (*Exemplar) Reset

func (x *Exemplar) Reset()

Reset resets the exemplar properties.

func (*Exemplar) Validate

func (x *Exemplar) Validate() error

Validate validates the exemplar. The combined length of label names and values of MUST NOT exceed 128 UTF-8 characters.

type Gauge

type Gauge interface {
	Metric

	// Set sets the value.
	Set(val float64)
	// Add increments the value.
	Add(val float64)
	// Value returns the current value.
	Value() float64
	// Reset resets the gauge to its original state.
	Reset(GaugeOptions)
}

Gauge is a Metric.

func NewGauge

func NewGauge(_ GaugeOptions) Gauge

NewGauge inits a new Gauge.

type GaugeFamily

type GaugeFamily interface {
	MetricFamily

	// With returns a Gauge for the given label values.
	With(labelValues ...string) Gauge
}

GaugeFamily is a metric family of Gauges.

type GaugeOptions

type GaugeOptions struct{}

GaugeOptions configure Gauge instances.

type Histogram

type Histogram interface {
	Metric

	// Observe adds an observation. Attempts to pass negative, NaN or infinity
	// values will result in an error.
	Observe(float64)

	// ObserveExemplar adds an observation using an exemplar. Attempts to pass
	// negative, NaN or infinity values will result in an error. Invalid exemplars
	// will be silently discarded.
	ObserveExemplar(*Exemplar)

	// Reset resets the histogram to its original state.
	Reset(HistogramOptions)

	// Created returns the created time.
	Created() time.Time
	// Sum returns the sum of all observations.
	Sum() float64
	// Count returns the total number of observations.
	Count() int64
	// NumBuckets returns the number of threshold buckets.
	NumBuckets() int
	// Exemplar returns the exemplar at bucket index.
	Exemplar(bucket int) *Exemplar
}

Histogram is a Metric.

func NewHistogram

func NewHistogram(bounds []float64, opts HistogramOptions) (Histogram, error)

NewHistogram inits a new histogram. The bucket boundaries for that are described by the bounds. Each boundary defines the upper threshold bound of a bucket.

When len(bounds) is 0 the histogram will be created with a single bucket with an +Inf threshold.

type HistogramFamily

type HistogramFamily interface {
	MetricFamily

	// With returns a Histogram for the given label values.
	With(labelValues ...string) Histogram
}

HistogramFamily is a metric family of Histograms.

type HistogramOptions

type HistogramOptions struct {
	CreatedAt time.Time    // defaults to time.Now()
	OnError   ErrorHandler // defaults to WarnOnError
}

HistogramOptions configure Histogram instances.

type Info

type Info interface {
	Metric
}

Info is a Metric.

func NewInfo

func NewInfo(_ InfoOptions) Info

NewInfo inits a new Info from labels.

type InfoFamily

type InfoFamily interface {
	MetricFamily

	// With returns an Info for the given label values.
	With(labelValues ...string) Info
}

InfoFamily is a metric family of Infos.

type InfoOptions

type InfoOptions struct{}

InfoOptions configure Info instances.

type Label

type Label struct {
	Name, Value string
}

Label is a name-value pair. These are used in multiple places: identifying timeseries, value of INFO metrics, and exemplars in Histograms.

func (Label) IsValid

func (l Label) IsValid() bool

IsValid validates the Label.

func (Label) IsZero

func (l Label) IsZero() bool

IsZero returns true if the Label is empty. Empty label values SHOULD be treated as if the label was not present.

type LabelSet

type LabelSet []Label

A LabelSet MUST consist of Labels and MAY be empty. Label names MUST be unique within a LabelSet.

func Labels added in v0.2.0

func Labels(nameValuePairs ...string) LabelSet

Labels constructs a LabelSet from name-value pairs.

func (LabelSet) Append added in v0.2.0

func (ls LabelSet) Append(name, value string) LabelSet

Append appends a label to the set and returns the resulting set.

func (LabelSet) AppendTo

func (ls LabelSet) AppendTo(target LabelSet) LabelSet

AppendTo copies the labels set by appending to target returning the result.

func (LabelSet) Validate

func (ls LabelSet) Validate() error

Validate validates the label set and returns errors on failures.

type Metric

type Metric interface {
	AppendPoints([]MetricPoint, *Desc) ([]MetricPoint, error)
}

A Metric collects metric data.

type MetricFamily

type MetricFamily interface {
	// ID returns the numeric metric family ID.
	ID() uint64
	// Desc exposed the metric family description.
	Desc() *Desc
	// Type returns the metric type.
	Type() MetricType
	// NumMetrics returns the number of metrics in the family.
	NumMetrics() int
}

A MetricFamily wraps a family of Metrics, where every Metric MUST have a unique LabelSet.

type MetricPoint

type MetricPoint struct {
	Suffix   MetricSuffix
	Value    float64
	Label    Label
	Exemplar *Exemplar
}

MetricPoint is a point in a Metric.

type MetricSuffix

type MetricSuffix uint8

MetricSuffix defines the metric suffix value.

const (
	SuffixEmpty   MetricSuffix = iota // gauge, stateset, unknown, summary
	SuffixTotal                       // counter
	SuffixCreated                     // counter, histogram, summary
	SuffixCount                       // histogram, summary
	SuffixSum                         // histogram, summary
	SuffixBucket                      // histogram, gaugehistogram

	SuffixInfo // info

)

MetricSuffix enum.

func (MetricSuffix) String

func (m MetricSuffix) String() string

String returns the suffix.

type MetricType

type MetricType uint8

MetricType defines the type of a Metric.

const (
	// UnknownType must use unknown MetricPoint values.
	UnknownType MetricType = iota
	// GaugeType must use gauge MetricPoint values.
	GaugeType
	// Counter must use counter MetricPoint values.
	CounterType
	// StateSetType set must use stateset MetricPoint values.
	StateSetType
	// InfoType must use info MetricPoint values.
	InfoType
	// HistogramType must use histogram MetricPoint values.
	HistogramType

	// Summary quantiles must use summary value MetricPoint values.
	SummaryType
)

func (MetricType) String

func (t MetricType) String() string

type Registry

type Registry struct {
	// Custom error handler, defaults to WarnOnError.
	OnError ErrorHandler
	// contains filtered or unexported fields
}

A Registry registers metric families and periodically collects their states.

func DefaultRegistry

func DefaultRegistry() *Registry

DefaultRegistry returns the default registry instance.

func NewConsistentRegistry

func NewConsistentRegistry(now func() time.Time) *Registry

NewConsistentRegistry created a new registry instance that uses a custom time function and produces consistent outputs. This is useful for tests.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns a new registry instance.

func (*Registry) AddCounter

func (r *Registry) AddCounter(desc Desc) (CounterFamily, error)

AddCounter registers a counter.

func (*Registry) AddGauge

func (r *Registry) AddGauge(desc Desc) (GaugeFamily, error)

AddGauge registers a gauge.

func (*Registry) AddHistogram

func (r *Registry) AddHistogram(desc Desc, bounds []float64) (HistogramFamily, error)

AddHistogram registers a histogram.

The bucket boundaries for that are described by the bounds. Each boundary defines the upper threshold bound of a bucket.

When len(bounds) is 0 the histogram will be created with a single bucket with an +Inf threshold.

func (*Registry) AddInfo

func (r *Registry) AddInfo(desc Desc) (InfoFamily, error)

AddInfo registers an info.

func (*Registry) AddStateSet

func (r *Registry) AddStateSet(desc Desc, names []string) (StateSetFamily, error)

AddStateSet registers a state set.

func (*Registry) AddSummary added in v0.3.0

func (r *Registry) AddSummary(desc Desc) (SummaryFamily, error)

AddSummary registers a summary.

func (*Registry) AddUnknown

func (r *Registry) AddUnknown(desc Desc) (GaugeFamily, error)

AddUnknown registers an unknown.

func (*Registry) Counter

func (r *Registry) Counter(desc Desc) CounterFamily

Counter registers a counter. It panics on errors.

func (*Registry) Gauge

func (r *Registry) Gauge(desc Desc) GaugeFamily

Gauge registers a gauge. It panics on errors.

func (*Registry) Histogram

func (r *Registry) Histogram(desc Desc, bounds []float64) HistogramFamily

Histogram registers a histogram. It panics on errors.

The bucket boundaries for that are described by the bounds. Each boundary defines the upper threshold bound of a bucket.

When len(bounds) is 0 the histogram will be created with a single bucket with an +Inf threshold.

func (*Registry) Info

func (r *Registry) Info(desc Desc) InfoFamily

Info registers an info. It panics on errors.

func (*Registry) StateSet

func (r *Registry) StateSet(desc Desc, names []string) StateSetFamily

StateSet registers a state set. It panics on errors.

func (*Registry) Summary added in v0.3.0

func (r *Registry) Summary(desc Desc) SummaryFamily

Summary registers a summary. It panics on errors.

func (*Registry) Unknown

func (r *Registry) Unknown(desc Desc) GaugeFamily

Unknown registers an unknown. It panics on errors.

func (*Registry) WriteTo

func (r *Registry) WriteTo(w io.Writer) (int64, error)

WriteTo implements io.WriterTo interface.

type StateSet

type StateSet interface {
	Metric

	// Set sets a state by name.
	Set(name string, val bool)
	// Toggle toggles a state by name.
	Toggle(name string)

	// Reset resets the states.
	Reset(StateSetOptions)

	// IsEnabled returns true if a state is enabled.
	IsEnabled(name string) bool
	// Contains returns true if a state is included in the set.
	Contains(name string) bool
	// Len returns the number of states in the set.
	Len() int
}

StateSet is a Metric.

func NewStateSet

func NewStateSet(names []string, opts StateSetOptions) StateSet

NewStateSet inits a new StateSet.

type StateSetFamily

type StateSetFamily interface {
	MetricFamily

	// With returns a StateSet for the given label values.
	With(labelValues ...string) StateSet
}

StateSetFamily is a metric family of StateSets.

type StateSetOptions

type StateSetOptions struct {
	OnError ErrorHandler // defaults to WarnOnError
}

StateSetOptions configure StateSet instances.

type Summary added in v0.3.0

type Summary interface {
	Metric

	// Observe adds an observation. Attempts to pass negative, NaN or infinity
	// values will result in an error.
	Observe(val float64)
	// Sum returns the sum of all observations.
	Sum() float64
	// Count returns the total number of observations.
	Count() int64
	// Created returns the created time.
	Created() time.Time

	// Reset resets the created time to now and the total to 0.
	Reset(SummaryOptions)
}

Summary is an Metric.

func NewSummary added in v0.3.0

func NewSummary(opts SummaryOptions) (Summary, error)

NewSummary inits a new summary.

type SummaryFamily added in v0.3.0

type SummaryFamily interface {
	MetricFamily

	// With returns a Summary for the given label values.
	With(labelValues ...string) Summary
}

SummaryFamily is a metric family of summaries.

type SummaryOptions added in v0.3.0

type SummaryOptions struct {
	CreatedAt time.Time    // defaults to time.Now()
	OnError   ErrorHandler // defaults to WarnOnError
}

SummaryOptions configure Summary instances.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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