Categorygithub.com/uber-go/tally/v4
modulepackage
4.1.16
Repository: https://github.com/uber-go/tally.git
Documentation: pkg.go.dev

# README

:heavy_check_mark: tally GoDoc Build Status Coverage Status

Fast, buffered, hierarchical stats collection in Go.

Installation

go get -u github.com/uber-go/tally

Abstract

Tally provides a common interface for emitting metrics, while letting you not worry about the velocity of metrics emission.

By default it buffers counters, gauges and histograms at a specified interval but does not buffer timer values. This is primarily so timer values can have all their values sampled if desired and if not they can be sampled as summaries or histograms independently by a reporter.

Structure

  • Scope: Keeps track of metrics, and their common metadata.
  • Metrics: Counters, Gauges, Timers and Histograms.
  • Reporter: Implemented by you. Accepts aggregated values from the scope. Forwards the aggregated values to your metrics ingestion pipeline.
    • The reporters already available listed alphabetically are:
      • github.com/uber-go/tally/m3: Report m3 metrics, timers are not sampled and forwarded directly.
      • github.com/uber-go/tally/multi: Report to multiple reporters, you can multi-write metrics to other reporters simply.
      • github.com/uber-go/tally/prometheus: Report prometheus metrics, timers by default are made summaries with an option to make them histograms instead.
      • github.com/uber-go/tally/statsd: Report statsd metrics, no support for tags.

Basics

  • Scopes created with tally provide race-safe registration and use of all metric types Counter, Gauge, Timer, Histogram.
  • NewRootScope(...) returns a Scope and io.Closer, the second return value is used to stop the scope's goroutine reporting values from the scope to it's reporter. This is to reduce the footprint of Scope from the public API for those implementing it themselves to use in Go packages that take a tally Scope.

Acquire a Scope

reporter = NewMyStatsReporter()  // Implement as you will
tags := map[string]string{
	"dc": "east-1",
	"type": "master",
}
reportEvery := time.Second

scope := tally.NewRootScope(tally.ScopeOptions{
	Tags: tags,
	Reporter: reporter,
}, reportEvery)

Get/Create a metric, use it

// Get a counter, increment a counter
reqCounter := scope.Counter("requests")  // cache me
reqCounter.Inc(1)

queueGauge := scope.Gauge("queue_length")  // cache me
queueGauge.Update(42)

Report your metrics

Use the inbuilt statsd reporter:

import (
	"io"
	"github.com/cactus/go-statsd-client/v5/statsd"
	"github.com/uber-go/tally"
	tallystatsd "github.com/uber-go/tally/statsd"
	// ...
)

func newScope() (tally.Scope, io.Closer) {
	statter, _ := statsd.NewBufferedClient("127.0.0.1:8125",
		"stats", 100*time.Millisecond, 1440)

	reporter := tallystatsd.NewReporter(statter, tallystatsd.Options{
		SampleRate: 1.0,
	})

	scope, closer := tally.NewRootScope(tally.ScopeOptions{
		Prefix:   "my-service",
		Tags:     map[string]string{},
		Reporter: reporter,
	}, time.Second)

	return scope, closer
}

Implement your own reporter using the StatsReporter interface:


// BaseStatsReporter implements the shared reporter methods.
type BaseStatsReporter interface {
	Capabilities() Capabilities
	Flush()
}

// StatsReporter is a backend for Scopes to report metrics to.
type StatsReporter interface {
	BaseStatsReporter

	// ReportCounter reports a counter value
	ReportCounter(
		name string,
		tags map[string]string,
		value int64,
	)

	// ReportGauge reports a gauge value
	ReportGauge(
		name string,
		tags map[string]string,
		value float64,
	)

	// ReportTimer reports a timer value
	ReportTimer(
		name string,
		tags map[string]string,
		interval time.Duration,
	)

	// ReportHistogramValueSamples reports histogram samples for a bucket
	ReportHistogramValueSamples(
		name string,
		tags map[string]string,
		buckets Buckets,
		bucketLowerBound,
		bucketUpperBound float64,
		samples int64,
	)

	// ReportHistogramDurationSamples reports histogram samples for a bucket
	ReportHistogramDurationSamples(
		name string,
		tags map[string]string,
		buckets Buckets,
		bucketLowerBound,
		bucketUpperBound time.Duration,
		samples int64,
	)
}

Or implement your own metrics implementation that matches the tally Scope interface to use different buffering semantics:

type Scope interface {
	// Counter returns the Counter object corresponding to the name.
	Counter(name string) Counter

	// Gauge returns the Gauge object corresponding to the name.
	Gauge(name string) Gauge

	// Timer returns the Timer object corresponding to the name.
	Timer(name string) Timer

	// Histogram returns the Histogram object corresponding to the name.
	// To use default value and duration buckets configured for the scope
	// simply pass tally.DefaultBuckets or nil.
	// You can use tally.ValueBuckets{x, y, ...} for value buckets.
	// You can use tally.DurationBuckets{x, y, ...} for duration buckets.
	// You can use tally.MustMakeLinearValueBuckets(start, width, count) for linear values.
	// You can use tally.MustMakeLinearDurationBuckets(start, width, count) for linear durations.
	// You can use tally.MustMakeExponentialValueBuckets(start, factor, count) for exponential values.
	// You can use tally.MustMakeExponentialDurationBuckets(start, factor, count) for exponential durations.
	Histogram(name string, buckets Buckets) Histogram

	// Tagged returns a new child scope with the given tags and current tags.
	Tagged(tags map[string]string) Scope

	// SubScope returns a new child scope appending a further name prefix.
	SubScope(name string) Scope

	// Capabilities returns a description of metrics reporting capabilities.
	Capabilities() Capabilities
}

// Capabilities is a description of metrics reporting capabilities.
type Capabilities interface {
	// Reporting returns whether the reporter has the ability to actively report.
	Reporting() bool

	// Tagging returns whether the reporter has the capability for tagged metrics.
	Tagging() bool
}

Performance

This stuff needs to be fast. With that in mind, we avoid locks and unnecessary memory allocations.

BenchmarkCounterInc-8               	200000000	         7.68 ns/op
BenchmarkReportCounterNoData-8      	300000000	         4.88 ns/op
BenchmarkReportCounterWithData-8    	100000000	        21.6 ns/op
BenchmarkGaugeSet-8                 	100000000	        16.0 ns/op
BenchmarkReportGaugeNoData-8        	100000000	        10.4 ns/op
BenchmarkReportGaugeWithData-8      	50000000	        27.6 ns/op
BenchmarkTimerInterval-8            	50000000	        37.7 ns/op
BenchmarkTimerReport-8              	300000000	         5.69 ns/op

Released under the MIT License.

# Packages

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Package tallymock is a generated GoMock package.
No description provided by the author

# Functions

BucketPairs creates a set of bucket pairs from a set of buckets describing the lower and upper bounds for each derived bucket.
ExponentialDurationBuckets creates a set of exponential duration buckets.
ExponentialValueBuckets creates a set of exponential value buckets.
KeyForPrefixedStringMap generates a unique key for a a prefix and a map string set combination.
KeyForStringMap generates a unique key for a map string set combination.
LinearDurationBuckets creates a set of linear duration buckets.
LinearValueBuckets creates a set of linear value buckets.
MustMakeExponentialDurationBuckets creates a set of exponential value buckets or panics.
MustMakeExponentialValueBuckets creates a set of exponential value buckets or panics.
MustMakeLinearDurationBuckets creates a set of linear duration buckets.
MustMakeLinearValueBuckets creates a set of linear value buckets or panics.
NewNoOpSanitizer returns a sanitizer which returns all inputs un-touched.
NewObjectPool creates a new pool.
NewRootScope creates a new root Scope with a set of options and a reporting interval.
NewRootScopeWithDefaultInterval invokes NewRootScope with the default reporting interval of 2s.
NewSanitizer returns a new sanitizer based on provided options.
NewStopwatch creates a new immutable stopwatch for recording the start time to a stopwatch reporter.
NewTestScope creates a new Scope without a stats reporter with the given prefix and adds the ability to take snapshots of metrics emitted to it.
NoOpSanitizeFn returns the input un-touched.

# Constants

DefaultTagRedactValue is the default tag value to use when redacting.
Version is the current version of the library.

# Variables

AlphanumericRange is the range of alphanumeric characters.
DefaultBuckets can be passed to specify to default buckets.
DefaultReplacementCharacter is the default character used for replacements.
DefaultSeparator is the default separator used to join nested scopes.
NoopScope is a scope that does nothing.
NullStatsReporter is an implementation of StatsReporter than simply does nothing.
UnderscoreCharacters is just an underscore character.
UnderscoreDashCharacters is a slice of underscore, and dash characters.
UnderscoreDashDotCharacters is a slice of underscore, dash, and dot characters.

# Structs

ObjectPool is an minimalistic object pool to avoid any circular dependencies on any other object pool.
SanitizeOptions are the set of configurable options for sanitisation.
ScopeOptions is a set of options to construct a scope.
Stopwatch is a helper for simpler tracking of elapsed time, use the Stop() method to report time elapsed since its created back to the timer or histogram.
ValidCharacters is a collection of valid characters.

# Interfaces

BaseStatsReporter implements the shared reporter methods.
BucketPair describes the lower and upper bounds for a derived bucket from a buckets set.
Buckets is an interface that can represent a set of buckets either as float64s or as durations.
CachedCount interface for reporting an individual counter.
CachedGauge interface for reporting an individual gauge.
CachedHistogram interface for reporting histogram samples to buckets.
CachedHistogramBucket interface for reporting histogram samples to a specific bucket.
CachedStatsReporter is a backend for Scopes that pre allocates all counter, gauges, timers & histograms.
CachedTimer interface for reporting an individual timer.
Capabilities is a description of metrics reporting capabilities.
Counter is the interface for emitting counter type metrics.
CounterSnapshot is a snapshot of a counter.
Gauge is the interface for emitting gauge metrics.
GaugeSnapshot is a snapshot of a gauge.
Histogram is the interface for emitting histogram metrics.
HistogramSnapshot is a snapshot of a histogram.
Sanitizer sanitizes the provided input based on the function executed.
Scope is a namespace wrapper around a stats reporter, ensuring that all emitted values have a given prefix or set of tags.
Snapshot is a snapshot of values since last report execution.
StatsReporter is a backend for Scopes to report metrics to.
StopwatchRecorder is a recorder that is called when a stopwatch is stopped with Stop().
TestScope is a metrics collector that has no reporting, ensuring that all emitted values have a given prefix or set of tags.
Timer is the interface for emitting timer metrics.
TimerSnapshot is a snapshot of a timer.

# Type aliases

DurationBuckets is a set of time.Duration values that implements Buckets.
SanitizeFn returns a sanitized version of the input string.
SanitizeRange is a range of characters (inclusive on both ends).
ValueBuckets is a set of float64 values that implements Buckets.