metrics

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2021 License: Apache-2.0 Imports: 12 Imported by: 18

README

Metrics is a simple library for collecting metrics for golang applications.

Example API use

// Initialize a metric context
m := metrics.NewMetricContext("system")

// Create a basic counter, all ops are atomic
c := metrics.NewBasicCounter()

c.Add(n)    // increment counter by delta n
c.Set(n)    // Set counter value to n


// Create a new counter; has additional state associated with it
// to calculate rate

c := metrics.NewCounter()

c.Add(n)    // increment counter by delta n
c.Set(n)    // Set counter value to n

r := c.ComputeRate() // compute rate of change/sec

// Create a new gauge
// Set/Get acquire a mutex
c := metrics.NewGauge()
c.Set(12.0) // Set Value
c.Get() // get Value

// StatsTimer - useful for computing statistics on timed operations
s := metrics.NewStatsTimer()

t := s.Start() // returns a timer
s.Stop(t) // stop the timer

// Example
func (* Webapp) ServeRequest(uri string) error {
	t := s.Start()

	// do something
	s.Stop(t)
}
pctile_75th, err := s.Percentile(75)
if err == nil {
	fmt.Println("Percentile latency for 75 pctile: ", pctile_75th)
}


// Launch a goroutine to serve metrics via http json
go func() {
	http.HandleFunc("/metrics.json", m.HttpJsonHandler)
	http.ListenAndServe("localhost:12345", nil)
}

// Get metrics via http json.
resp, err := http.Get("http://localhost:12345/metrics.json")

FAQ

  • What metric type should be used? We follow venerable RRD conventions.
    • A gauge should be used for things like memory used at particular instant, or say price of AAPL stock.
    • A counter should be used for continuous incrementing counters - say for example - you are reading counters stored by kernel in /proc, like number of jiffies spent in kernel processing or if your app needs to keep track of say number of requests served. Use a basiccounter for lock-free counter.

Documentation

Index

Constants

View Source
const NsInSec = float64(time.Second)

nanoseconds in a second represented in float64

Variables

View Source
var Percentiles = []float64{50, 75, 95, 99, 99.9, 99.99, 99.999}

Percentiles are default percentiles to compute when serializing statstimer type to stdout/json

Functions

This section is empty.

Types

type BasicCounter

type BasicCounter uint64

BasicCounter is a minimal counter(uint64) - all operations are atomic Usage:

b := metrics.NewBasicCounter()
b.Add(1)
b.Get()

func NewBasicCounter

func NewBasicCounter() *BasicCounter

NewBasicCounter initializes and returns a BasicCounter

func (*BasicCounter) Add

func (c *BasicCounter) Add(delta uint64)

Add delta to counter value v

func (*BasicCounter) Get

func (c *BasicCounter) Get() uint64

Get value of counter

func (*BasicCounter) MarshalJSON

func (c *BasicCounter) MarshalJSON() ([]byte, error)

MarshalJSON returns a byte slice of JSON representation of basiccounter

func (*BasicCounter) Reset

func (c *BasicCounter) Reset()

Reset counter to zero

func (*BasicCounter) Set

func (c *BasicCounter) Set(v uint64)

Set counter to value v.

type Counter

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

Counter represents an always incrementing metric type Counter differs from BasicCounter by having additional fields for computing rate. Operations on counter hold a mutex. use BasicCounter if you need lock-free counters

func NewCounter

func NewCounter() *Counter

NewCounter initializes and returns a new counter

func (*Counter) Add

func (c *Counter) Add(delta uint64)

Add - add input value to counter

func (*Counter) ComputeRate

func (c *Counter) ComputeRate() float64

ComputeRate calculates the rate of change of counter per second. (acquires a lock)

func (*Counter) Get

func (c *Counter) Get() uint64

Get - returns current value of counter

func (*Counter) MarshalJSON

func (c *Counter) MarshalJSON() ([]byte, error)

MarshalJSON returns a byte slice of JSON representation of counter

func (*Counter) Reset

func (c *Counter) Reset()

Reset - resets all internal variables to defaults Usually called from NewCounter but useful if you have to re-use and existing object

func (*Counter) Set

func (c *Counter) Set(v uint64)

Set - Sets counter to input value. This is useful if you are reading a metric that is already a counter

type Gauge

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

Gauge represents a metric of type Gauge. An example would be number of users logged in at the moment.

func NewGauge

func NewGauge() *Gauge

NewGauge initializes a Gauge and returns it

func (*Gauge) Get

func (g *Gauge) Get() float64

Get - Returns current value of Gauge

func (*Gauge) MarshalJSON

func (g *Gauge) MarshalJSON() ([]byte, error)

MarshalJSON returns a byte slice of JSON representation of Gauge

func (*Gauge) Reset

func (g *Gauge) Reset()

Reset - resets all values are reset to defaults Usually called from NewGauge but useful if you have to re-use and existing object

func (*Gauge) Set

func (g *Gauge) Set(v float64)

Set - Sets value of Gauge to input

type MetricContext

type MetricContext struct {
	Counters      map[string]*Counter
	Gauges        map[string]*Gauge
	BasicCounters map[string]*BasicCounter
	StatsTimers   map[string]*StatsTimer
	OutputFilter  OutputFilterFunc
	// contains filtered or unexported fields
}

MetricContext represents a reference to all metrics registered by name within a namespace

func NewMetricContext

func NewMetricContext(namespace string) *MetricContext

NewMetricContext initializes a MetricContext with the input namespace and returns it

func (*MetricContext) EncodeJSON

func (m *MetricContext) EncodeJSON(w io.Writer) error

EncodeJSON is a streaming encoder that writes all metrics passing filter to writer w as JSON

func (*MetricContext) HttpJsonHandler

func (m *MetricContext) HttpJsonHandler(w http.ResponseWriter, r *http.Request)

HttpJsonHandler setups a handler for exposing metrics via JSON over HTTP

func (*MetricContext) Register

func (m *MetricContext) Register(v interface{}, name string)

Register registers a metric with metriccontext

func (*MetricContext) Unregister

func (m *MetricContext) Unregister(v interface{}, name string)

Unregister unregisters a metric with metriccontext

type MetricJSON

type MetricJSON struct {
	Type  string
	Name  string
	Value interface{}
}

MetricJSON is a type for serializing any metric type

type OutputFilterFunc

type OutputFilterFunc func(name string, v interface{}) bool

OutputFilterFunc represents a function that is used to filter metrics from being reported out from JSON handler

type StatsTimer

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

StatsTimer represents a metric of type statstimer

func NewStatsTimer

func NewStatsTimer(timeUnit time.Duration, nsamples int) *StatsTimer

NewStatsTimer initializes and returns a StatsTimer. StatTimer can be used to compute statistics for a timed operation. Arguments:

timeUnit time.Duration - time unit to report statistics on
nsamples int - number of samples to keep in-memory for stats computation

Example:

m := metrics.NewMetricContext("webapp")
s := m.NewStatsTimer("latency", time.Millisecond, 100)
func (wa *WebApp)  HandleQuery(w http.ResponseWriter, r *http.Request) {
   stopWatch := s.Start()
   ... do work...
   s.Stop(stopWatch)
}
pctile95, err := s.Percentile(95)
if err == nil {
  fmt.Printf("95th percentile for latency: ", pctile95)
}

func (*StatsTimer) MarshalJSON

func (s *StatsTimer) MarshalJSON() ([]byte, error)

MarshalJSON returns a byte slice containing representation of StatsTimer

func (*StatsTimer) Percentile

func (s *StatsTimer) Percentile(percentile float64) (float64, error)

Percentile returns the value at input percentile Implementation is based on Nearest rank http://en.wikipedia.org/wiki/Percentile

func (*StatsTimer) Reset

func (s *StatsTimer) Reset()

Reset - resets the stat of StatsTimer

func (*StatsTimer) Start

func (s *StatsTimer) Start() *Timer

Start - Start a stopWatch for the StatsTimer and returns it

func (*StatsTimer) Stop

func (s *StatsTimer) Stop(t *Timer) float64

Stop - Stops the stopWatch for the StatsTimer.

type Timer

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

Timer represents a type to store data for implementing a timer

func NewTimer

func NewTimer() *Timer

NewTimer returns a Timer

func (*Timer) Get

func (t *Timer) Get() int64

Get returns the current value of timer or zero if the timer is still running

func (*Timer) Start

func (t *Timer) Start()

Start initializes and starts a Timer

func (*Timer) Stop

func (t *Timer) Stop() int64

Stop stops the Timer

Jump to

Keyboard shortcuts

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