metrics

package
v1.14.6-0...-341647f Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2024 License: GPL-3.0, BSD-2-Clause-Views Imports: 25 Imported by: 6,199

README

go-metrics

travis build status

Go port of Coda Hale's Metrics library: https://github.com/dropwizard/metrics.

Documentation: https://godoc.org/github.com/rcrowley/go-metrics.

Usage

Create and update metrics:

c := metrics.NewCounter()
metrics.Register("foo", c)
c.Inc(47)

g := metrics.NewGauge()
metrics.Register("bar", g)
g.Update(47)

r := NewRegistry()
g := metrics.NewRegisteredFunctionalGauge("cache-evictions", r, func() int64 { return cache.getEvictionsCount() })

s := metrics.NewExpDecaySample(1028, 0.015) // or metrics.NewUniformSample(1028)
h := metrics.NewHistogram(s)
metrics.Register("baz", h)
h.Update(47)

m := metrics.NewMeter()
metrics.Register("quux", m)
m.Mark(47)

t := metrics.NewTimer()
metrics.Register("bang", t)
t.Time(func() {})
t.Update(47)

Register() is not threadsafe. For threadsafe metric registration use GetOrRegister:

t := metrics.GetOrRegisterTimer("account.create.latency", nil)
t.Time(func() {})
t.Update(47)

NOTE: Be sure to unregister short-lived meters and timers otherwise they will leak memory:

// Will call Stop() on the Meter to allow for garbage collection
metrics.Unregister("quux")
// Or similarly for a Timer that embeds a Meter
metrics.Unregister("bang")

Periodically log every metric in human-readable form to standard error:

go metrics.Log(metrics.DefaultRegistry, 5 * time.Second, log.New(os.Stderr, "metrics: ", log.Lmicroseconds))

Periodically log every metric in slightly-more-parseable form to syslog:

w, _ := syslog.Dial("unixgram", "/dev/log", syslog.LOG_INFO, "metrics")
go metrics.Syslog(metrics.DefaultRegistry, 60e9, w)

Periodically emit every metric to Graphite using the Graphite client:


import "github.com/cyberdelia/go-metrics-graphite"

addr, _ := net.ResolveTCPAddr("tcp", "127.0.0.1:2003")
go graphite.Graphite(metrics.DefaultRegistry, 10e9, "metrics", addr)

Periodically emit every metric into InfluxDB:

NOTE: this has been pulled out of the library due to constant fluctuations in the InfluxDB API. In fact, all client libraries are on their way out. see issues #121 and #124 for progress and details.

import "github.com/vrischmann/go-metrics-influxdb"

go influxdb.InfluxDB(metrics.DefaultRegistry,
  10e9, 
  "127.0.0.1:8086", 
  "database-name", 
  "username", 
  "password"
)

Periodically emit every metric to StatHat:

import "github.com/rcrowley/go-metrics/stathat"

go stathat.Stathat(metrics.DefaultRegistry, 10e9, "example@example.com")

Maintain all metrics along with expvars at /debug/metrics:

This uses the same mechanism as the official expvar but exposed under /debug/metrics, which shows a json representation of all your usual expvars as well as all your go-metrics.

import "github.com/rcrowley/go-metrics/exp"

exp.Exp(metrics.DefaultRegistry)

Installation

go get github.com/rcrowley/go-metrics

StatHat support additionally requires their Go client:

go get github.com/stathat/go

Publishing Metrics

Clients are available for the following destinations:

Documentation

Overview

Go port of Coda Hale's Metrics library

<https://github.com/rcrowley/go-metrics>

Coda Hale's original work: <https://github.com/codahale/metrics>

Example
c := NewCounter()
Register("money", c)
c.Inc(17)

// Threadsafe registration
t := GetOrRegisterTimer("db.get.latency", nil)
t.Time(func() { time.Sleep(10 * time.Millisecond) })
t.Update(1)

fmt.Println(c.Snapshot().Count())
fmt.Println(t.Snapshot().Min())
Output:

17
1

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultConfig = Config{
	Enabled:          false,
	EnabledExpensive: false,
	HTTP:             "127.0.0.1",
	Port:             6060,
	EnableInfluxDB:   false,
	InfluxDBEndpoint: "http://localhost:8086",
	InfluxDBDatabase: "geth",
	InfluxDBUsername: "test",
	InfluxDBPassword: "test",
	InfluxDBTags:     "host=localhost",

	EnableInfluxDBV2:     false,
	InfluxDBToken:        "test",
	InfluxDBBucket:       "geth",
	InfluxDBOrganization: "geth",
}

DefaultConfig is the default config for metrics used in go-ethereum.

View Source
var (
	DefaultRegistry = NewRegistry()
)
View Source
var ErrDuplicateMetric = errors.New("duplicate metric")

ErrDuplicateMetric is the error returned by Registry.Register when a metric already exists. If you mean to Register that metric you must first Unregister the existing metric.

Functions

func CalculatePercentiles added in v1.13.1

func CalculatePercentiles(values []int64, ps []float64) []float64

CalculatePercentiles returns a slice of arbitrary percentiles of the slice of int64. This method returns interpolated results, so e.g. if there are only two values, [0, 10], a 50% percentile will land between them.

Note: As a side-effect, this method will also sort the slice of values. Note2: The input format for percentiles is NOT percent! To express 50%, use 0.5, not 50.

func CaptureDebugGCStats added in v1.8.2

func CaptureDebugGCStats(r Registry, d time.Duration)

CaptureDebugGCStats captures new values for the Go garbage collector statistics exported in debug.GCStats. This is designed to be called as a goroutine.

func CaptureDebugGCStatsOnce added in v1.8.2

func CaptureDebugGCStatsOnce(r Registry)

CaptureDebugGCStatsOnce captures new values for the Go garbage collector statistics exported in debug.GCStats. This is designed to be called in a background goroutine. Giving a registry which has not been given to RegisterDebugGCStats will panic.

Be careful (but much less so) with this because debug.ReadGCStats calls the C function runtime·lock(runtime·mheap) which, while not a stop-the-world operation, isn't something you want to be doing all the time.

func CollectProcessMetrics added in v0.9.34

func CollectProcessMetrics(refresh time.Duration)

CollectProcessMetrics periodically collects various metrics about the running process.

func Each added in v1.8.2

func Each(f func(string, interface{}))

Each call the given function for each registered metric.

func Enable

func Enable()

Enable enables the metrics system. The Enabled-flag is expected to be set, once, during startup, but toggling off and on is not supported.

Enable is not safe to call concurrently. You need to call this as early as possible in the program, before any metrics collection will happen.

func Enabled added in v1.2.2

func Enabled() bool

Enabled is checked by functions that are deemed 'expensive', e.g. if a meter-type does locking and/or non-trivial math operations during update.

func Get added in v1.8.2

func Get(name string) interface{}

Get the metric by the given name or nil if none is registered.

func GetOrRegister added in v1.8.2

func GetOrRegister(name string, i interface{}) interface{}

GetOrRegister gets an existing metric or creates and registers a new one. Threadsafe alternative to calling Get and Register on failure.

func Log added in v1.8.2

func Log(r Registry, freq time.Duration, l Logger)

func LogScaled added in v1.8.2

func LogScaled(r Registry, freq time.Duration, scale time.Duration, l Logger)

Output each metric in the given registry periodically using the given logger. Print timings in `scale` units (eg time.Millisecond) rather than nanos.

func MustRegister added in v1.8.2

func MustRegister(name string, i interface{})

MustRegister register the given metric under the given name. Panics if a metric by the given name is already registered.

func OpenTSDB added in v1.8.2

func OpenTSDB(r Registry, d time.Duration, prefix string, addr *net.TCPAddr)

OpenTSDB is a blocking exporter function which reports metrics in r to a TSDB server located at addr, flushing them every d duration and prepending metric names with prefix.

Example
addr, _ := net.ResolveTCPAddr("net", ":2003")
go OpenTSDB(DefaultRegistry, 1*time.Second, "some.prefix", addr)
Output:

func OpenTSDBWithConfig added in v1.8.2

func OpenTSDBWithConfig(c OpenTSDBConfig)

OpenTSDBWithConfig is a blocking exporter function just like OpenTSDB, but it takes a OpenTSDBConfig instead.

Example
addr, _ := net.ResolveTCPAddr("net", ":2003")
go OpenTSDBWithConfig(OpenTSDBConfig{
	Addr:          addr,
	Registry:      DefaultRegistry,
	FlushInterval: 1 * time.Second,
	DurationUnit:  time.Millisecond,
})
Output:

func ReadCPUStats added in v1.9.0

func ReadCPUStats(stats *CPUStats)

ReadCPUStats retrieves the current CPU stats.

func ReadDiskStats added in v0.9.34

func ReadDiskStats(stats *DiskStats) error

ReadDiskStats retrieves the disk IO stats belonging to the current process.

func ReadRuntimeStats added in v1.13.1

func ReadRuntimeStats() *runtimeStats

func Register added in v1.8.2

func Register(name string, i interface{}) error

Register the given metric under the given name. Returns a ErrDuplicateMetric if a metric by the given name is already registered.

func RegisterDebugGCStats added in v1.8.2

func RegisterDebugGCStats(r Registry)

RegisterDebugGCStats registers metrics for the Go garbage collector statistics exported in debug.GCStats. The metrics are named by their fully-qualified Go symbols, i.e. debug.GCStats.PauseTotal.

func RunHealthchecks added in v1.8.2

func RunHealthchecks()

RunHealthchecks run all registered healthchecks.

func RuntimeHistogramFromData added in v1.13.1

func RuntimeHistogramFromData(scale float64, hist *metrics.Float64Histogram) *runtimeHistogram

func SamplePercentile added in v1.8.2

func SamplePercentile(values []int64, p float64) float64

SamplePercentile returns an arbitrary percentile of the slice of int64.

func SampleVariance added in v1.8.2

func SampleVariance(mean float64, values []int64) float64

SampleVariance returns the variance of the slice of int64.

func Syslog added in v1.8.2

func Syslog(r Registry, d time.Duration, w *syslog.Writer)

Output each metric in the given registry to syslog periodically using the given syslogger.

func Unregister added in v1.8.2

func Unregister(name string)

Unregister the metric with the given name.

func Write added in v1.8.2

func Write(r Registry, d time.Duration, w io.Writer)

Write sorts writes each metric in the given registry periodically to the given io.Writer.

func WriteJSON added in v1.8.2

func WriteJSON(r Registry, d time.Duration, w io.Writer)

WriteJSON writes metrics from the given registry periodically to the specified io.Writer as JSON.

func WriteJSONOnce added in v1.8.2

func WriteJSONOnce(r Registry, w io.Writer)

WriteJSONOnce writes metrics from the given registry to the specified io.Writer as JSON.

func WriteOnce added in v1.8.2

func WriteOnce(r Registry, w io.Writer)

WriteOnce sorts and writes metrics in the given registry to the given io.Writer.

Types

type CPUStats added in v1.9.0

type CPUStats struct {
	GlobalTime float64 // Time spent by the CPU working on all processes
	GlobalWait float64 // Time spent by waiting on disk for all processes
	LocalTime  float64 // Time spent by the CPU working on this process
}

CPUStats is the system and process CPU stats. All values are in seconds.

type Config added in v1.10.0

type Config struct {
	Enabled          bool   `toml:",omitempty"`
	EnabledExpensive bool   `toml:"-"`
	HTTP             string `toml:",omitempty"`
	Port             int    `toml:",omitempty"`
	EnableInfluxDB   bool   `toml:",omitempty"`
	InfluxDBEndpoint string `toml:",omitempty"`
	InfluxDBDatabase string `toml:",omitempty"`
	InfluxDBUsername string `toml:",omitempty"`
	InfluxDBPassword string `toml:",omitempty"`
	InfluxDBTags     string `toml:",omitempty"`

	EnableInfluxDBV2     bool   `toml:",omitempty"`
	InfluxDBToken        string `toml:",omitempty"`
	InfluxDBBucket       string `toml:",omitempty"`
	InfluxDBOrganization string `toml:",omitempty"`
}

Config contains the configuration for the metric collection.

type Counter added in v1.8.2

type Counter atomic.Int64

Counter hold an int64 value that can be incremented and decremented.

func GetOrRegisterCounter added in v1.8.2

func GetOrRegisterCounter(name string, r Registry) *Counter

GetOrRegisterCounter returns an existing Counter or constructs and registers a new Counter.

func NewCounter added in v1.5.0

func NewCounter() *Counter

NewCounter constructs a new Counter.

func NewRegisteredCounter added in v1.8.2

func NewRegisteredCounter(name string, r Registry) *Counter

NewRegisteredCounter constructs and registers a new Counter.

func (*Counter) Clear added in v1.8.2

func (c *Counter) Clear()

Clear sets the counter to zero.

func (*Counter) Dec added in v1.8.2

func (c *Counter) Dec(i int64)

Dec decrements the counter by the given amount.

func (*Counter) Inc added in v1.8.2

func (c *Counter) Inc(i int64)

Inc increments the counter by the given amount.

func (*Counter) Snapshot added in v1.8.2

func (c *Counter) Snapshot() CounterSnapshot

Snapshot returns a read-only copy of the counter.

type CounterFloat64 added in v1.11.6

type CounterFloat64 atomic.Uint64

CounterFloat64 holds a float64 value that can be incremented and decremented.

func GetOrRegisterCounterFloat64 added in v1.11.6

func GetOrRegisterCounterFloat64(name string, r Registry) *CounterFloat64

GetOrRegisterCounterFloat64 returns an existing *CounterFloat64 or constructs and registers a new CounterFloat64.

func NewCounterFloat64 added in v1.11.6

func NewCounterFloat64() *CounterFloat64

NewCounterFloat64 constructs a new CounterFloat64.

func NewRegisteredCounterFloat64 added in v1.11.6

func NewRegisteredCounterFloat64(name string, r Registry) *CounterFloat64

NewRegisteredCounterFloat64 constructs and registers a new CounterFloat64.

func (*CounterFloat64) Clear added in v1.11.6

func (c *CounterFloat64) Clear()

Clear sets the counter to zero.

func (*CounterFloat64) Dec added in v1.11.6

func (c *CounterFloat64) Dec(v float64)

Dec decrements the counter by the given amount.

func (*CounterFloat64) Inc added in v1.11.6

func (c *CounterFloat64) Inc(v float64)

Inc increments the counter by the given amount.

func (*CounterFloat64) Snapshot added in v1.11.6

func (c *CounterFloat64) Snapshot() CounterFloat64Snapshot

Snapshot returns a read-only copy of the counter.

type CounterFloat64Snapshot added in v1.11.6

type CounterFloat64Snapshot float64

CounterFloat64Snapshot is a read-only copy of a float64 counter.

func (CounterFloat64Snapshot) Count added in v1.11.6

func (c CounterFloat64Snapshot) Count() float64

Count returns the value at the time the snapshot was taken.

type CounterSnapshot added in v1.8.2

type CounterSnapshot int64

CounterSnapshot is a read-only copy of a Counter.

func (CounterSnapshot) Count added in v1.8.2

func (c CounterSnapshot) Count() int64

Count returns the count at the time the snapshot was taken.

type DiskStats added in v0.9.34

type DiskStats struct {
	ReadCount  int64 // Number of read operations executed
	ReadBytes  int64 // Total number of bytes read
	WriteCount int64 // Number of write operations executed
	WriteBytes int64 // Total number of byte written
}

DiskStats is the per process disk io stats.

type EWMA added in v1.8.2

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

EWMA continuously calculate an exponentially-weighted moving average based on an outside source of clock ticks.

func NewEWMA added in v1.8.2

func NewEWMA(alpha float64) *EWMA

NewEWMA constructs a new EWMA with the given alpha.

func NewEWMA1 added in v1.8.2

func NewEWMA1() *EWMA

NewEWMA1 constructs a new EWMA for a one-minute moving average.

func NewEWMA15 added in v1.8.2

func NewEWMA15() *EWMA

NewEWMA15 constructs a new EWMA for a fifteen-minute moving average.

func NewEWMA5 added in v1.8.2

func NewEWMA5() *EWMA

NewEWMA5 constructs a new EWMA for a five-minute moving average.

func (*EWMA) Snapshot added in v1.8.2

func (a *EWMA) Snapshot() EWMASnapshot

Snapshot returns a read-only copy of the EWMA.

func (*EWMA) Update added in v1.8.2

func (a *EWMA) Update(n int64)

Update adds n uncounted events.

type EWMASnapshot added in v1.8.2

type EWMASnapshot float64

EWMASnapshot is a read-only copy of an EWMA.

func (EWMASnapshot) Rate added in v1.8.2

func (a EWMASnapshot) Rate() float64

Rate returns the rate of events per second at the time the snapshot was taken.

type ExpDecaySample added in v1.8.2

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

ExpDecaySample is an exponentially-decaying sample using a forward-decaying priority reservoir. See Cormode et al's "Forward Decay: A Practical Time Decay Model for Streaming Systems".

<http://dimacs.rutgers.edu/~graham/pubs/papers/fwddecay.pdf>

func (*ExpDecaySample) Clear added in v1.8.2

func (s *ExpDecaySample) Clear()

Clear clears all samples.

func (*ExpDecaySample) SetRand added in v1.11.1

func (s *ExpDecaySample) SetRand(prng *rand.Rand) Sample

SetRand sets the random source (useful in tests)

func (*ExpDecaySample) Snapshot added in v1.8.2

func (s *ExpDecaySample) Snapshot() *sampleSnapshot

Snapshot returns a read-only copy of the sample.

func (*ExpDecaySample) Update added in v1.8.2

func (s *ExpDecaySample) Update(v int64)

Update samples a new value.

type Gauge added in v1.8.2

type Gauge atomic.Int64

Gauge holds an int64 value that can be set arbitrarily.

func GetOrRegisterGauge added in v1.8.2

func GetOrRegisterGauge(name string, r Registry) *Gauge

GetOrRegisterGauge returns an existing Gauge or constructs and registers a new Gauge.

func NewGauge added in v1.8.2

func NewGauge() *Gauge

NewGauge constructs a new Gauge.

func NewRegisteredGauge added in v1.8.2

func NewRegisteredGauge(name string, r Registry) *Gauge

NewRegisteredGauge constructs and registers a new Gauge.

func (*Gauge) Dec added in v1.9.4

func (g *Gauge) Dec(i int64)

Dec decrements the gauge's current value by the given amount.

func (*Gauge) Inc added in v1.9.4

func (g *Gauge) Inc(i int64)

Inc increments the gauge's current value by the given amount.

func (*Gauge) Snapshot added in v1.8.2

func (g *Gauge) Snapshot() GaugeSnapshot

Snapshot returns a read-only copy of the gauge.

func (*Gauge) Update added in v1.8.2

func (g *Gauge) Update(v int64)

Update updates the gauge's value.

func (*Gauge) UpdateIfGt added in v1.13.1

func (g *Gauge) UpdateIfGt(v int64)

UpdateIfGt updates the gauge's value if v is larger then the current value.

type GaugeFloat64 added in v1.8.2

type GaugeFloat64 atomic.Uint64

GaugeFloat64 hold a float64 value that can be set arbitrarily.

func GetOrRegisterGaugeFloat64 added in v1.8.2

func GetOrRegisterGaugeFloat64(name string, r Registry) *GaugeFloat64

GetOrRegisterGaugeFloat64 returns an existing GaugeFloat64 or constructs and registers a new GaugeFloat64.

func NewGaugeFloat64 added in v1.8.2

func NewGaugeFloat64() *GaugeFloat64

NewGaugeFloat64 constructs a new GaugeFloat64.

func NewRegisteredGaugeFloat64 added in v1.8.2

func NewRegisteredGaugeFloat64(name string, r Registry) *GaugeFloat64

NewRegisteredGaugeFloat64 constructs and registers a new GaugeFloat64.

func (*GaugeFloat64) Snapshot added in v1.8.2

func (g *GaugeFloat64) Snapshot() GaugeFloat64Snapshot

Snapshot returns a read-only copy of the gauge.

func (*GaugeFloat64) Update added in v1.8.2

func (g *GaugeFloat64) Update(v float64)

Update updates the gauge's value.

type GaugeFloat64Snapshot added in v1.8.2

type GaugeFloat64Snapshot float64

GaugeFloat64Snapshot is a read-only copy of a GaugeFloat64.

func (GaugeFloat64Snapshot) Value added in v1.8.2

func (g GaugeFloat64Snapshot) Value() float64

Value returns the value at the time the snapshot was taken.

type GaugeInfo added in v1.13.0

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

GaugeInfo maintains a set of key/value mappings.

func GetOrRegisterGaugeInfo added in v1.13.0

func GetOrRegisterGaugeInfo(name string, r Registry) *GaugeInfo

GetOrRegisterGaugeInfo returns an existing GaugeInfo or constructs and registers a new GaugeInfo.

func NewGaugeInfo added in v1.13.0

func NewGaugeInfo() *GaugeInfo

NewGaugeInfo constructs a new GaugeInfo.

func NewRegisteredGaugeInfo added in v1.13.0

func NewRegisteredGaugeInfo(name string, r Registry) *GaugeInfo

NewRegisteredGaugeInfo constructs and registers a new GaugeInfo.

func (*GaugeInfo) Snapshot added in v1.13.0

func (g *GaugeInfo) Snapshot() GaugeInfoSnapshot

Snapshot returns a read-only copy of the gauge.

func (*GaugeInfo) Update added in v1.13.0

func (g *GaugeInfo) Update(v GaugeInfoValue)

Update updates the gauge's value.

type GaugeInfoSnapshot added in v1.13.0

type GaugeInfoSnapshot GaugeInfoValue

gaugeInfoSnapshot is a read-only copy of another GaugeInfo.

func (GaugeInfoSnapshot) Value added in v1.13.0

Value returns the value at the time the snapshot was taken.

type GaugeInfoValue added in v1.13.0

type GaugeInfoValue map[string]string

GaugeInfoValue is a mapping of keys to values

func (GaugeInfoValue) String added in v1.13.0

func (val GaugeInfoValue) String() string

type GaugeSnapshot added in v1.8.2

type GaugeSnapshot int64

GaugeSnapshot is a read-only copy of a Gauge.

func (GaugeSnapshot) Value added in v1.8.2

func (g GaugeSnapshot) Value() int64

Value returns the value at the time the snapshot was taken.

type Healthcheck added in v1.8.2

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

Healthcheck is the standard implementation of a Healthcheck and stores the status and a function to call to update the status.

func NewHealthcheck added in v1.8.2

func NewHealthcheck(f func(*Healthcheck)) *Healthcheck

NewHealthcheck constructs a new Healthcheck which will use the given function to update its status.

func (*Healthcheck) Check added in v1.8.2

func (h *Healthcheck) Check()

Check runs the healthcheck function to update the healthcheck's status.

func (*Healthcheck) Error added in v1.8.2

func (h *Healthcheck) Error() error

Error returns the healthcheck's status, which will be nil if it is healthy.

func (*Healthcheck) Healthy added in v1.8.2

func (h *Healthcheck) Healthy()

Healthy marks the healthcheck as healthy.

func (*Healthcheck) Unhealthy added in v1.8.2

func (h *Healthcheck) Unhealthy(err error)

Unhealthy marks the healthcheck as unhealthy. The error is stored and may be retrieved by the Error method.

type Histogram added in v1.8.2

type Histogram interface {
	Clear()
	Update(int64)
	Snapshot() HistogramSnapshot
}

Histogram calculates distribution statistics from a series of int64 values.

func GetOrRegisterHistogram added in v1.8.2

func GetOrRegisterHistogram(name string, r Registry, s Sample) Histogram

GetOrRegisterHistogram returns an existing Histogram or constructs and registers a new StandardHistogram.

func GetOrRegisterHistogramLazy added in v1.10.2

func GetOrRegisterHistogramLazy(name string, r Registry, s func() Sample) Histogram

GetOrRegisterHistogramLazy returns an existing Histogram or constructs and registers a new StandardHistogram.

func NewHistogram added in v1.8.2

func NewHistogram(s Sample) Histogram

NewHistogram constructs a new StandardHistogram from a Sample.

func NewRegisteredHistogram added in v1.8.2

func NewRegisteredHistogram(name string, r Registry, s Sample) Histogram

NewRegisteredHistogram constructs and registers a new StandardHistogram from a Sample.

type HistogramSnapshot added in v1.8.2

type HistogramSnapshot interface {
	Count() int64
	Max() int64
	Mean() float64
	Min() int64
	Percentile(float64) float64
	Percentiles([]float64) []float64
	Size() int
	StdDev() float64
	Sum() int64
	Variance() float64
}

type Logger added in v1.8.2

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

type Meter added in v1.8.2

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

Meter count events to produce exponentially-weighted moving average rates at one-, five-, and fifteen-minutes and a mean rate.

func GetOrRegisterMeter added in v1.8.2

func GetOrRegisterMeter(name string, r Registry) *Meter

GetOrRegisterMeter returns an existing Meter or constructs and registers a new Meter. Be sure to unregister the meter from the registry once it is of no use to allow for garbage collection.

func NewInactiveMeter added in v1.13.0

func NewInactiveMeter() *Meter

NewInactiveMeter returns a meter but does not start any goroutines. This method is mainly intended for testing.

func NewMeter added in v0.9.34

func NewMeter() *Meter

NewMeter constructs a new Meter and launches a goroutine. Be sure to call Stop() once the meter is of no use to allow for garbage collection.

func NewRegisteredMeter added in v1.8.2

func NewRegisteredMeter(name string, r Registry) *Meter

NewRegisteredMeter constructs and registers a new Meter and launches a goroutine. Be sure to unregister the meter from the registry once it is of no use to allow for garbage collection.

func (*Meter) Mark added in v1.8.2

func (m *Meter) Mark(n int64)

Mark records the occurrence of n events.

func (*Meter) Snapshot added in v1.8.2

func (m *Meter) Snapshot() *MeterSnapshot

Snapshot returns a read-only copy of the meter.

func (*Meter) Stop added in v1.8.2

func (m *Meter) Stop()

Stop stops the meter, Mark() will be a no-op if you use it after being stopped.

type MeterSnapshot added in v1.8.2

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

MeterSnapshot is a read-only copy of the meter's internal values.

func (*MeterSnapshot) Count added in v1.8.2

func (m *MeterSnapshot) Count() int64

Count returns the count of events at the time the snapshot was taken.

func (*MeterSnapshot) Rate1 added in v1.8.2

func (m *MeterSnapshot) Rate1() float64

Rate1 returns the one-minute moving average rate of events per second at the time the snapshot was taken.

func (*MeterSnapshot) Rate15 added in v1.8.2

func (m *MeterSnapshot) Rate15() float64

Rate15 returns the fifteen-minute moving average rate of events per second at the time the snapshot was taken.

func (*MeterSnapshot) Rate5 added in v1.8.2

func (m *MeterSnapshot) Rate5() float64

Rate5 returns the five-minute moving average rate of events per second at the time the snapshot was taken.

func (*MeterSnapshot) RateMean added in v1.8.2

func (m *MeterSnapshot) RateMean() float64

RateMean returns the meter's mean rate of events per second at the time the snapshot was taken.

type OpenTSDBConfig added in v1.8.2

type OpenTSDBConfig struct {
	Addr          *net.TCPAddr  // Network address to connect to
	Registry      Registry      // Registry to be exported
	FlushInterval time.Duration // Flush interval
	DurationUnit  time.Duration // Time conversion unit for durations
	Prefix        string        // Prefix to be prepended to metric names
}

OpenTSDBConfig provides a container with configuration parameters for the OpenTSDB exporter

type PrefixedRegistry added in v1.8.2

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

func (*PrefixedRegistry) Each added in v1.8.2

func (r *PrefixedRegistry) Each(fn func(string, interface{}))

Each call the given function for each registered metric.

func (*PrefixedRegistry) Get added in v1.8.2

func (r *PrefixedRegistry) Get(name string) interface{}

Get the metric by the given name or nil if none is registered.

func (*PrefixedRegistry) GetAll added in v1.8.2

func (r *PrefixedRegistry) GetAll() map[string]map[string]interface{}

GetAll metrics in the Registry

func (*PrefixedRegistry) GetOrRegister added in v1.8.2

func (r *PrefixedRegistry) GetOrRegister(name string, metric interface{}) interface{}

GetOrRegister gets an existing metric or registers the given one. The interface can be the metric to register if not found in registry, or a function returning the metric for lazy instantiation.

func (*PrefixedRegistry) MarshalJSON added in v1.8.2

func (r *PrefixedRegistry) MarshalJSON() ([]byte, error)

func (*PrefixedRegistry) Register added in v1.8.2

func (r *PrefixedRegistry) Register(name string, metric interface{}) error

Register the given metric under the given name. The name will be prefixed.

func (*PrefixedRegistry) RunHealthchecks added in v1.8.2

func (r *PrefixedRegistry) RunHealthchecks()

RunHealthchecks run all registered healthchecks.

func (*PrefixedRegistry) Unregister added in v1.8.2

func (r *PrefixedRegistry) Unregister(name string)

Unregister the metric with the given name. The name will be prefixed.

type Registry added in v1.8.2

type Registry interface {

	// Each call the given function for each registered metric.
	Each(func(string, interface{}))

	// Get the metric by the given name or nil if none is registered.
	Get(string) interface{}

	// GetAll metrics in the Registry.
	GetAll() map[string]map[string]interface{}

	// GetOrRegister gets an existing metric or registers the given one.
	// The interface can be the metric to register if not found in registry,
	// or a function returning the metric for lazy instantiation.
	GetOrRegister(string, interface{}) interface{}

	// Register the given metric under the given name.
	Register(string, interface{}) error

	// RunHealthchecks run all registered healthchecks.
	RunHealthchecks()

	// Unregister the metric with the given name.
	Unregister(string)
}

A Registry holds references to a set of metrics by name and can iterate over them, calling callback functions provided by the user.

This is an interface to encourage other structs to implement the Registry API as appropriate.

func NewOrderedRegistry added in v1.13.0

func NewOrderedRegistry() Registry

NewOrderedRegistry creates a new ordered registry (for testing).

func NewPrefixedChildRegistry added in v1.8.2

func NewPrefixedChildRegistry(parent Registry, prefix string) Registry

func NewPrefixedRegistry added in v1.8.2

func NewPrefixedRegistry(prefix string) Registry

func NewRegistry added in v1.8.2

func NewRegistry() Registry

NewRegistry creates a new registry.

type ResettingTimer added in v1.8.2

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

ResettingTimer is used for storing aggregated values for timers, which are reset on every flush interval.

func GetOrRegisterResettingTimer added in v1.8.2

func GetOrRegisterResettingTimer(name string, r Registry) *ResettingTimer

GetOrRegisterResettingTimer returns an existing ResettingTimer or constructs and registers a new ResettingTimer.

func NewRegisteredResettingTimer added in v1.8.2

func NewRegisteredResettingTimer(name string, r Registry) *ResettingTimer

NewRegisteredResettingTimer constructs and registers a new ResettingTimer.

func NewResettingTimer added in v1.8.2

func NewResettingTimer() *ResettingTimer

NewResettingTimer constructs a new ResettingTimer

func (*ResettingTimer) Snapshot added in v1.8.2

func (t *ResettingTimer) Snapshot() *ResettingTimerSnapshot

Snapshot resets the timer and returns a read-only copy of its contents.

func (*ResettingTimer) Time added in v1.8.2

func (t *ResettingTimer) Time(f func())

Record the duration of the execution of the given function.

func (*ResettingTimer) Update added in v1.8.2

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

Record the duration of an event.

func (*ResettingTimer) UpdateSince added in v1.8.2

func (t *ResettingTimer) UpdateSince(ts time.Time)

Record the duration of an event that started at a time and ends now.

type ResettingTimerSnapshot added in v1.8.2

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

ResettingTimerSnapshot is a point-in-time copy of another ResettingTimer.

func (*ResettingTimerSnapshot) Count added in v1.13.1

func (t *ResettingTimerSnapshot) Count() int

Count return the length of the values from snapshot.

func (*ResettingTimerSnapshot) Max added in v1.13.1

func (t *ResettingTimerSnapshot) Max() int64

Max returns the max of the snapshotted values note: this method is not thread safe

func (*ResettingTimerSnapshot) Mean added in v1.8.2

func (t *ResettingTimerSnapshot) Mean() float64

Mean returns the mean of the snapshotted values note: this method is not thread safe

func (*ResettingTimerSnapshot) Min added in v1.13.1

func (t *ResettingTimerSnapshot) Min() int64

Min returns the min of the snapshotted values note: this method is not thread safe

func (*ResettingTimerSnapshot) Percentiles added in v1.8.2

func (t *ResettingTimerSnapshot) Percentiles(percentiles []float64) []float64

Percentiles returns the boundaries for the input percentiles. note: this method is not thread safe

type Sample added in v1.8.2

type Sample interface {
	Snapshot() *sampleSnapshot
	Clear()
	Update(int64)
}

Sample maintains a statistically-significant selection of values from a stream.

func NewExpDecaySample added in v1.8.2

func NewExpDecaySample(reservoirSize int, alpha float64) Sample

NewExpDecaySample constructs a new exponentially-decaying sample with the given reservoir size and alpha.

func NewUniformSample added in v1.8.2

func NewUniformSample(reservoirSize int) Sample

NewUniformSample constructs a new uniform sample with the given reservoir size.

func ResettingSample added in v1.10.2

func ResettingSample(sample Sample) Sample

ResettingSample converts an ordinary sample into one that resets whenever its snapshot is retrieved. This will break for multi-monitor systems, but when only a single metric is being pushed out, this ensure that low-frequency events don't skew th charts indefinitely.

type StandardHistogram added in v1.8.2

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

StandardHistogram is the standard implementation of a Histogram and uses a Sample to bound its memory use.

func (*StandardHistogram) Clear added in v1.8.2

func (h *StandardHistogram) Clear()

Clear clears the histogram and its sample.

func (*StandardHistogram) Snapshot added in v1.8.2

func (h *StandardHistogram) Snapshot() HistogramSnapshot

Snapshot returns a read-only copy of the histogram.

func (*StandardHistogram) Update added in v1.8.2

func (h *StandardHistogram) Update(v int64)

Update samples a new value.

type StandardRegistry added in v1.8.2

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

StandardRegistry the standard implementation of a Registry uses sync.map of names to metrics.

func (*StandardRegistry) Each added in v1.8.2

func (r *StandardRegistry) Each(f func(string, interface{}))

Each call the given function for each registered metric.

func (*StandardRegistry) Get added in v1.8.2

func (r *StandardRegistry) Get(name string) interface{}

Get the metric by the given name or nil if none is registered.

func (*StandardRegistry) GetAll added in v1.8.2

func (r *StandardRegistry) GetAll() map[string]map[string]interface{}

GetAll metrics in the Registry

func (*StandardRegistry) GetOrRegister added in v1.8.2

func (r *StandardRegistry) GetOrRegister(name string, i interface{}) interface{}

GetOrRegister gets an existing metric or creates and registers a new one. Threadsafe alternative to calling Get and Register on failure. The interface can be the metric to register if not found in registry, or a function returning the metric for lazy instantiation.

func (*StandardRegistry) MarshalJSON added in v1.8.2

func (r *StandardRegistry) MarshalJSON() ([]byte, error)

MarshalJSON returns a byte slice containing a JSON representation of all the metrics in the Registry.

func (*StandardRegistry) Register added in v1.8.2

func (r *StandardRegistry) Register(name string, i interface{}) error

Register the given metric under the given name. Returns a ErrDuplicateMetric if a metric by the given name is already registered.

func (*StandardRegistry) RunHealthchecks added in v1.8.2

func (r *StandardRegistry) RunHealthchecks()

RunHealthchecks run all registered healthchecks.

func (*StandardRegistry) Unregister added in v1.8.2

func (r *StandardRegistry) Unregister(name string)

Unregister the metric with the given name.

type Stoppable added in v1.8.2

type Stoppable interface {
	Stop()
}

Stoppable defines the metrics which has to be stopped.

type Timer added in v1.8.2

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

Timer captures the duration and rate of events, using a Histogram and a Meter.

func GetOrRegisterTimer added in v1.8.2

func GetOrRegisterTimer(name string, r Registry) *Timer

GetOrRegisterTimer returns an existing Timer or constructs and registers a new Timer. Be sure to unregister the meter from the registry once it is of no use to allow for garbage collection.

Example
m := "account.create.latency"
t := GetOrRegisterTimer(m, nil)
t.Update(47)
fmt.Println(t.Snapshot().Max()) 
Output:

47

func NewCustomTimer added in v1.8.2

func NewCustomTimer(h Histogram, m *Meter) *Timer

NewCustomTimer constructs a new Timer from a Histogram and a Meter. Be sure to call Stop() once the timer is of no use to allow for garbage collection.

func NewRegisteredTimer added in v1.8.2

func NewRegisteredTimer(name string, r Registry) *Timer

NewRegisteredTimer constructs and registers a new Timer. Be sure to unregister the meter from the registry once it is of no use to allow for garbage collection.

func NewTimer added in v0.9.34

func NewTimer() *Timer

NewTimer constructs a new Timer using an exponentially-decaying sample with the same reservoir size and alpha as UNIX load averages. Be sure to call Stop() once the timer is of no use to allow for garbage collection.

func (*Timer) Snapshot added in v1.8.2

func (t *Timer) Snapshot() *TimerSnapshot

Snapshot returns a read-only copy of the timer.

func (*Timer) Stop added in v1.8.2

func (t *Timer) Stop()

Stop stops the meter.

func (*Timer) Time added in v1.8.2

func (t *Timer) Time(f func())

Time record the duration of the execution of the given function.

func (*Timer) Update added in v1.8.2

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

Update the duration of an event, in nanoseconds.

func (*Timer) UpdateSince added in v1.8.2

func (t *Timer) UpdateSince(ts time.Time)

UpdateSince update the duration of an event that started at a time and ends now. The record uses nanoseconds.

type TimerSnapshot added in v1.8.2

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

TimerSnapshot is a read-only copy of another Timer.

func (*TimerSnapshot) Count added in v1.8.2

func (t *TimerSnapshot) Count() int64

Count returns the number of events recorded at the time the snapshot was taken.

func (*TimerSnapshot) Max added in v1.8.2

func (t *TimerSnapshot) Max() int64

Max returns the maximum value at the time the snapshot was taken.

func (*TimerSnapshot) Mean added in v1.8.2

func (t *TimerSnapshot) Mean() float64

Mean returns the mean value at the time the snapshot was taken.

func (*TimerSnapshot) Min added in v1.8.2

func (t *TimerSnapshot) Min() int64

Min returns the minimum value at the time the snapshot was taken.

func (*TimerSnapshot) Percentile added in v1.8.2

func (t *TimerSnapshot) Percentile(p float64) float64

Percentile returns an arbitrary percentile of sampled values at the time the snapshot was taken.

func (*TimerSnapshot) Percentiles added in v1.8.2

func (t *TimerSnapshot) Percentiles(ps []float64) []float64

Percentiles returns a slice of arbitrary percentiles of sampled values at the time the snapshot was taken.

func (*TimerSnapshot) Rate1 added in v1.8.2

func (t *TimerSnapshot) Rate1() float64

Rate1 returns the one-minute moving average rate of events per second at the time the snapshot was taken.

func (*TimerSnapshot) Rate15 added in v1.8.2

func (t *TimerSnapshot) Rate15() float64

Rate15 returns the fifteen-minute moving average rate of events per second at the time the snapshot was taken.

func (*TimerSnapshot) Rate5 added in v1.8.2

func (t *TimerSnapshot) Rate5() float64

Rate5 returns the five-minute moving average rate of events per second at the time the snapshot was taken.

func (*TimerSnapshot) RateMean added in v1.8.2

func (t *TimerSnapshot) RateMean() float64

RateMean returns the meter's mean rate of events per second at the time the snapshot was taken.

func (*TimerSnapshot) Size

func (t *TimerSnapshot) Size() int

Size returns the size of the sample at the time the snapshot was taken.

func (*TimerSnapshot) StdDev added in v1.8.2

func (t *TimerSnapshot) StdDev() float64

StdDev returns the standard deviation of the values at the time the snapshot was taken.

func (*TimerSnapshot) Sum added in v1.8.2

func (t *TimerSnapshot) Sum() int64

Sum returns the sum at the time the snapshot was taken.

func (*TimerSnapshot) Variance added in v1.8.2

func (t *TimerSnapshot) Variance() float64

Variance returns the variance of the values at the time the snapshot was taken.

type UniformSample added in v1.8.2

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

UniformSample implements a uniform sample using Vitter's Algorithm R.

<http://www.cs.umd.edu/~samir/498/vitter.pdf>

func (*UniformSample) Clear added in v1.8.2

func (s *UniformSample) Clear()

Clear clears all samples.

func (*UniformSample) SetRand added in v1.11.1

func (s *UniformSample) SetRand(prng *rand.Rand) Sample

SetRand sets the random source (useful in tests)

func (*UniformSample) Snapshot added in v1.8.2

func (s *UniformSample) Snapshot() *sampleSnapshot

Snapshot returns a read-only copy of the sample.

func (*UniformSample) Update added in v1.8.2

func (s *UniformSample) Update(v int64)

Update samples a new value.

Directories

Path Synopsis
Hook go-metrics into expvar on any /debug/metrics request, load all vars from the registry into expvar, and execute regular expvar handler
Hook go-metrics into expvar on any /debug/metrics request, load all vars from the registry into expvar, and execute regular expvar handler
Package prometheus exposes go-metrics into a Prometheus format.
Package prometheus exposes go-metrics into a Prometheus format.

Jump to

Keyboard shortcuts

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