metrics

package module
v0.0.0-...-60c18d2 Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2016 License: MIT Imports: 18 Imported by: 7

README

Metrics

Go Report Card GoDoc codecov Go Report Card

forked from https://github.com/facebookgo/metrics and added some useful types

Introduction

When I use facebook/metrics I find the type of it support just for int64 or int64[], but I should take all the events and error-logs in my developed modular. So I add the flow(流) type and mstring,then you can take some type-string data into it.

How to use it ?

package main

import (
	"fmt"
	"time"

	metrics "github.com/wgliang/metrics"
	metricslib "github.com/wgliang/metrics/metrics-lib"
)

func Module1(ms *metrics.Metrics) {
	m1 := make(map[string]interface{})
	m1["module1_counter"] = ms.RegMetric("module1_counter", metricslib.NewCounter())
	m1["module1_action"] = ms.RegMetric("module1_action", metricslib.NewFlow(50))
	for i := 0; i < 3; i++ {
		m1["module1_counter"].(metricslib.Counter).Inc(1)
		m1["module1_action"].(metricslib.Flow).RPush(` has been added to venuscron. `)
		// time.Sleep(3 * time.Second)
	}
}

func Module2(ms *metrics.Metrics) {
	m2 := make(map[string]interface{})
	m2["module2_counter"] = ms.RegMetric("module2_counter", metricslib.NewCounter())
	m2["module2_action"] = ms.RegMetric("module2_action", metricslib.NewFlow(50))
	for i := 0; i < 3; i++ {
		m2["module2_counter"].(metricslib.Counter).Inc(1)
		m2["module2_action"].(metricslib.Flow).RPush(` has been added to venuscron. `)
		// time.Sleep(3 * time.Second)
	}
}

func main() {
	ms := metrics.NewMetrics(&metrics.Options{
		Switcher: 1,
		Path:     "{static-files}",
		Addr:     "127.0.0.1:9090",
	})
	go Module1(ms)
	go Module2(ms)
	time.Sleep(3 * time.Second)

	for key, _ := range ms.Metrics {
		value, err := ms.Metrics2string(key)
		if err != nil {
			fmt.Println(err)
		}
		fmt.Println(key + " , " + value)
	}
}

Or..

see data from 127.0.0.1:9090/api/metrics/metrics/{action} , "action" is the name that you have register in modules.

Documentation

Overview

this is s struct for event-flow, and you can define it's size

Index

Constants

View Source
const TickDuration = 5 * time.Second

TickDuration defines the rate at which Tick() should get called for EWMA and other Tickable things that rely on EWMA like Meter & Timer.

Variables

View Source
var UseNilMetrics bool = false

Functions

func Collector

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

Collector the given metric under the given name. Returns a DuplicateMetric if a metric by the given name is already Collectored.

func Each

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

Call the given function for each Collectored metric.

func Get

func Get(name string) interface{}

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

func GetOrCollector

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

Gets an existing metric or creates and Collectors a new one. Threadsafe alternative to calling Get and Collector on failure.

func InitMetrics

func InitMetrics(me *Metrics)

init metrics-data colloctor

func MustCollector

func MustCollector(name string, i interface{})

Collector the given metric under the given name. Panics if a metric by the given name is already Collectored.

func RunHealthchecks

func RunHealthchecks()

Run all Collectored healthchecks.

func Size

func Size() int64

Get metrics number

func UnCollector

func UnCollector(name string)

UnCollector the metric with the given name.

Types

type Collectry

type Collectry interface {

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

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

	// Gets an existing metric or Collectors the given one.
	// The interface can be the metric to Collector if not found in Collectry,
	// or a function returning the metric for lazy instantiation.
	GetOrCollector(string, interface{}) interface{}

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

	// Run all Collectored healthchecks.
	RunHealthchecks()

	// UnCollector the metric with the given name.
	Uncollector(string)

	// UnCollector all metrics.  (Mostly for testing.)
	UncollectorAll()

	// Get metrics
	Values() interface{}

	// Get metrics number
	Size() int64
}

A Collectry 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 so as to encourage other structs to implement the Collectry API as appropriate.

var DefaultCollectry Collectry = NewCollectry()

func NewCollectry

func NewCollectry() Collectry

Create a new Collectry.

func NewPrefixedChildCollectry

func NewPrefixedChildCollectry(parent Collectry, prefix string) Collectry

func NewPrefixedCollectry

func NewPrefixedCollectry(prefix string) Collectry

type Counter

type Counter interface {
	// Clear the counter: set it to zero.
	Clear()

	// Return the current count.
	Count() int64

	// Decrement the counter by the given amount.
	Dec(amount int64) Counter

	// Increment the counter by the given amount.
	Inc(amount int64) Counter
}

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

func NewCounter

func NewCounter() Counter

Create a new counter.

type DuplicateMetric

type DuplicateMetric string

DuplicateMetric is the error returned by Collectry.Collector when a metric already exists. If you mean to Collector that metric you must first UnCollector the existing metric.

func (DuplicateMetric) Error

func (err DuplicateMetric) Error() string

type EWMA

type EWMA interface {
	// Return the moving average rate of events per second.
	Rate() float64

	// Tick the clock to update the moving average.
	Tick()

	// Add n uncounted events.
	Update(n int64)
}

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

func NewEWMA

func NewEWMA(alpha float64) EWMA

Create a new EWMA with the given alpha.

func NewEWMA1

func NewEWMA1() EWMA

Create a new EWMA with alpha set for a one-minute moving average.

func NewEWMA15

func NewEWMA15() EWMA

Create a new EWMA with alpha set for a fifteen-minute moving average.

func NewEWMA5

func NewEWMA5() EWMA

Create a new EWMA with alpha set for a five-minute moving average.

type Flow

type Flow interface {
	// Clear all flows.
	Clear()

	// Return the size of the flows, which is at most the reservoir size.
	Size() int64

	// Return all the values in the flow.
	Values() (values []string)

	// right pop and push operation
	RPop() (string, error)
	RPush(string)
	// left pop and push operation
	LPop() (string, error)
	LPush(string)
}

func NewFlow

func NewFlow(size int64) Flow

New a flow

type Gauge

type Gauge interface {
	// Update the gauge's value.
	Update(value int64)

	// Return the gauge's current value.
	Value() int64
}

Gauges hold an int64 value that can be set arbitrarily.

func NewGauge

func NewGauge() Gauge

Create a new gauge.

type GaugeFloat64

type GaugeFloat64 interface {
	// Update the gauge's value.
	Update(value float64)

	// Return the gauge's current value.
	Value() float64
}

Gauges hold an int64 value that can be set arbitrarily.

func NewGaugeFloat64

func NewGaugeFloat64() GaugeFloat64

Create a new gauge.

type Healthcheck

type Healthcheck interface {
	Check()
	Error() error
	Healthy()
	Unhealthy(error)
}

Healthchecks hold an error value describing an arbitrary up/down status.

func NewHealthcheck

func NewHealthcheck(f func(Healthcheck)) Healthcheck

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

type Histogram

type Histogram interface {
	// Clear the histogram.
	Clear()

	// Return the count of inputs since the histogram was last cleared.
	Count() int64

	// Return the sum of inputs since the histogram was last cleared.
	Sum() int64

	// Return the maximal value seen since the histogram was last cleared.
	Max() int64

	// Return the mean of all values seen since the histogram was last cleared.
	Mean() float64

	// Return the minimal value seen since the histogram was last cleared.
	Min() int64

	// Return an arbitrary percentile of all values seen since the histogram was
	// last cleared.
	Percentile(p float64) float64

	// Return a slice of arbitrary percentiles of all values seen since the
	// histogram was last cleared.
	Percentiles(ps []float64) []float64

	// Return the standard deviation of all values seen since the histogram was
	// last cleared.
	StdDev() float64

	// Update the histogram with a new value.
	Update(value int64)

	// Return the variance of all values seen since the histogram was last cleared.
	Variance() float64
}

Histograms calculate distribution statistics from an int64 value.

func NewHistogram

func NewHistogram(s Sample) Histogram

Create a new histogram with the given Sample. The initial values compare so that the first value will be both min and max and the variance is flagged for special treatment on its first iteration.

type Meter

type Meter interface {
	// Return the count of events seen.
	Count() int64

	// Mark the occurance of n events.
	Mark(n int64)

	// Tick the clock to update the moving average.
	Tick()

	// Return the meter's one-minute moving average rate of events.
	Rate1() float64

	// Return the meter's five-minute moving average rate of events.
	Rate5() float64

	// Return the meter's fifteen-minute moving average rate of events.
	Rate15() float64

	// Return the meter's mean rate of events.
	RateMean() float64
}

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

func NewMeter

func NewMeter() Meter

Create a new meter.

type Metrics

type Metrics struct {
	Metrics map[string]interface{}
	Path    string
	Addr    string
	// contains filtered or unexported fields
}

metrics-data struct

func NewMetrics

func NewMetrics(option *Options) *Metrics

func (*Metrics) Metrics2string

func (me *Metrics) Metrics2string(metricName string) (string, error)

func (*Metrics) MetricsResponse

func (me *Metrics) MetricsResponse(w http.ResponseWriter, req *http.Request)

Metrics数据解析响应

func (*Metrics) RegHandler

func (me *Metrics) RegHandler(mux *mux.Router)

register route

func (*Metrics) RegMetric

func (me *Metrics) RegMetric(name string, metric interface{}) interface{}

register Metrics

type Mstring

type Mstring interface {
	// Update the mstring's value.
	Update(value string)

	// Return the mstring's current value.
	Value() string
}

plains hold an int64 value that can be set arbitrarily.

func NewMString

func NewMString() Mstring

Create a new mstring.

type NilHealthcheck

type NilHealthcheck struct{}

NilHealthcheck is a no-op.

func (NilHealthcheck) Check

func (NilHealthcheck) Check()

Check is a no-op.

func (NilHealthcheck) Error

func (NilHealthcheck) Error() error

Error is a no-op.

func (NilHealthcheck) Healthy

func (NilHealthcheck) Healthy()

Healthy is a no-op.

func (NilHealthcheck) Unhealthy

func (NilHealthcheck) Unhealthy(error)

Unhealthy is a no-op.

type Options

type Options struct {
	Switcher int
	Path     string
	Addr     string
}

metrics-data options

type PrefixedCollectry

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

func (*PrefixedCollectry) Collector

func (r *PrefixedCollectry) Collector(name string, metric interface{}) error

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

func (*PrefixedCollectry) Each

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

Call the given function for each Collectored metric.

func (*PrefixedCollectry) Get

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

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

func (*PrefixedCollectry) GetOrCollector

func (r *PrefixedCollectry) GetOrCollector(name string, metric interface{}) interface{}

Gets an existing metric or Collectors the given one. The interface can be the metric to Collector if not found in Collectry, or a function returning the metric for lazy instantiation.

func (*PrefixedCollectry) RunHealthchecks

func (r *PrefixedCollectry) RunHealthchecks()

Run all Collectored healthchecks.

func (*PrefixedCollectry) Size

func (r *PrefixedCollectry) Size() int64

size of my metrics

func (*PrefixedCollectry) Uncollector

func (r *PrefixedCollectry) Uncollector(name string)

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

func (*PrefixedCollectry) UncollectorAll

func (r *PrefixedCollectry) UncollectorAll()

UnCollector all metrics. (Mostly for testing.)

func (*PrefixedCollectry) Values

func (r *PrefixedCollectry) Values() interface{}

type Sample

type Sample interface {
	// Clear all samples.
	Clear()

	// Return the size of the sample, which is at most the reservoir size.
	Size() int

	// Update the sample with a new value.
	Update(value int64)

	// Return all the values in the sample.
	Values() []int64
}

Samples maintain a statistically-significant selection of values from a stream.

func NewExpDecaySample

func NewExpDecaySample(reservoirSize int, alpha float64) Sample

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

func NewUniformSample

func NewUniformSample(reservoirSize int) Sample

Create a new uniform sample with the given reservoir size.

type StandardCollectry

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

The standard implementation of a Collectry is a mutex-protected map of names to metrics.

func (*StandardCollectry) Collector

func (r *StandardCollectry) Collector(name string, i interface{}) error

Collector the given metric under the given name. Returns a DuplicateMetric if a metric by the given name is already Collectored.

func (*StandardCollectry) Each

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

Call the given function for each Collectored metric.

func (*StandardCollectry) Get

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

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

func (*StandardCollectry) GetOrCollector

func (r *StandardCollectry) GetOrCollector(name string, i interface{}) interface{}

Gets an existing metric or creates and Collectors a new one. Threadsafe alternative to calling Get and Collector on failure. The interface can be the metric to Collector if not found in Collectry, or a function returning the metric for lazy instantiation.

func (*StandardCollectry) RunHealthchecks

func (r *StandardCollectry) RunHealthchecks()

Run all Collectored healthchecks.

func (*StandardCollectry) Size

func (r *StandardCollectry) Size() int64

size of my metrics

func (*StandardCollectry) Uncollector

func (r *StandardCollectry) Uncollector(name string)

UnCollector the metric with the given name.

func (*StandardCollectry) UncollectorAll

func (r *StandardCollectry) UncollectorAll()

UnCollector all metrics. (Mostly for testing.)

func (*StandardCollectry) Values

func (r *StandardCollectry) Values() interface{}

type StandardHealthcheck

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

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

func (*StandardHealthcheck) Check

func (h *StandardHealthcheck) Check()

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

func (*StandardHealthcheck) Error

func (h *StandardHealthcheck) Error() error

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

func (*StandardHealthcheck) Healthy

func (h *StandardHealthcheck) Healthy()

Healthy marks the healthcheck as healthy.

func (*StandardHealthcheck) Unhealthy

func (h *StandardHealthcheck) Unhealthy(err error)

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

type Tickable

type Tickable interface {
	// Tick the clock to update the moving average.
	Tick()
}

Tickable defines the interface implemented by poetry that need to Tick.

type Timer

type Timer interface {
	// Return the count of inputs.
	Count() int64

	// Return the maximal value seen.
	Max() int64

	// Return the mean of all values seen.
	Mean() float64

	// Return the minimal value seen.
	Min() int64

	// Return an arbitrary percentile of all values seen.
	Percentile(p float64) float64

	// Return a slice of arbitrary percentiles of all values seen.
	Percentiles(ps []float64) []float64

	// Return the meter's one-minute moving average rate of events.
	Rate1() float64

	// Return the meter's five-minute moving average rate of events.
	Rate5() float64

	// Return the meter's fifteen-minute moving average rate of events.
	Rate15() float64

	// Return the meter's mean rate of events.
	RateMean() float64

	// Return the standard deviation of all values seen.
	StdDev() float64

	// Start captures the current time and returns a value which implements Stop
	// to log the elapsed time. It should be used like:
	//
	//     defer timer.Start().Stop()
	Start() interface {
		Stop()
	}

	// Record the duration of an event.
	Update(d time.Duration)

	// Record the duration of an event that started at a time and ends now.
	UpdateSince(t time.Time)

	// Tick the clock to update the moving average.
	Tick()
}

Timers capture the duration and rate of events.

func NewCustomTimer

func NewCustomTimer(h Histogram, m Meter) Timer

Create a new timer with the given Histogram and Meter.

func NewTimer

func NewTimer() Timer

Create a new timer with a standard histogram and meter. The histogram will use an exponentially-decaying sample with the same reservoir size and alpha as UNIX load averages.

Jump to

Keyboard shortcuts

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