instruments

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Jun 6, 2022 License: MIT Imports: 8 Imported by: 6

README

Instruments

Build Status GoDoc

Instruments allows you to collects metrics over discrete time intervals. This a fork of the (original library)[https://github.com/heroku/instruments] which comes with several new additions - consider it a v2!

Collected metrics will only reflect observations from last time window only, rather than including observations from prior windows, contrary to EWMA based metrics.

The new features include:

  • Slighly faster
  • More convenient API
  • Support for tags
  • Built-in reporters
  • Accurate histograms

Instruments

Instruments support two types of instruments: Discrete instruments return a single value, and Sample instruments a sorted array of values.

These base instruments are available:

  • Counter: a simple counter.
  • Rate: tracks the rate of values per seconds.
  • Reservoir: randomly samples values.
  • Derive: tracks the rate of values based on the delta with previous value.
  • Gauge: tracks last value.
  • Timer: tracks durations.

You can create custom instruments or compose new instruments form the built-in instruments as long as they implements the Sample or Discrete interfaces.

Documentation

Please see the API documentation for package and API descriptions and examples.

See also

Documentation

Overview

Package instruments allows you to collects metrics over discrete time intervals.

Collected metrics will only reflect observations from last time window only, rather than including observations from prior windows, contrary to EWMA based metrics.

Instruments support two types of instruments: Discrete instruments return a single value, and Sample instruments a value distribution.

Theses base instruments are available:

- Counter: holds a counter that can be incremented or decremented. - Rate: tracks the rate of values per seconds. - Reservoir: randomly samples values. - Derive: tracks the rate of values based on the delta with previous value. - Gauge: tracks last value. - Timer: tracks durations.

You can create custom instruments or compose new instruments form the built-in instruments as long as they implements the Sample or Discrete interfaces.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func MetricID

func MetricID(name string, tags []string) string

MetricID takes a name and tags and generates a consistent metric identifier

func SplitMetricID

func SplitMetricID(metricID string) (name string, tags []string)

SplitMetricID takes a metric ID and splits it into name and tags.

Types

type Counter

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

Counter holds a counter that can be incremented or decremented.

Example
package main

import (
	"fmt"

	"github.com/bsm/instruments"
)

func main() {
	counter := instruments.NewCounter()
	counter.Update(20)
	counter.Update(25)
	fmt.Println(counter.Snapshot())
}
Output:

45

func NewCounter

func NewCounter() *Counter

NewCounter creates a new counter instrument.

func (*Counter) Snapshot

func (c *Counter) Snapshot() float64

Snapshot returns the current value and reset the counter.

func (*Counter) Update

func (c *Counter) Update(v float64)

Update adds v to the counter.

type Derive

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

Derive tracks the rate of deltas per seconds.

Example
package main

import (
	"fmt"

	"github.com/bsm/instruments"
)

func main() {
	derive := instruments.NewDerive(34)
	derive.Update(56)
	derive.Update(78)
	fmt.Println(derive.Snapshot())
}
Output:

func NewDerive

func NewDerive(v float64) *Derive

NewDerive creates a new derive instruments.

func NewDeriveScale

func NewDeriveScale(v float64, d time.Duration) *Derive

NewDeriveScale creates a new derive instruments with the given unit.

func (*Derive) Snapshot

func (d *Derive) Snapshot() float64

Snapshot returns the number of values per seconds since the last snapshot, and reset the count to zero.

func (*Derive) Update

func (d *Derive) Update(v float64)

Update update rate value based on the stored previous value.

type Discrete

type Discrete interface {
	Snapshot() float64
}

Discrete represents a single value instrument.

type Distribution added in v1.3.0

type Distribution interface {
	// Count returns the number of observations
	Count() int
	// Min returns the minimum observed value
	Min() float64
	// Max returns the maximum observed value
	Max() float64
	// Sum returns the sum
	Sum() float64
	// Mean returns the mean
	Mean() float64
	// Quantile returns the quantile for a given q (0..1)
	Quantile(q float64) float64
	// Variance returns the variance
	Variance() float64
	// NumBins number of bins/buckets.
	NumBins() int
	// Bin returns the bin/bucket value and weight at index.
	Bin(index int) (value, weight float64)
}

Distribution is returned by Sample snapshots

type Gauge

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

Gauge tracks a value.

Example
package main

import (
	"fmt"

	"github.com/bsm/instruments"
)

func main() {
	gauge := instruments.NewGauge()
	gauge.Update(35.6)
	fmt.Println(gauge.Snapshot())
}
Output:

35.6

func NewGauge

func NewGauge() *Gauge

NewGauge creates a new Gauge

func (*Gauge) Snapshot

func (g *Gauge) Snapshot() float64

Snapshot returns the current value.

func (*Gauge) Update

func (g *Gauge) Update(v float64)

Update updates the current stored value.

type Logger added in v1.2.0

type Logger interface {
	Printf(string, ...interface{})
}

Logger allows to plug in a logger.

type Rate

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

Rate tracks the rate of values per second.

Example
package main

import (
	"fmt"

	"github.com/bsm/instruments"
)

func main() {
	rate := instruments.NewRate()
	rate.Update(20)
	rate.Update(25)
	fmt.Println(rate.Snapshot())
}
Output:

func NewRate

func NewRate() *Rate

NewRate creates a new rate instrument.

func NewRateScale

func NewRateScale(d time.Duration) *Rate

NewRateScale creates a new rate instruments with the given unit.

func (*Rate) Snapshot

func (r *Rate) Snapshot() float64

Snapshot returns the number of values per second since the last snapshot, and reset the count to zero.

func (*Rate) Update

func (r *Rate) Update(v float64)

Update updates rate value.

type Registry

type Registry struct {
	Logger Logger
	// contains filtered or unexported fields
}

Registry is a registry of all instruments.

Example
package main

import (
	"log"
	"os"
	"time"

	"github.com/bsm/instruments"
	"github.com/bsm/instruments/logreporter"
)

func main() {
	// Create new registry instance, flushing at minutely intervals
	registry := instruments.New(time.Minute, "myapp.")
	defer registry.Close()

	// Subscribe a reporter
	logger := log.New(os.Stdout, "", log.LstdFlags)
	registry.Subscribe(logreporter.New(logger))

	// Fetch a timer
	timer := registry.Timer("processing-time", []string{"tag1", "tag2"})

	// Measure something
	start := time.Now()
	time.Sleep(20 * time.Millisecond)
	timer.Since(start)
}
Output:

func New

func New(flushInterval time.Duration, prefix string, tags ...string) *Registry

New creates a new Registry with a flushInterval at which metrics are reported to the subscribed Reporter instances, a custom prefix which is prepended to every metric name and default tags. Default: 60s

You should call/defer Close() on exit to flush all accummulated data and release all resources.

func NewUnstarted

func NewUnstarted(prefix string, tags ...string) *Registry

NewUnstarted creates a new Registry without a background flush thread.

func (*Registry) AddTags added in v1.1.0

func (r *Registry) AddTags(tags ...string)

AddTags allows to add tags

func (*Registry) Close

func (r *Registry) Close() error

Close flushes all pending data to reporters and releases resources.

func (*Registry) Counter

func (r *Registry) Counter(name string, tags []string) *Counter

Counter fetches an instrument from the registry or creates a new one.

If another instrument type is already registered with the same name/tags, a blank one will be returned and an error will be logged to the Errors() channel.

func (*Registry) Derive

func (r *Registry) Derive(name string, tags []string, v float64) *Derive

Derive fetches an instrument from the registry or creates a new one.

If another instrument type is already registered with the same name/tags, a blank one will be returned and an error will be logged to the Errors() channel.

func (*Registry) DeriveScale

func (r *Registry) DeriveScale(name string, tags []string, v float64, d time.Duration) *Derive

DeriveScale fetches an instrument from the registry or creates a new one with a custom scale.

If another instrument type is already registered with the same name/tags, a blank one will be returned and an error will be logged to the Errors() channel.

func (*Registry) Fetch

func (r *Registry) Fetch(name string, tags []string, factory func() interface{}) interface{}

Fetch returns an instrument from the Registry or creates a new one using the provided factory.

func (*Registry) Flush

func (r *Registry) Flush() error

Flush performs a manual flush to all subscribed reporters. This method is usually called by a background thread every flushInterval, specified in New()

func (*Registry) Gauge

func (r *Registry) Gauge(name string, tags []string) *Gauge

Gauge fetches an instrument from the registry or creates a new one.

If another instrument type is already registered with the same name/tags, a blank one will be returned and an error will be logged to the Errors() channel.

func (*Registry) Get

func (r *Registry) Get(name string, tags []string) interface{}

Get returns an instrument from the Registry.

func (*Registry) Rate

func (r *Registry) Rate(name string, tags []string) *Rate

Rate fetches an instrument from the registry or creates a new one.

If another instrument type is already registered with the same name/tags, a blank one will be returned and an error will be logged to the Errors() channel.

func (*Registry) RateScale

func (r *Registry) RateScale(name string, tags []string, d time.Duration) *Rate

RateScale fetches an instrument from the registry or creates a new one with a custom scale.

If another instrument type is already registered with the same name/tags, a blank one will be returned and an error will be logged to the Errors() channel.

func (*Registry) Register

func (r *Registry) Register(name string, tags []string, v interface{})

Register registers a new instrument.

func (*Registry) Reservoir

func (r *Registry) Reservoir(name string, tags []string) *Reservoir

Reservoir fetches an instrument from the registry or creates a new one.

If another instrument type is already registered with the same name/tags, a blank one will be returned and an error will be logged to the Errors() channel.

func (*Registry) SetTags added in v1.1.0

func (r *Registry) SetTags(tags ...string)

SetTags allows to set tags

func (*Registry) Size

func (r *Registry) Size() int

Size returns the numbers of instruments in the registry.

func (*Registry) Subscribe

func (r *Registry) Subscribe(rep Reporter)

Subscribe attaches a reporter to the Registry.

func (*Registry) Tags added in v1.1.0

func (r *Registry) Tags() []string

Tags returns global registry tags

func (*Registry) Timer

func (r *Registry) Timer(name string, tags []string) *Timer

Timer fetches an instrument from the registry or creates a new one.

If another instrument type is already registered with the same name/tags, a blank one will be returned and an error will be logged to the Errors() channel.

func (*Registry) Unregister

func (r *Registry) Unregister(name string, tags []string)

Unregister remove from the registry the instrument matching the given name/tags

type Reporter

type Reporter interface {
	// Prep is called at the beginning of each reporting cycle, which
	// allows reporters to prepare for next data snapshot.
	Prep() error
	// Discrete accepts a numeric value with name and (sorted) tags
	Discrete(name string, tags []string, value float64) error
	// Sample accepts a sampled distribution with name and (sorted) tags
	Sample(name string, tags []string, dist Distribution) error
	// Flush is called at the end of each reporting cycle, which
	// allows reporters to safely buffer data and emit it to
	// backend as a bulk.
	Flush() error
}

Reporter describes the interface every reporter must follow. See logreporter package as an example.

type Reservoir

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

Reservoir tracks a sample of values.

Example
package main

import (
	"fmt"

	"github.com/bsm/instruments"
)

func main() {
	reservoir := instruments.NewReservoir()
	reservoir.Update(12)
	reservoir.Update(54)
	reservoir.Update(34)
	fmt.Println(reservoir.Snapshot().Quantile(0.99))
}
Output:

54

func NewReservoir

func NewReservoir() *Reservoir

NewReservoir creates a new reservoir

func (*Reservoir) Snapshot

func (r *Reservoir) Snapshot() Distribution

Snapshot returns a Distribution

func (*Reservoir) Update

func (r *Reservoir) Update(v float64)

Update fills the sample randomly with given value, for reference, see: http://en.wikipedia.org/wiki/Reservoir_sampling

type Sample

type Sample interface {
	Snapshot() Distribution
}

Sample represents a sample instrument.

type Timer

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

Timer tracks durations.

Example
package main

import (
	"fmt"
	"time"

	"github.com/bsm/instruments"
)

func main() {
	timer := instruments.NewTimer()
	ts := time.Now()
	time.Sleep(10 * time.Millisecond)
	timer.Since(ts)
	fmt.Println(timer.Snapshot().Quantile(0.99))
}
Output:

func NewTimer

func NewTimer() *Timer

NewTimer creates a new Timer with millisecond resolution

func (*Timer) Since

func (t *Timer) Since(start time.Time)

Since records duration since the given start time.

func (*Timer) Snapshot

func (t *Timer) Snapshot() Distribution

Snapshot returns durations distribution

func (*Timer) Update

func (t *Timer) Update(d time.Duration)

Update adds duration to the sample in ms.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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