stats

package module
v4.8.0 Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2025 License: MIT Imports: 8 Imported by: 22

README

stats CircleCI Go Report Card GoDoc

A Go package for abstracting stats collection.

Installation

go get github.com/segmentio/stats/v4

Migration to v4

Version 4 of the stats package introduced a new way of producing metrics based on defining struct types with tags on certain fields that define how to interpret the values. This approach allows for much more efficient metric production as it allows the program to do quick assignments and increments of the struct fields to set the values to be reported, and submit them all with one call to the stats engine, resulting in orders of magnitude faster metrics production. Here's an example:

type funcMetrics struct {
    calls struct {
        count int           `metric:"count" type:"counter"`
        time  time.Duration `metric:"time"  type:"histogram"`
    } `metric:"func.calls"`
}
t := time.Now()
f()
callTime := time.Since(t)

m := &funcMetrics{}
m.calls.count = 1
m.calls.time = callTime

// Equivalent to:
//
//   stats.Incr("func.calls.count")
//   stats.Observe("func.calls.time", callTime)
//
stats.Report(m)

To avoid greatly increasing the complexity of the codebase some old APIs were removed in favor of this new approach, other were transformed to provide more flexibility and leverage new features.

The stats package used to only support float values, metrics can now be of various numeric types (see stats.MakeMeasure for a detailed description), therefore functions like stats.Add now accept an interface{} value instead of float64. stats.ObserveDuration was also removed since this new approach makes it obsolete (durations can be passed to stats.Observe directly).

The stats.Engine type used to be configured through a configuration object passed to its constructor function, and a few methods (like Register) were exposed to mutate engine instances. This required synchronization in order to be safe to modify an engine from multiple goroutines. We haven't had a use case for modifying an engine after creating it so the constraint on being thread-safe were lifted and the fields exposed on the stats.Engine struct type directly to communicate that they are unsafe to modify concurrently. The helper methods remain tho to make migration of existing code smoother.

Histogram buckets (mostly used for the prometheus client) are now defined by default on the stats.Buckets global variable instead of within the engine. This decoupling was made to avoid paying the cost of doing histogram bucket lookups when producing metrics to backends that don't use them (like datadog or influxdb for example).

The data model also changed a little. Handlers for metrics produced by an engine now accept a list of measures instead of single metrics, each measure being made of a name, a set of fields, and tags to apply to each of those fields. This allows a more generic and more efficient approach to metric production, better fits the influxdb data model, while still being compatible with other clients (datadog, prometheus, ...). A single timeseries is usually identified by the combination of the measure name, a field name and value, and the set of tags set on that measure. Refer to each client for a details about how measures are translated to individual metrics.

Note that no changes were made to the end metrics being produced by each sub-package (httpstats, procstats, ...). This was important as we must keep the behavior backward compatible since making changes here would implicitly break dashboards or monitors set on the various metric collection systems that this package supports, potentially causing production issues.

If you find a bug or an API is not available anymore but deserves to be ported feel free to open an issue.

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/v4"
    "github.com/segmentio/stats/v4/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/v4"
    "github.com/segmentio/stats/v4/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"})

    // ...
}
Flushing Metrics

Metrics are stored in a buffer, which will be flushed when it reaches its capacity. For most use-cases, you do not need to explicitly send out metrics.

If you're producing metrics only very infrequently, you may have metrics that stay in the buffer and never get sent out. In that case, you can manually trigger stats flushes like so:

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

    // Force a metrics flush every second
    go func() {
      for range time.Tick(time.Second) {
        stats.Flush()
      }
    }()

    // ...
}

Monitoring

Processes

🚧 Go metrics reported with the procstats package were previously tagged with a version label that reported the Go runtime version. This label was renamed to go_version in v4.6.0.

The github.com/segmentio/stats/procstats package exposes an API for creating a statistics collector on local processes. Statistics are collected for the current process and metrics including Goroutine count and memory usage are reported.

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

package main

import (
    "github.com/segmentio/stats/v4/datadog"
    "github.com/segmentio/stats/v4/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()

    // ...
}

One can also collect additional statistics on resource delays, such as CPU delays, block I/O delays, and paging/swapping delays. This capability is currently only available on Linux, and can be optionally enabled as follows:

func main() {
    // As above...

    // Start a new collector for the current process, reporting Go metrics.
    c := procstats.StartCollector(procstats.NewDelayMetrics())
    defer c.Close()
}
HTTP Servers

The github.com/segmentio/stats/httpstats package exposes a decorator of http.Handler that automatically adds metric collection 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/v4/datadog"
    "github.com/segmentio/stats/v4/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 example of how to use the decorator:

package main

import (
    "net/http"

    "github.com/segmentio/stats/v4/datadog"
    "github.com/segmentio/stats/v4/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/v4/datadog"
    "github.com/segmentio/stats/v4/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)

    // ...
}
Redis

The github.com/segmentio/stats/redisstats package exposes:

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

package main

import (
    "github.com/segmentio/redis-go"
    "github.com/segmentio/stats/v4/redisstats"
)

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

    client := redis.Client{
        Addr:      "127.0.0.1:6379",
        Transport: redisstats.NewTransport(&redis.Transport{}),
    }

    // ...
}

And on the server side:

package main

import (
    "github.com/segmentio/redis-go"
    "github.com/segmentio/stats/v4/redisstats"
)

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

    handler := redis.HandlerFunc(func(res redis.ResponseWriter, req *redis.Request) {
      // Implement handler function here
    })

    server := redis.Server{
        Handler: redisstats.NewHandler(&handler),
    }

    server.ListenAndServe()

    // ...
}

Documentation

Overview

Package stats exposes tools for producing application performance metrics to various metric collection backends.

Index

Constants

View Source
const (
	Counter   = statsv5.Counter
	Gauge     = statsv5.Gauge
	Histogram = statsv5.Histogram
)

FieldType constants (see same-named constants in stats/v5).

View Source
const (
	Null     = statsv5.Null
	Bool     = statsv5.Bool
	Int      = statsv5.Int
	Uint     = statsv5.Uint
	Float    = statsv5.Float
	Duration = statsv5.Duration
	Invalid  = statsv5.Invalid
)

Type constants. See same-named constants in stats/v5.

Variables

View Source
var Buckets = HistogramBuckets{}

Buckets is a registry where histogram buckets are placed. Some metric collection backends need to have histogram buckets defined by the program (like Prometheus), a common pattern is to use the init function of a package to register buckets for the various histograms that it produces.

View Source
var DefaultEngine = statsv5.DefaultEngine

DefaultEngine behaves like stats/v5.DefaultEngine.

View Source
var Discard = statsv5.Discard

Discard behaves like stats/v5.Discard.

Functions

func Add

func Add(name string, value interface{}, tags ...Tag)

Add behaves like stats/v5.Add.

func AddAt

func AddAt(time time.Time, name string, value interface{}, tags ...Tag)

AddAt behaves like stats/v5.AddAt.

func ContextAddTags

func ContextAddTags(ctx context.Context, tags ...Tag) bool

ContextAddTags adds the given tags to the given context, if the tags have been set on any of the ancestor contexts. ContextAddTags returns true if tags were successfully appended to the context, and false otherwise.

The proper way to set tags on a context if you don't know whether or not tags already exist on the context is to first call ContextAddTags, and if that returns false, then call ContextWithTags instead.

func ContextWithTags

func ContextWithTags(ctx context.Context, tags ...Tag) context.Context

ContextWithTags returns a new child context with the given tags. If the parent context already has tags set on it, they are _not_ propegated into the context children.

func Flush

func Flush()

Flush behaves like stats/v5.Flush.

func Incr

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

Incr behaves like stats/v5.Incr.

func IncrAt

func IncrAt(time time.Time, name string, tags ...Tag)

IncrAt behaves like stats/v5.IncrAt.

func Observe

func Observe(name string, value interface{}, tags ...Tag)

Observe behaves like stats/v5.Observe.

func ObserveAt

func ObserveAt(time time.Time, name string, value interface{}, tags ...Tag)

ObserveAt behaves like stats/v5.ObserveAt.

func Register

func Register(handler Handler)

Register behaves like stats/v5.Register.

func Report

func Report(metrics interface{}, tags ...Tag)

Report behaves like stats/v5.Report.

func ReportAt

func ReportAt(time time.Time, metrics interface{}, tags ...Tag)

ReportAt behaves like stats/v5.ReportAt.

func Set

func Set(name string, value interface{}, tags ...Tag)

Set behaves like stats/v5.Set.

func SetAt

func SetAt(time time.Time, name string, value interface{}, tags ...Tag)

SetAt behaves like stats/v5.SetAt.

func TagsAreSorted

func TagsAreSorted(tags []Tag) bool

TagsAreSorted behaves like stats/v5.TagsAreSorted.

Types

type Buffer

type Buffer struct {
	// Target size of the memory buffer where metrics are serialized.
	//
	// If left to zero, a size of 1024 bytes is used as default (this is low,
	// you should set this value).
	//
	// Note that if the buffer size is small, the program may generate metrics
	// that don't fit into the configured buffer size. In that case the buffer
	// will still pass the serialized byte slice to its Serializer to leave the
	// decision of accepting or rejecting the metrics.
	BufferSize int

	// Size of the internal buffer pool, this controls how well the buffer
	// performs in highly concurrent environments. If unset, 2 x GOMAXPROCS
	// is used as a default value.
	BufferPoolSize int

	// The Serializer used to write the measures.
	//
	// This field cannot be nil.
	Serializer Serializer
	// contains filtered or unexported fields
}

Buffer is the implementation of a measure handler which uses a Serializer to serialize the metric into a memory buffer and write them once the buffer has reached a target size.

func (*Buffer) Flush

func (b *Buffer) Flush()

Flush satisfies the Flusher interface.

func (*Buffer) HandleMeasures

func (b *Buffer) HandleMeasures(time time.Time, measures ...Measure)

HandleMeasures satisfies the Handler interface.

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.

Note: Clock times are reported to datadog in seconds. See `stats/datadog/measure.go`.

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 time the clock was created at.

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 time the clock was created at.

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

type Engine

type Engine = statsv5.Engine

Engine behaves like stats/v5.Engine.

func NewEngine

func NewEngine(prefix string, handler Handler, tags ...Tag) *Engine

NewEngine behaves like stats/v5.NewEngine.

func WithPrefix

func WithPrefix(prefix string, tags ...Tag) *Engine

WithPrefix behaves like stats/v5.WithPrefix.

func WithTags

func WithTags(tags ...Tag) *Engine

WithTags behaves like stats/v5.WithTags.

type Field

type Field = statsv5.Field

Field behaves like stats/v5.Field.

func MakeField

func MakeField(name string, value interface{}, ftype FieldType) Field

MakeField behaves like stats/v5.MakeField.

type FieldType

type FieldType = statsv5.FieldType

FieldType behaves like stats/v5.FieldType.

type Flusher

type Flusher = statsv5.Flusher

Flusher behaves like stats/v5.Flusher.

type Handler

type Handler = statsv5.Handler

Handler behaves like stats/v5.Handler.

func FilteredHandler added in v4.6.4

func FilteredHandler(h Handler, filter func([]Measure) []Measure) Handler

FilteredHandler behaves like stats/v5.FilteredHandler.

func MultiHandler

func MultiHandler(handlers ...Handler) Handler

MultiHandler behaves like stats/v5.MultiHandler.

type HandlerFunc

type HandlerFunc = statsv5.HandlerFunc

HandlerFunc behaves like stats/v5.HandlerFunc.

type HistogramBuckets

type HistogramBuckets map[Key][]Value

HistogramBuckets is a map type storing histogram buckets.

func (HistogramBuckets) Set

func (b HistogramBuckets) Set(key string, buckets ...interface{})

Set sets a set of buckets to the given list of sorted values.

type Key

type Key struct {
	Measure string
	Field   string
}

Key is a type used to uniquely identify metrics.

type Measure

type Measure = statsv5.Measure

Measure behaves like stats/v5.Measure.

func MakeMeasures

func MakeMeasures(prefix string, value interface{}, tags ...Tag) []Measure

MakeMeasures behaves like stats/v5.MakeMeasures.

type Serializer

type Serializer interface {
	io.Writer

	// Appends the serialized representation of the given measures into b.
	//
	// The method must not retain any of the arguments.
	AppendMeasures(b []byte, time time.Time, measures ...Measure) []byte
}

The Serializer interface is used to abstract the logic of serializing measures.

type Tag

type Tag = statsv5.Tag

Tag behaves like stats/v5.Tag.

func ContextTags

func ContextTags(ctx context.Context) []Tag

ContextTags returns a copy of the tags on the context if they exist and nil if they don't exist.

func M

func M(m map[string]string) []Tag

M behaves like stats/v5.M.

func SortTags

func SortTags(tags []Tag) []Tag

SortTags behaves like stats/v5.SortTags.

func T

func T(k, v string) Tag

T behaves like stats/v5.T.

type Type

type Type = statsv5.Type

Type behaves like stats/v5.Type.

type Value

type Value = statsv5.Value

Value behaves like stats/v5.Value.

func MustValueOf added in v4.5.3

func MustValueOf(v Value) Value

MustValueOf behaves like stats/v5.MustValueOf.

func ValueOf

func ValueOf(v interface{}) Value

ValueOf behaves like stats/v5.ValueOf.

Jump to

Keyboard shortcuts

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