stats

package module
v3.0.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2017 License: MIT Imports: 4 Imported by: 0

README

stats CircleCI Go Report Card GoDoc

A Go package for abstracting stats collection.

Installation

go get github.com/segmentio/stats

Quick Start

Engine

A core concept of the stats package is the Engine. Every program importing the package gets a default engine where all metrics produced are aggregated.
The program then has to instantiate clients that will consume from the engine at regular time intervals and report the state of the engine to metrics collection platforms.

package main

import (
    "github.com/segmentio/stats"
    "github.com/segmentio/stats/datadog"
)

func main() {
    // Creates a new datadog client publishing metrics to localhost:8125
    dd := datadog.NewClient("localhost:8125")

    // Register the client so it receives metrics from the default engine.
    stats.Register(dd)

    // Flush the default stats engine on return to ensure all buffered
    // metrics are sent to the dogstatsd server.
    defer stats.Flush()

    // That's it! Metrics produced by the application will now be reported!
    // ...
}
Metrics
package main

import (
    "github.com/segmentio/stats"
    "github.com/segmentio/stats/datadog"
)

func main() {
    stats.Register(datadog.NewClient("localhost:8125"))
    defer stats.Flush()

    // Increment counters.
    stats.Incr("user.login")
    defer stats.Incr("user.logout")

    // Set a tag on a counter increment.
    stats.Incr("user.login", stats.Tag{"user", "luke"})

    // ...
}

Monitoring

Processes

The github.com/segmentio/stats/httpstats exposes an API for creating stats collector on local processes. Stats are collected for current the process and metrics like goroutines count or memory usage are reported.

Here's an example of how to use the collector:

package main

import (
    "github.com/segmentio/stats/datadog"
    "github.com/segmentio/stats/procstats"
)


func main() {
     stats.Register(datadog.NewClient("localhost:8125"))
     defer stats.Flush()

    // Start a new collector for the current process, reporting Go metrics.
    c := procstats.StartCollector(procstats.NewGoMetrics())

    // Gracefully stops stats collection.
    defer c.Close()

    // ...
}
HTTP Servers

The github.com/segmentio/stats/httpstats package exposes a decorator of http.Handler that automatically adds metric colleciton to a HTTP handler, reporting things like request processing time, error counters, header and body sizes...

Here's an example of how to use the decorator:

package main

import (
    "net/http"

    "github.com/segmentio/stats/datadog"
    "github.com/segmentio/stats/httpstats"
)

func main() {
     stats.Register(datadog.NewClient("localhost:8125"))
     defer stats.Flush()

    // ...

    http.ListenAndServe(":8080", httpstats.NewHandler(
        http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
            // This HTTP handler is automatically reporting metrics for all
            // requests it handles.
            // ...
        }),
    ))
}
HTTP Clients

The github.com/segmentio/stats/httpstats package exposes a decorator of http.RoundTripper which collects and reports metrics for client requests the same way it's done on the server side.

Here's an exmaple of how to use the decorator:

package main

import (
    "net/http"

    "github.com/segmentio/stats/datadog"
    "github.com/segmentio/stats/httpstats"
)

func main() {
     stats.Register(datadog.NewClient("localhost:8125"))
     defer stats.Flush()

    // Make a new HTTP client with a transport that will report HTTP metrics,
    // set the engine to nil to use the default.
    httpc := &http.Client{
        Transport: httpstats.NewTransport(
            &http.Transport{},
        ),
    }

    // ...
}

You can also modify the default HTTP client to automatically get metrics for all packages using it, this is very convinient to get insights into dependencies.

package main

import (
    "net/http"

    "github.com/segmentio/stats/datadog"
    "github.com/segmentio/stats/httpstats"
)

func main() {
     stats.Register(datadog.NewClient("localhost:8125"))
     defer stats.Flush()

    // Wraps the default HTTP client's transport.
    http.DefaultClient.Transport = httpstats.NewTransport(http.DefaultClient.Transport)

    // ...
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultEngine is the engine used by global metrics.
	//
	// Programs that need to change the default engine should do before creating
	// any metrics handlers or producers.
	DefaultEngine = NewEngine(progname())
)

Functions

func Add

func Add(name string, value float64, tags ...Tag)

Add adds value to the metric identified by name and tags, a new counter is created in the default engine if none existed.

func Flush

func Flush()

Flush flushes all metrics on the default engine.

func Incr

func Incr(name string, tags ...Tag)

Incr increments by one the metric identified by name and tags, a new counter is created in the default engine if none existed.

func Observe

func Observe(name string, value float64, tags ...Tag)

Observe reports a value for the metric identified by name and tags, a new histogram is created in the default engine if none existed.

func ObserveDuration

func ObserveDuration(name string, value time.Duration, tags ...Tag)

ObserveDuration reports a duration value of the metric identified by name and tags, a new timer is created in the default engine if none existed.

func Register

func Register(handler Handler)

Register adds handler to the default engine.

func Set

func Set(name string, value float64, tags ...Tag)

Set sets the value of the metric identified by name and tags, a new gauge is created in the default engine if none existed.

Types

type Clock

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

The Clock type can be used to report statistics on durations.

Clocks are useful to measure the duration taken by sequential execution steps and therefore aren't safe to be used concurrently by multiple goroutines.

func Time

func Time(name string, start time.Time, tags ...Tag) *Clock

Time returns a clock that produces metrics with name and tags and can be used to report durations.

func (*Clock) Name

func (c *Clock) Name() string

Name returns the name of the clock.

func (*Clock) Stamp

func (c *Clock) Stamp(name string)

Stamp reports the time difference between now and the last time the method was called (or since the clock was created).

The metric produced by this method call will have a "stamp" tag set to name.

func (*Clock) StampAt

func (c *Clock) StampAt(name string, now time.Time)

StampAt reports the time difference between now and the last time the method was called (or since the clock was created).

The metric produced by this method call will have a "stamp" tag set to name.

func (*Clock) Stop

func (c *Clock) Stop()

Stop reports the time difference between now and the last time the Stamp method was called (or since the clock was created).

The metric produced by this method call will have a "stamp" tag set to "total".

func (*Clock) StopAt

func (c *Clock) StopAt(now time.Time)

StopAt reports the time difference between now and the last time the Stamp method was called (or since the clock was created).

The metric produced by this method call will have a "stamp" tag set to "total".

func (*Clock) Tags

func (c *Clock) Tags() []Tag

Tags returns the list of tags set on the clock.

The method returns a reference to the clock's internal tag slice, it does not make a copy. It's expected that the program will treat this value as a read-only list and won't modify its content.

func (*Clock) WithTags

func (c *Clock) WithTags(tags ...Tag) *Clock

WithTags returns a copy of the clock, potentially setting tags on the returned object.

type Counter

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

A Counter represent a metric that is monotonically increasing.

func C

func C(name string, tags ...Tag) *Counter

C returns a new counter that produces a metric with name and tags on the default engine.

func (*Counter) Add

func (c *Counter) Add(value float64)

Add adds a value to the counter.

Note that most data collection systems expect counters to be monotonically increasing so the program should not call this method with negative values.

func (*Counter) Incr

func (c *Counter) Incr()

Incr increments the counter by a value of 1.

func (*Counter) Name

func (c *Counter) Name() string

Name returns the name of the counter.

func (*Counter) Set

func (c *Counter) Set(value float64)

Set sets the value of the counter.

Note that most data collection systems expect counters to be monotonically increasing. Calling Set may break this contract, it is the responsibility of the application to make sure it's not lowering the counter value.

This method is useful for reporting values of counters that aren't managed by the application itself, like CPU ticks for example.

func (*Counter) Tags

func (c *Counter) Tags() []Tag

Tags returns the list of tags set on the counter.

The method returns a reference to the counter's internal tag slice, it does not make a copy. It's expected that the program will treat this value as a read-only list and won't modify its content.

func (*Counter) Value

func (c *Counter) Value() float64

Value returns the current value of the counter.

func (*Counter) WithTags

func (c *Counter) WithTags(tags ...Tag) *Counter

WithTags returns a copy of the counter, potentially setting tags on the returned object.

The internal value of the returned counter is set to zero.

type Engine

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

The Engine is the central system where metrics are reported and dispatched to handlers in charge of publishing them to various metrics platforms.

Most applications don't need to create a stats engine and can simply use DefaultEngine, which is implicitly used by all top-level functions of the package.

func NewEngine

func NewEngine(name string, tags ...Tag) *Engine

NewEngine creates and returns an engine with tag and tags.

func (*Engine) Add

func (eng *Engine) Add(name string, value float64, tags ...Tag)

Add adds value to the counter with name and tags on eng.

func (*Engine) Counter

func (eng *Engine) Counter(name string, tags ...Tag) *Counter

Counter creates a new counter producing a metric with name and tag on eng.

func (*Engine) Flush

func (eng *Engine) Flush()

Flush flushes all handlers of eng that implement the Flusher interface.

func (*Engine) Gauge

func (eng *Engine) Gauge(name string, tags ...Tag) *Gauge

Gauge creates a new gauge producing a metric with name and tag on eng.

func (*Engine) Handlers

func (eng *Engine) Handlers() []Handler

Handlers returns a slice containing the handlers currently set on the engine.

func (*Engine) Histogram

func (eng *Engine) Histogram(name string, tags ...Tag) *Histogram

Histogram creates a new hitsogram producing a metric with name and tag on eng.

func (*Engine) Incr

func (eng *Engine) Incr(name string, tags ...Tag)

Incr increments by 1 the counter with name and tags on eng.

func (*Engine) Name

func (eng *Engine) Name() string

Name returns the name of the engine.

func (*Engine) Observe

func (eng *Engine) Observe(name string, value float64, tags ...Tag)

Observe reports a value on the histogram with name and tags on eng.

func (*Engine) ObserveDuration

func (eng *Engine) ObserveDuration(name string, value time.Duration, tags ...Tag)

ObserveDuration reports a duration in seconds to the histogram with name and tags on eng.

func (*Engine) Register

func (eng *Engine) Register(handler Handler)

Register adds handler to eng.

To prevent any deadlock from happening this method should never be called from the handler's HandleMetric method.

func (*Engine) Set

func (eng *Engine) Set(name string, value float64, tags ...Tag)

Set sets the gauge with name and tags on eng to value.

func (*Engine) Tags

func (eng *Engine) Tags() []Tag

Tags returns a slice containing the tags set on the engine.

func (*Engine) Timer

func (eng *Engine) Timer(name string, tags ...Tag) *Timer

Timer creates a new timer producing metrics with name and tag on eng.

func (*Engine) WithTags

func (eng *Engine) WithTags(tags ...Tag) *Engine

WithTags creates a new engine which inherits the properties and handlers, potentially adding tags to the returned engine.

type Flusher

type Flusher interface {
	// Flush is called when the object should flush out all data it has cached
	// or buffered internally.
	Flush()
}

Flusher is an interface that may be implemented by metric handlers that do buffering or caching of the metrics they receive.

type Gauge

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

A Gauge represent a metric that reports a single value.

func G

func G(name string, tags ...Tag) *Gauge

G returns a new gauge that produces a metric with name and tags on the default engine.

func (*Gauge) Add

func (g *Gauge) Add(value float64)

Add adds a value to the gauge.

func (*Gauge) Decr

func (g *Gauge) Decr()

Decr decrements the gauge by a value of 1.

func (*Gauge) Incr

func (g *Gauge) Incr()

Incr increments the gauge by a value of 1.

func (*Gauge) Name

func (g *Gauge) Name() string

Name returns the name of the gauge.

func (*Gauge) Set

func (g *Gauge) Set(value float64)

Set sets the gauge to value.

func (*Gauge) Tags

func (g *Gauge) Tags() []Tag

Tags returns the list of tags set on the gauge.

The method returns a reference to the gauge's internal tag slice, it does not make a copy. It's expected that the program will treat this value as a read-only list and won't modify its content.

func (*Gauge) Value

func (g *Gauge) Value() float64

Value returns the current value of the gauge.

func (*Gauge) WithTags

func (g *Gauge) WithTags(tags ...Tag) *Gauge

WithTags returns a copy of the gauge, potentially setting tags on the returned object.

The internal value of the returned gauge is set to zero.

type Handler

type Handler interface {
	// HandleMetric is called to report metrics produced by the program.
	//
	// The handler does not have ownership of the metric object it receives, it
	// must not retain the object or any of its field.
	HandleMetric(*Metric)
}

Handler is an interface implemented by types that receive metrics and expose them to diverse platforms.

Handlers are usually not used directly, instead they are hooked to an engine which provides a higher-level abstraction to generate and publish metrics.

type HandlerFunc

type HandlerFunc func(*Metric)

HandlerFunc makes it possible for simple functions to be used as metric handlers.

func (HandlerFunc) HandleMetric

func (f HandlerFunc) HandleMetric(m *Metric)

HandleMetric calls f.

type Histogram

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

A Histogram represent a metric that reports a distribution of observed values.

func H

func H(name string, tags ...Tag) *Histogram

H returns a new histogram that produces a metric with name and tags on the default engine.

func (*Histogram) Name

func (h *Histogram) Name() string

Name returns the name of the histogram.

func (*Histogram) Observe

func (h *Histogram) Observe(value float64)

Observe reports a value observed by the histogram.

func (*Histogram) Tags

func (h *Histogram) Tags() []Tag

Tags returns the list of tags set on the histogram.

The method returns a reference to the histogram's internal tag slice, it does not make a copy. It's expected that the program will treat this value as a read-only list and won't modify its content.

func (*Histogram) WithTags

func (h *Histogram) WithTags(tags ...Tag) *Histogram

WithTags returns a copy of the histogram, potentially setting tags on the returned object.

type Metric

type Metric struct {
	// Type is a constant representing the type of the metric, which is one of
	// the constants defined by the MetricType enumeration.
	Type MetricType

	// Namespace in which the metric was generated.
	Namespace string

	// Name is the name of the metric as defined by the program.
	Name string

	// Tags is the list of tags set on the metric.
	Tags []Tag

	// Value is the value reported by the metric, for counters this is the value
	// by which the counter is incremented.
	Value float64

	// Time is unused for now, reserved for future extensions.
	Time time.Time
}

Metric is a universal representation of the state of a metric.

No operations are available on this data type, instead it carries the state of a metric a single metric when querying the state of a stats engine.

type MetricType

type MetricType int

MetricType is an enumeration representing the type of a metric.

const (
	// CounterType is the constant representing counter metrics.
	CounterType MetricType = iota

	// GaugeType is the constant representing gauge metrics.
	GaugeType

	// HistogramType is the constant representing histogram metrics.
	HistogramType
)

type Tag

type Tag struct {
	Name  string
	Value string
}

Tag represents a single tag that can be set on a metric.

type Timer

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

A Timer is a special case for a histogram that reports durations.

func T

func T(name string, tags ...Tag) *Timer

T returns a new timer that produces a metric with name and tags on the default engine.

func (*Timer) Name

func (t *Timer) Name() string

Name returns the name of the timer.

func (*Timer) Start

func (t *Timer) Start() *Clock

Start the timer, returning a clock object that should be used to publish the timer metrics.

func (*Timer) StartAt

func (t *Timer) StartAt(now time.Time) *Clock

StartAt the timer with a predefined start time, returning a clock object that should be used to publish the timer metrics.

func (*Timer) Tags

func (t *Timer) Tags() []Tag

Tags returns the list of tags set on the timer.

The method returns a reference to the timer's internal tag slice, it does not make a copy. It's expected that the program will treat this value as a read-only list and won't modify its content.

func (*Timer) WithTags

func (t *Timer) WithTags(tags ...Tag) *Timer

WithTags returns a copy of the timer, potentially setting tags on the returned object.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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