stats

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2017 License: MIT Imports: 11 Imported by: 24

README

hellofresh/stats-go

Build Status Coverage Status GoDoc Go Report Card

Generic Stats library written in Go

This is generic stats library that we at HelloFresh use in our projects to collect services' stats and then create monitoring dashboards to track activity and problems.

Key Features

  • Several stats backends:
    • log for development environment
    • statsd for production (with fallback to log if statsd server is not available)
    • memory for testing purpose, to track stats operations in unit tests
    • noop for environments that do not require any stats gathering
  • Fixed metric sections count for all metrics to allow easy monitoring/alerting setup in grafana
  • Easy to build HTTP requests metrics - timing and count
  • Generalise or modify HTTP Requests metric - e.g. skip ID part

Installation

go get -u github.com/hellofresh/stats-go

Usage

Instance creation
package main

import (
        "os"

        "github.com/hellofresh/stats-go"
)

func main() {
        // client that tries to connect to statsd service, fallback to debug log backend if fails to connect
        statsdClient, _ := stats.NewClient("statsd://statsd-host:8125", "my.app.prefix")
        defer statsdClient.Close()

        // debug log backend for stats
        logClient, _ := stats.NewClient("log://", "")
        defer logClient.Close()

        // memory backend to track operations in unit tests
        memoryClient, _ := stats.NewClient("memory://", "")
        defer memoryClient.Close()

        // noop backend to ignore all stats
        noopClient, _ := stats.NewClient("noop://", "")
        defer noopClient.Close()

        // client that tries to connect to statsd service, fallback to debug log backend if fails to connect
        // format for backward compatibility with previous version
        legacyStatsdClient, _ := stats.NewClient("statsd-host:8125", "my.app.prefix")
        defer legacyStatsdClient.Close()

        // debug log backend for stats
        // format for backward compatibility with previous version
        legacyLogClient, _ := stats.NewClient("", "")
        defer legacyLogClient.Close()

        // get settings from env to determine backend and prefix
        statsClient, _ := stats.NewClient(os.Getenv("STATS_DSN"), os.Getenv("STATS_PREFIX"))
        defer statsClient.Close()
}
Count metrics manually
timing := statsClient.BuildTimeTracker().Start()
operations := statsClient.MetricOperation{"orders", "order", "create"}
err := orderService.Create(...)
statsClient.TrackOperation("ordering", operations, timing, err == nil)
Track requests metrics with middleware, e.g. for Gin Web Framework
package middleware

import (
	"net/http"

	log "github.com/Sirupsen/logrus"
	"github.com/gin-gonic/gin"
	stats "github.com/hellofresh/stats-go"
)

// NewStatsRequest returns a middleware handler function.
func NewStatsRequest(sc stats.Client) gin.HandlerFunc {
	return func(c *gin.Context) {
		log.WithField("path", c.Request.URL.Path).Debug("Starting Stats middleware")

		timing := sc.BuildTimeTracker().Start()

		c.Next()

		success := c.Writer.Status() < http.StatusBadRequest
		log.WithFields(log.Fields{"request_url": c.Request.URL.Path}).Debug("Track request stats")
		sc.TrackRequest(c.Request, timing, success)
	}
}
package main

import (
        "net/http"
        "os"

        "github.com/example/app/middleware"
        "github.com/gin-gonic/gin"
        stats "github.com/hellofresh/stats-go"
)

func main() {
        statsClient := stats.NewStatsdClient(os.Getenv("STATS_DSN"), os.Getenv("STATS_PREFIX"))
        defer statsClient.Close()

        router := gin.Default()
        router.Use(middleware.NewStatsRequest(statsClient))

        router.GET("/", func(c *gin.Context) {
                // will produce "<prefix>.get.-.-" metric
                c.JSON(http.StatusOK, "I'm producing stats!")
        })

        router.Run(":8080")
}
Usage in unit tests
package foo

import "github.com/hellofresh/stats-go"

const sectionStatsFoo = "foo"

func DoSomeJob(statsClient stats.Client) error {
        tt := statsClient.BuildTimeTracker().Start()
        operation := stats.MetricOperation{"do", "some", "job"}

        result, err := doSomeRealJobHere()
        statsClient.TrackOperation(sectionStatsFoo, operation, tt, result)

        return err
}
package foo

import (
        "testing"

        "github.com/hellofresh/stats-go"
        "github.com/stretchr/testify/assert"
)

func TestDoSomeJob(t *testing.T) {
        statsClient, _ := stats.NewClient("memory://", "") 
        
        err := DoSomeJob(statsClient)
        assert.Nil(t, err)
        
        statsMemory, _ := statsClient.(stats.MemoryClient)
        assert.Equal(t, 1, len(statsMemory.TimeMetrics))
        assert.Equal(t, "foo-ok.do.some.job", statsMemory.TimeMetrics[0].Bucket)
        assert.Equal(t, 1, statsMemory.CountMetrics["foo-ok.do.some.job"])
}
Generalise resources by type and stripping resource ID

In some cases you do not need to collect metrics for all unique requests, but a single metric for requests of the similar type, e.g. access time to concrete users pages does not matter a lot, but average access time is important. hellofresh/stats-go allows HTTP Request metric modification and supports ID filtering out of the box, so you can get generic metric get.users.-id- instead thousands of metrics like get.users.1, get.users.13, get.users.42 etc. that may make your graphite suffer from overloading.

To use metric generalisation by second level path ID, you can pass stats.HttpMetricNameAlterCallback instance to stats.Client.SetHttpMetricCallback(). Also there is a shortcut function stats.NewHasIDAtSecondLevelCallback() that generates a callback handler for stats.SectionsTestsMap, and shortcut function stats.ParseSectionsTestsMap, that generates sections test map from string, so you can get these values from config. It accepts a list of sections with test callback in the following format: <section>:<test-callback-name>. You can use either double colon or new line character as section-callback pairs separator, so all of the following forms are correct:

  • <section-0>:<test-callback-name-0>:<section-1>:<test-callback-name-1>:<section-2>:<test-callback-name-2>
  • <section-0>:<test-callback-name-0>\n<section-1>:<test-callback-name-1>\n<section-2>:<test-callback-name-2>
  • <section-0>:<test-callback-name-0>:<section-1>:<test-callback-name-1>\n<section-2>:<test-callback-name-2>

Currently the following test callbacks are implemented:

  • true - second path level is always treated as ID, e.g. /users/13 -> users.-id-, /users/search -> users.-id-, /users -> users.-id-
  • numeric - only numeric second path level is interpreted as ID, e.g. /users/13 -> users.-id-, /users/search -> users.search
  • not_empty - only not empty second path level is interpreted as ID, e.g. /users/13 -> users.-id-, /users -> users.-

You can register your own test callback functions using the stats.RegisterSectionTest() function before parsing sections map from string.

package main

import (
        "net/http"
        "os"

        "github.com/example/app/middleware"
        "github.com/gin-gonic/gin"
        stats "github.com/hellofresh/stats-go"
)

func main() {
        // STATS_IDS=users:not_empty:clients:numeric
        sectionsTestsMap, err := stats.ParseSectionsTestsMap(os.Getenv("STATS_IDS"))
        if err != nil {
                sectionsTestsMap = map[stats.PathSection]stats.SectionTestDefinition{}
        }
        statsClient, _ := stats.NewClient(os.Getenv("STATS_DSN"), os.Getenv("STATS_PREFIX"))
        statsClient.SetHTTPMetricCallback(stats.NewHasIDAtSecondLevelCallback(sectionsTestsMap))
        defer statsClient.Close()

        router := gin.Default()
        router.Use(middleware.NewStatsRequest(statsClient))

        router.GET("/users", func(c *gin.Context) {
                // will produce "<prefix>.get.users.-" metric
                c.JSON(http.StatusOK, "Get the userslist")
        })
        router.GET("/users/:id", func(c *gin.Context) {
                // will produce "<prefix>.get.users.-id-" metric 
                c.JSON(http.StatusOK, "Get the user ID " + c.Params.ByName("id"))
        })
        router.GET("/clients/:id", func(c *gin.Context) {
                // will produce "<prefix>.get.clients.-id-" metric
                c.JSON(http.StatusOK, "Get the client ID " + c.Params.ByName("id"))
        })

        router.Run(":8080")
}

Contributing

To start contributing, please check CONTRIBUTING.

Documentation

Documentation

Index

Constants

View Source
const (

	// MetricEmptyPlaceholder is a string placeholder for empty (unset) sections of operation
	MetricEmptyPlaceholder = "-"

	// MetricIDPlaceholder is a string placeholder for ID section of operation if any
	MetricIDPlaceholder = "-id-"
)
View Source
const (
	// StatsD is a dsn scheme value for statsd client
	StatsD = "statsd"
	// Log is a dsn scheme value for log client
	Log = "log"
	// Memory is a dsn scheme value for memory client
	Memory = "memory"
	// Noop is a dsn scheme value for noop client
	Noop = "noop"
)
View Source
const (

	// SectionTestTrue is a name for "stats.TestAlwaysTrue" test callback function
	SectionTestTrue = "true"

	// SectionTestIsNumeric is a name for "stats.TestIsNumeric" test callback function
	SectionTestIsNumeric = "numeric"

	// SectionTestIsNotEmpty is a name for "stats.TestIsNotEmpty" test callback function
	SectionTestIsNotEmpty = "not_empty"
)

Variables

View Source
var (
	// ErrInvalidFormat error indicates that sections string has invalid format
	ErrInvalidFormat = errors.New("Invalid sections format")

	// ErrUnknownSectionTest error indicates that section has unknown test callback name
	ErrUnknownSectionTest = errors.New("Unknown section test")
)
View Source
var ErrUnknownClient = errors.New("Unknown stats client type")

ErrUnknownClient is an error returned when trying to create stats client of unknown type

Functions

func RegisterSectionTest

func RegisterSectionTest(name string, callback SectionTestCallback)

RegisterSectionTest registers new section test callback function with its name

func SanitizeMetricName

func SanitizeMetricName(metric string) string

SanitizeMetricName modifies metric name to work well with statsd

func TestAlwaysTrue

func TestAlwaysTrue(PathSection) bool

TestAlwaysTrue section test callback function that gives true result to any section

func TestIsNotEmpty

func TestIsNotEmpty(s PathSection) bool

TestIsNotEmpty section test callback function that gives true result if section is not empty placeholder ("-")

func TestIsNumeric

func TestIsNumeric(s PathSection) bool

TestIsNumeric section test callback function that gives true result if section is numeric

Types

type Bucket

type Bucket interface {
	// Metric builds simple metric name in the form "<section>.<operation-0>.<operation-1>.<operation-2>"
	Metric() string

	// MetricWithSuffix builds metric name with success suffix in the form "<section>-ok|fail.<operation-0>.<operation-1>.<operation-2>"
	MetricWithSuffix() string

	// MetricTotal builds simple total metric name in the form total.<section>"
	MetricTotal() string

	// MetricTotalWithSuffix builds total metric name with success suffix in the form total-ok|fail.<section>"
	MetricTotalWithSuffix() string
}

Bucket is an interface for building metric names for operations

type BucketHTTPRequest added in v0.2.0

type BucketHTTPRequest struct {
	*BucketPlain
	// contains filtered or unexported fields
}

BucketHTTPRequest struct in an implementation of Bucket interface that produces metric names for HTTP Request. Metrics has the following formats for methods:

Metric() -> <section>.<method>.<path-level-0>.<path-level-1>
MetricWithSuffix() -> <section>-ok|fail.<method>.<path-level-0>.<path-level-1>
TotalRequests() -> total.<section>
MetricTotalWithSuffix() -> total-ok|fail.<section>

Normally "<section>" is set to "request", but you can use any string value here.

func NewBucketHTTPRequest added in v0.2.0

func NewBucketHTTPRequest(section string, r *http.Request, success bool, callback HTTPMetricNameAlterCallback) *BucketHTTPRequest

NewBucketHTTPRequest builds and returns new BucketHTTPRequest instance

type BucketPlain

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

BucketPlain struct in an implementation of Bucket interface that produces metric names for given section and operation

func NewBucketPlain

func NewBucketPlain(section string, operation MetricOperation, success bool) *BucketPlain

NewBucketPlain builds and returns new BucketPlain instance

func (*BucketPlain) Metric

func (b *BucketPlain) Metric() string

Metric builds simple metric name in the form:

<section>.<operation-0>.<operation-1>.<operation-2>

func (*BucketPlain) MetricTotal

func (b *BucketPlain) MetricTotal() string

MetricTotal builds simple total metric name in the form:

total.<section>

func (*BucketPlain) MetricTotalWithSuffix

func (b *BucketPlain) MetricTotalWithSuffix() string

MetricTotalWithSuffix builds total metric name with success suffix in the form

total-ok|fail.<section>

func (*BucketPlain) MetricWithSuffix

func (b *BucketPlain) MetricWithSuffix() string

MetricWithSuffix builds metric name with success suffix in the form:

<section>-ok|fail.<operation-0>.<operation-1>.<operation-2>

type Client added in v0.2.0

type Client interface {
	// BuildTimeTracker builds timer to track metric timings
	BuildTimeTracker() TimeTracker
	// Close closes underlying client connection if any
	Close() error

	// TrackRequest tracks HTTP Request stats
	TrackRequest(r *http.Request, tt TimeTracker, success bool) Client

	// TrackOperation tracks custom operation
	TrackOperation(section string, operation MetricOperation, tt TimeTracker, success bool) Client
	// TrackOperationN tracks custom operation with n diff
	TrackOperationN(section string, operation MetricOperation, tt TimeTracker, n int, success bool) Client

	// SetHTTPMetricCallback sets callback handler that allows metric operation alteration for HTTP Request
	SetHTTPMetricCallback(callback HTTPMetricNameAlterCallback) Client

	// SetHTTPRequestSection sets metric section for HTTP Request metrics
	SetHTTPRequestSection(section string) Client

	// ResetHTTPRequestSection resets metric section for HTTP Request metrics to default value that is "request"
	ResetHTTPRequestSection() Client
}

Client is an interface for different methods of gathering stats

func NewClient added in v0.2.0

func NewClient(dsn, prefix string) (Client, error)

NewClient creates and builds new stats client instance by given dsn

type HTTPMetricNameAlterCallback added in v0.2.0

type HTTPMetricNameAlterCallback func(metricParts MetricOperation, r *http.Request) MetricOperation

HTTPMetricNameAlterCallback is a type for HTTP Request metric alter handler

func NewHasIDAtSecondLevelCallback

func NewHasIDAtSecondLevelCallback(hasIDAtSecondLevel SectionsTestsMap) HTTPMetricNameAlterCallback

NewHasIDAtSecondLevelCallback returns HttpMetricNameAlterCallback implementation that checks for IDs on the second level of HTTP Request path

type Incrementer

type Incrementer interface {
	// Increment increments metric
	Increment(metric string)

	// IncrementN increments metric by n
	IncrementN(metric string, n int)

	// Increment increments all metrics for given bucket
	IncrementAll(b Bucket)

	// Increment increments all metrics for given bucket by n
	IncrementAllN(b Bucket, n int)
}

Incrementer is a metric incrementer interface

func NewIncrementer

func NewIncrementer(c *statsd.Client, muted bool) Incrementer

NewIncrementer builds and returns new Incrementer instance

type LogClient added in v0.2.0

type LogClient struct {
	*StatsdClient
}

LogClient is Client implementation for debug log

func NewLogClient added in v0.2.0

func NewLogClient() *LogClient

NewLogClient builds and returns new LogClient instance

type LogIncrementer

type LogIncrementer struct{}

LogIncrementer struct is Incrementer interface implementation that writes all metrics to log

func (*LogIncrementer) Increment

func (i *LogIncrementer) Increment(metric string)

Increment writes given metric to log

func (*LogIncrementer) IncrementAll

func (i *LogIncrementer) IncrementAll(b Bucket)

IncrementAll writes all metrics for given bucket to log

func (*LogIncrementer) IncrementAllN

func (i *LogIncrementer) IncrementAllN(b Bucket, n int)

IncrementAllN writes all metrics for given bucket to log

func (*LogIncrementer) IncrementN

func (i *LogIncrementer) IncrementN(metric string, n int)

IncrementN writes given metric to log

type LogTimeTracker

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

LogTimeTracker struct is TimeTracker interface implementation that writes all timings to log

func (*LogTimeTracker) Finish

func (t *LogTimeTracker) Finish(bucket string)

Finish writes elapsed time for metric to log

func (*LogTimeTracker) Start

func (t *LogTimeTracker) Start() TimeTracker

Start starts timer

type MemoryClient added in v0.2.0

type MemoryClient struct {
	sync.Mutex

	TimeMetrics  []TimerMetric
	CountMetrics map[string]int
	// contains filtered or unexported fields
}

MemoryClient is Client implementation for tests

func NewMemoryClient added in v0.2.0

func NewMemoryClient() *MemoryClient

NewMemoryClient builds and returns new MemoryClient instance

func (*MemoryClient) BuildTimeTracker added in v0.2.0

func (sc *MemoryClient) BuildTimeTracker() TimeTracker

BuildTimeTracker builds timer to track metric timings

func (*MemoryClient) Close added in v0.2.0

func (sc *MemoryClient) Close() error

Close resets all collected stats

func (*MemoryClient) ResetHTTPRequestSection added in v0.2.0

func (sc *MemoryClient) ResetHTTPRequestSection() Client

ResetHTTPRequestSection resets metric section for HTTP Request metrics to default value that is "request"

func (*MemoryClient) SetHTTPMetricCallback added in v0.2.0

func (sc *MemoryClient) SetHTTPMetricCallback(callback HTTPMetricNameAlterCallback) Client

SetHTTPMetricCallback sets callback handler that allows metric operation alteration for HTTP Request

func (*MemoryClient) SetHTTPRequestSection added in v0.2.0

func (sc *MemoryClient) SetHTTPRequestSection(section string) Client

SetHTTPRequestSection sets metric section for HTTP Request metrics

func (*MemoryClient) TrackOperation added in v0.2.0

func (sc *MemoryClient) TrackOperation(section string, operation MetricOperation, tt TimeTracker, success bool) Client

TrackOperation tracks custom operation

func (*MemoryClient) TrackOperationN added in v0.2.0

func (sc *MemoryClient) TrackOperationN(section string, operation MetricOperation, tt TimeTracker, n int, success bool) Client

TrackOperationN tracks custom operation with n diff

func (*MemoryClient) TrackRequest added in v0.2.0

func (sc *MemoryClient) TrackRequest(r *http.Request, tt TimeTracker, success bool) Client

TrackRequest tracks HTTP Request stats

type MemoryIncrementer added in v0.2.0

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

MemoryIncrementer struct is Incrementer interface implementation that stores results in memory for further usage

func NewMemoryIncrementer added in v0.2.0

func NewMemoryIncrementer() *MemoryIncrementer

NewMemoryIncrementer builds and returns new MemoryIncrementer instance

func (*MemoryIncrementer) Increment added in v0.2.0

func (i *MemoryIncrementer) Increment(metric string)

Increment increments given metric in memory

func (*MemoryIncrementer) IncrementAll added in v0.2.0

func (i *MemoryIncrementer) IncrementAll(b Bucket)

IncrementAll increments all metrics for given bucket in memory

func (*MemoryIncrementer) IncrementAllN added in v0.2.0

func (i *MemoryIncrementer) IncrementAllN(b Bucket, n int)

IncrementAllN increments all metrics for given bucket in memory

func (*MemoryIncrementer) IncrementN added in v0.2.0

func (i *MemoryIncrementer) IncrementN(metric string, n int)

IncrementN increments given metric in memory

func (*MemoryIncrementer) Metrics added in v0.2.0

func (i *MemoryIncrementer) Metrics() map[string]int

Metrics returns all previously stored metrics

type MemoryTimeTracker added in v0.2.0

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

MemoryTimeTracker struct is TimeTracker interface implementation that stores results in memory for further usage

func (*MemoryTimeTracker) Elapsed added in v0.2.0

func (t *MemoryTimeTracker) Elapsed() TimerMetric

Elapsed returns elapsed duration

func (*MemoryTimeTracker) Finish added in v0.2.0

func (t *MemoryTimeTracker) Finish(bucket string)

Finish stores elapsed duration in memory

func (*MemoryTimeTracker) Start added in v0.2.0

func (t *MemoryTimeTracker) Start() TimeTracker

Start starts timer

type MetricOperation

type MetricOperation [3]string

MetricOperation is a list of metric operations to use for metric

type NoopClient added in v0.2.1

type NoopClient struct{}

NoopClient is Client implementation that does literally nothing

func NewNoopClient added in v0.2.1

func NewNoopClient() *NoopClient

NewNoopClient builds and returns new NoopClient instance

func (*NoopClient) BuildTimeTracker added in v0.2.1

func (c *NoopClient) BuildTimeTracker() TimeTracker

BuildTimeTracker builds timer to track metric timings

func (*NoopClient) Close added in v0.2.1

func (c *NoopClient) Close() error

Close closes underlying client connection if any

func (*NoopClient) ResetHTTPRequestSection added in v0.2.1

func (c *NoopClient) ResetHTTPRequestSection() Client

ResetHTTPRequestSection resets metric section for HTTP Request metrics to default value that is "request"

func (*NoopClient) SetHTTPMetricCallback added in v0.2.1

func (c *NoopClient) SetHTTPMetricCallback(callback HTTPMetricNameAlterCallback) Client

SetHTTPMetricCallback sets callback handler that allows metric operation alteration for HTTP Request

func (*NoopClient) SetHTTPRequestSection added in v0.2.1

func (c *NoopClient) SetHTTPRequestSection(section string) Client

SetHTTPRequestSection sets metric section for HTTP Request metrics

func (*NoopClient) TrackOperation added in v0.2.1

func (c *NoopClient) TrackOperation(section string, operation MetricOperation, tt TimeTracker, success bool) Client

TrackOperation tracks custom operation

func (*NoopClient) TrackOperationN added in v0.2.1

func (c *NoopClient) TrackOperationN(section string, operation MetricOperation, tt TimeTracker, n int, success bool) Client

TrackOperationN tracks custom operation with n diff

func (*NoopClient) TrackRequest added in v0.2.1

func (c *NoopClient) TrackRequest(r *http.Request, tt TimeTracker, success bool) Client

TrackRequest tracks HTTP Request stats

type PathSection

type PathSection string

PathSection type represents single path section string

type SectionTestCallback

type SectionTestCallback func(PathSection) bool

SectionTestCallback type represents section test callback function

func GetSectionTestCallback

func GetSectionTestCallback(name string) SectionTestCallback

GetSectionTestCallback returns section test callback function by name

type SectionTestDefinition

type SectionTestDefinition struct {
	Name     string
	Callback SectionTestCallback
}

SectionTestDefinition type represents section test callback definition

type SectionsTestsMap

type SectionsTestsMap map[PathSection]SectionTestDefinition

SectionsTestsMap type represents section test callbacks definitions map

func ParseSectionsTestsMap

func ParseSectionsTestsMap(s string) (SectionsTestsMap, error)

ParseSectionsTestsMap parses string into SectionsTestsMap. In most cases string comes as config to the application e.g. from env. Valid string formats are: 1. <section-0>:<test-callback-name-0>:<section-1>:<test-callback-name-1>:<section-2>:<test-callback-name-2> 2. <section-0>:<test-callback-name-0>\n<section-1>:<test-callback-name-1>\n<section-2>:<test-callback-name-2> 3. <section-0>:<test-callback-name-0>:<section-1>:<test-callback-name-1>\n<section-2>:<test-callback-name-2>

func (SectionsTestsMap) String

func (m SectionsTestsMap) String() string

String returns pretty formatted string representation of SectionsTestsMap

type StatsdClient added in v0.2.0

type StatsdClient struct {
	sync.Mutex
	// contains filtered or unexported fields
}

StatsdClient is Client implementation for statsd

func NewStatsdClient added in v0.2.0

func NewStatsdClient(dsn, prefix string) *StatsdClient

NewStatsdClient builds and returns new StatsdClient instance

func (*StatsdClient) BuildTimeTracker added in v0.2.0

func (sc *StatsdClient) BuildTimeTracker() TimeTracker

BuildTimeTracker builds timer to track metric timings

func (*StatsdClient) Close added in v0.2.0

func (sc *StatsdClient) Close() error

Close statsd connection

func (*StatsdClient) ResetHTTPRequestSection added in v0.2.0

func (sc *StatsdClient) ResetHTTPRequestSection() Client

ResetHTTPRequestSection resets metric section for HTTP Request metrics to default value that is "request"

func (*StatsdClient) SetHTTPMetricCallback added in v0.2.0

func (sc *StatsdClient) SetHTTPMetricCallback(callback HTTPMetricNameAlterCallback) Client

SetHTTPMetricCallback sets callback handler that allows metric operation alteration for HTTP Request

func (*StatsdClient) SetHTTPRequestSection added in v0.2.0

func (sc *StatsdClient) SetHTTPRequestSection(section string) Client

SetHTTPRequestSection sets metric section for HTTP Request metrics

func (*StatsdClient) TrackOperation added in v0.2.0

func (sc *StatsdClient) TrackOperation(section string, operation MetricOperation, tt TimeTracker, success bool) Client

TrackOperation tracks custom operation

func (*StatsdClient) TrackOperationN added in v0.2.0

func (sc *StatsdClient) TrackOperationN(section string, operation MetricOperation, tt TimeTracker, n int, success bool) Client

TrackOperationN tracks custom operation with n diff

func (*StatsdClient) TrackRequest added in v0.2.0

func (sc *StatsdClient) TrackRequest(r *http.Request, tt TimeTracker, success bool) Client

TrackRequest tracks HTTP Request stats

type StatsdIncrementer

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

StatsdIncrementer struct is Incrementer interface implementation that writes all metrics to statsd

func (*StatsdIncrementer) Increment

func (i *StatsdIncrementer) Increment(metric string)

Increment increments metric in statsd

func (*StatsdIncrementer) IncrementAll

func (i *StatsdIncrementer) IncrementAll(b Bucket)

IncrementAll increments all metrics for given bucket in statsd

func (*StatsdIncrementer) IncrementAllN

func (i *StatsdIncrementer) IncrementAllN(b Bucket, n int)

IncrementAllN increments all metrics for given bucket in statsd

func (*StatsdIncrementer) IncrementN

func (i *StatsdIncrementer) IncrementN(metric string, n int)

IncrementN increments metric by n in statsd

type StatsdTimeTracker

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

StatsdTimeTracker struct is TimeTracker interface implementation that writes all timings to statsd

func (*StatsdTimeTracker) Finish

func (t *StatsdTimeTracker) Finish(bucket string)

Finish writes elapsed time for metric to statsd

func (*StatsdTimeTracker) Start

func (t *StatsdTimeTracker) Start() TimeTracker

Start starts timer

type TimeTracker

type TimeTracker interface {
	// Start starts timer
	Start() TimeTracker
	// Finish writes elapsed time for metric
	Finish(bucket string)
}

TimeTracker is a metric time tracking interface

func NewTimeTracker

func NewTimeTracker(c *statsd.Client, muted bool) TimeTracker

NewTimeTracker builds and returns new TimeTracker instance

type TimerMetric added in v0.2.0

type TimerMetric struct {
	Bucket  string
	Elapsed time.Duration
}

TimerMetric is a type for storing single duration metric

Jump to

Keyboard shortcuts

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