gometer

package module
v0.0.0-...-105e337 Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2021 License: MIT Imports: 9 Imported by: 0

README

gometer GoDoc Build Status Go Report Card Coverage Status

gometer is a small library for your application's metrics.

The main goal of gometer is to be very simple, small and stupid, and to write formatted key-value metrics somewhere.

Installation

Install Go and run:

go get -v github.com/dshil/gometer

Documentation

Documentation is available on GoDoc.

Quick start

Write metrics to stdout.
package example

import (
	"fmt"
	"os"

	"github.com/dshil/gometer"
)

func ExampleWriteToStdout() {
	metrics := gometer.New()

	metrics.SetOutput(os.Stdout)
	metrics.SetFormatter(gometer.NewFormatter("\n"))

	c := metrics.Get("http_requests_total")
	c.Add(1)

	if err := metrics.Write(); err != nil {
		fmt.Println(err.Error())
		return
	}
	// Output:
	// http_requests_total = 1
}
Write metrics to a file periodically.
package example

import (
	"fmt"
	"time"

	"github.com/dshil/gometer"
)

func ExampleWriteToFile() {
	metrics := gometer.New()
	metrics.SetFormatter(gometer.NewFormatter("\n"))

	gometer.StartFileWriter(gometer.FileWriterParams{
		FilePath:       "test_file",
		UpdateInterval: time.Second,
		ErrorHandler: func(err error) {
			fmt.Println(err)
		},
	}).Stop()
}
Own formatter for metrics representation.
package example

import (
	"bytes"
	"fmt"
	"os"

	"github.com/dshil/gometer"
)

type simpleFormatter struct{}

func (f *simpleFormatter) Format(counters gometer.SortedCounters) []byte {
	var buf bytes.Buffer

	for _, c := range counters {
		fmt.Fprintf(&buf, "%s:%d%s", c.Name, c.Counter.Get(), "\n")
	}

	return buf.Bytes()
}

var _ gometer.Formatter = (*simpleFormatter)(nil)

func ExampleSimpleFormatter() {
	metrics := gometer.New()
	metrics.SetOutput(os.Stdout)
	metrics.SetFormatter(new(simpleFormatter))

	c := metrics.Get("foo")
	c.Add(100)

	if err := metrics.Write(); err != nil {
		fmt.Println(err)
		return
	}

	// Output:
	// foo:100
}

func ExampleDefaultFormatter() {
	metrics := gometer.New()
	metrics.SetOutput(os.Stdout)

	for _, name := range []string{"foo", "bar", "baz"} {
		c := metrics.Get(name)
		c.Add(100)
	}

	if err := metrics.Write(); err != nil {
		fmt.Println(err)
		return
	}

	// Output:
	// bar = 100
	// baz = 100
	// foo = 100
}
Get metrics in JSON format for a specified pattern.
package example

import (
	"fmt"

	"github.com/dshil/gometer"
	"github.com/gobwas/glob"
)

func ExampleMetricsGetJSONGlobPatterns() {
	metrics := gometer.New()

	for k, v := range map[string]int64{
		"abc":  10,
		"abb":  42,
		"adc":  33,
		"aaac": 17,
	} {
		c := metrics.Get(k)
		c.Set(v)
	}

	for _, tCase := range [...]struct {
		pattern  string
		expected string
	}{
		{
			pattern:  "*",
			expected: `{"abc": 10, "abb": 42, "adc": 33, "aaac":17}`,
		},
		{
			pattern:  "a*",
			expected: `{"abc": 10, "abb": 42, "adc": 33, "aaac":17}`,
		},
		{
			pattern:  "a?c",
			expected: `{"abc": 10, "adc": 33}`,
		},
		{
			pattern:  "a*c",
			expected: `{"abc": 10, "adc": 33, "aaac":17}`,
		},
		{
			pattern:  "*b*",
			expected: `{"abc": 10, "abb": 42}`,
		},
		{
			pattern:  "??[ab]*",
			expected: `{"abb": 42, "aaac":17}`,
		},
	} {
		g := glob.MustCompile(tCase.pattern)
		b := metrics.GetJSON(g.Match)
		fmt.Println(string(b))
	}
	// Output:
	// {"aaac":17,"abb":42,"abc":10,"adc":33}
	// {"aaac":17,"abb":42,"abc":10,"adc":33}
	// {"abc":10,"adc":33}
	// {"aaac":17,"abc":10,"adc":33}
	// {"abb":42,"abc":10}
	// {"aaac":17,"abb":42}
}
Group metrics by a specified prefix.
package example

import (
	"fmt"
	"os"

	"github.com/dshil/gometer"
)

func ExamplePrefixMetrics() {
	prefixMetrics := gometer.New().WithPrefix("data.%s.%s.", "errors", "counters")
	prefixMetrics.SetOutput(os.Stdout)

	for _, name := range []string{"foo", "bar", "baz"} {
		c := prefixMetrics.Get(name)
		c.Add(100)
	}

	if err := prefixMetrics.Write(); err != nil {
		fmt.Println(err)
		return
	}

	// Output:
	// data.errors.counters.bar = 100
	// data.errors.counters.baz = 100
	// data.errors.counters.foo = 100
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Default = New()

Default is a standard metrics object.

Functions

func GetJSON

func GetJSON(predicate func(string) bool) []byte

GetJSON filters counters by given predicate and returns them as a json marshaled map.

func SetFormatter

func SetFormatter(f Formatter)

SetFormatter sets formatter for standard metrics. Fore more details see DefaultMetrics.SetFormatter().

func SetOutput

func SetOutput(out io.Writer)

SetOutput sets output destination for standard metrics.

func Write

func Write() error

Write all existing metrics to an output destination. For more details see DefaultMetrics.Write().

Types

type Counter

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

Counter represents a kind of metric.

func Get

func Get(counterName string) *Counter

Get returns counter by name. If counter doesn't exist it will be created.

func (*Counter) Add

func (c *Counter) Add(val int64)

Add adds the corresponding value to a counter.

func (*Counter) AddAndGet

func (c *Counter) AddAndGet(val int64) int64

AddAndGet adds val to a counter and returns an updated value.

func (*Counter) Get

func (c *Counter) Get() int64

Get returns the corresponding value for a counter.

func (*Counter) Set

func (c *Counter) Set(val int64)

Set sets the value to a counter. Value can be negative.

type DefaultMetrics

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

DefaultMetrics is a default implementation of Metrics.

func New

func New() *DefaultMetrics

New creates new empty collection of metrics.

func (*DefaultMetrics) Formatter

func (m *DefaultMetrics) Formatter() Formatter

Formatter returns a metrics formatter.

func (*DefaultMetrics) Get

func (m *DefaultMetrics) Get(counterName string) *Counter

Get returns counter by name. If counter doesn't exist it will be created.

func (*DefaultMetrics) GetJSON

func (m *DefaultMetrics) GetJSON(predicate func(string) bool) []byte

GetJSON filters counters by given predicate and returns them as a json marshaled map.

func (*DefaultMetrics) SetFormatter

func (m *DefaultMetrics) SetFormatter(f Formatter)

SetFormatter sets a metrics's formatter.

func (*DefaultMetrics) SetOutput

func (m *DefaultMetrics) SetOutput(out io.Writer)

SetOutput sets output destination for metrics.

func (*DefaultMetrics) SetRootPrefix

func (m *DefaultMetrics) SetRootPrefix(prefix string)

SetRootPrefix sets root prefix used to format output

func (*DefaultMetrics) StartFileWriter

func (m *DefaultMetrics) StartFileWriter(params FileWriterParams) Stopper

StartFileWriter starts a goroutine that periodically writes metrics to a file.

func (*DefaultMetrics) WithPrefix

func (m *DefaultMetrics) WithPrefix(prefix string, v ...interface{}) *PrefixMetrics

WithPrefix creates new PrefixMetrics that uses original Metrics with specified prefix.

func (*DefaultMetrics) Write

func (m *DefaultMetrics) Write() error

Write writes all existing metrics to output destination.

Writing metrics to the file using this method will not recreate a file. It appends existing metrics to existing file's data. if you want to write metrics to clear file use StartFileWriter() method.

type FileWriterParams

type FileWriterParams struct {
	FilePath       string
	UpdateInterval time.Duration
	NoFlushOnStop  bool
	ErrorHandler   func(err error)
}

FileWriterParams represents a params for asynchronous file writing operation.

FilePath represents a file path. UpdateInterval determines how often metrics data will be written to a file. NoFlushOnStop disables metrics flushing when the metrics writer finishes. ErrorHandler allows to handle errors from the goroutine that writes metrics.

type Formatter

type Formatter interface {
	Format(counters SortedCounters) []byte
}

Formatter determines a format of metrics representation.

func NewFormatter

func NewFormatter(lineSeparator string) Formatter

NewFormatter returns new default formatter.

lineSeparator determines how one line of metric will be separated from another.

As line separator can be used any symbol: e.g. '\n', ':', '.', ','.

Default format for one line of metrics is: "%v = %v". Metrics will be sorted by key.

type Metrics

type Metrics interface {
	SetOutput(io.Writer)
	SetFormatter(Formatter)
	Formatter() Formatter
	Get(string) *Counter
	GetJSON(func(string) bool) []byte
	WithPrefix(string, ...interface{}) *PrefixMetrics
	Write() error
	StartFileWriter(FileWriterParams) Stopper
}

Metrics is a collection of metrics.

type PanicHandler

type PanicHandler interface {
	Handle(err error)
}

PanicHandler is used to handle errors that causing the panic.

type PrefixMetrics

type PrefixMetrics struct {
	Metrics
	// contains filtered or unexported fields
}

PrefixMetrics is a Metrics wrapper, that always add specified prefix to counters names.

func WithPrefix

func WithPrefix(prefix string, v ...interface{}) *PrefixMetrics

WithPrefix creates new PrefixMetrics that uses original Metrics with specified prefix. For more details see DefaultMetrics.WithPrefix().

func (*PrefixMetrics) Get

func (m *PrefixMetrics) Get(counterName string) *Counter

Get calls underlying Metrics Get method with prefixed counterName.

func (*PrefixMetrics) WithPrefix

func (m *PrefixMetrics) WithPrefix(prefix string, v ...interface{}) *PrefixMetrics

WithPrefix returns new PrefixMetrics with extended prefix.

type SortedCounters

type SortedCounters []struct {
	Name    string
	Counter *Counter
}

SortedCounters represents counters slice sorted by name

type Stopper

type Stopper interface {
	Stop()
}

Stopper is used to stop started entities.

func StartFileWriter

func StartFileWriter(p FileWriterParams) Stopper

StartFileWriter starts a goroutine that periodically writes metrics to a file. For more details see DefaultMetrics.StartFileWriter().

Jump to

Keyboard shortcuts

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