smetric

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2024 License: BSD-2-Clause Imports: 8 Imported by: 0

README

smetric structured metrics

go helper to simply initializing structs holding prometheus metrics based on "github.com/VictoriaMetrics/metrics" InitMetricStruct initialize any variable holding pointer to metrics, register metrics with names generated from names of the fields of struct

Usage

Basic usage

    package main

    import (
    	"github.com/VictoriaMetrics/metrics"
		"github.com/tvojacek/smetric"
    )
	
    func main() {
        type OperationMetrics struct {
            Success  *metrics.Counter
            Failures *metrics.Counter
        }
        type CommonMetrics struct {
            Healthy       *metrics.Counter
            Reconnections *metrics.Counter
        }
        type exampleMetrics struct {
            CommonMetrics
            MessagesConsumed OperationMetrics
            WithCustomName   OperationMetrics `metric:"writes"`
        }
    
        var myMetrics exampleMetrics
    
        metricNamesBuilder := NewNameBuilder("database").WithParameter("url", "localhost")
        set := metrics.NewSet()
        err := InitMetricStruct(&myMetrics, metricNamesBuilder, set)
        if err != nil {
            panic(err)
        }
		
	    myMetrics.MessagesConsumed.Success.Inc()
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var EmptyParameterValue = strconv.Quote("1")
View Source
var ErrorDuplicateMetric = fmt.Errorf("metric already exist")
View Source
var ErrorNotExistMetric = fmt.Errorf("metric does not exist")
View Source
var InvalidCharacterError = errors.New("invalid character")

Functions

func GetChanLength

func GetChanLength[T any](chanel chan T) func() float64

func GetSnakeMetricName

func GetSnakeMetricName(input string) (string, error)

GetSnakeMetricName convert input string to snake case metric names function return error if input contain invalid character valid characters are [a-z,A-Z,0-9,_]

func GetSnakeMetricNameSync

func GetSnakeMetricNameSync(input string) (string, error)

GetSnakeMetricNameSync convert input string to snake case metric names function return error if input contain invalid character valid characters are [a-z,A-Z,0-9,_]

func InitMetricStruct

func InitMetricStruct(metricStruct interface{}, nameBuilder NameBuilder, set *metrics.Set) error

InitMetricStruct register metrics defined in metricStruct. Names of metric are generated from tags `metric:"custom_suffix"` or names of struct fields converted to snake_case. Each nested struct add its name as prefix for nested metrics Implicit names for embed struct are ignored. Tags are never ignored.

Supported metrics types:

  • *metric.Counters,
  • *metric.FloatCounters
  • *metric.Summaries
  • *metric.Histograms
  • Gauges

Function parameter metricStruct must be pointer to struct.

set can be nil, default set used.

Gauges helper allow to create gauges with same structured name like rest of the metrics.

Func can panic if metric with duplicate name is already registered. It is user responsibility that metrics with same names do not exist in set prior calling function and tags does not have duplicate values.

Example
type OperationMetrics struct {
	Success  *metrics.Counter
	Failures *metrics.Counter
}
type CommonMetrics struct {
	Healthy       *metrics.Counter
	Reconnections *metrics.Counter
}
type exampleMetrics struct {
	CommonMetrics
	MessagesConsumed OperationMetrics
	WithCustomName   OperationMetrics `metric:"writes"`
}

var myMetrics exampleMetrics

metricNamesBuilder := NewNameBuilder("database").WithParameter("url", "localhost")
set := metrics.NewSet()
err := InitMetricStruct(&myMetrics, metricNamesBuilder, set)
if err != nil {
	panic(err)
}

for _, name := range set.ListMetricNames() {
	fmt.Println(name)
}
set.UnregisterAllMetrics()
Output:

database_healthy{url="localhost"}
database_reconnections{url="localhost"}
database_messages_consumed_failures{url="localhost"}
database_messages_consumed_success{url="localhost"}
database_writes_failures{url="localhost"}
database_writes_success{url="localhost"}
Example (Gauges)

ExampleInitMetricStruct_gauges cleanup can be omited

type exampleMetrics struct {
	Input ChannelMetrics
}

var myMetrics exampleMetrics

metricNamesBuilder := NewNameBuilder("data_processor").WithParameter("url", "localhost")
set := metrics.NewSet()
err := InitMetricStruct(&myMetrics, metricNamesBuilder, set)
if err != nil {
	panic(err)
}

var myChan chan struct{}

myMetrics.Input.AddLength(GetChanLength(myChan))

if err != nil {
	panic(err)
}
fmt.Println(myMetrics.Input.Name())
for _, name := range set.ListMetricNames() {
	fmt.Println(name)
}
Output:

input
data_processor_input_length{url="localhost"}
data_processor_input_over_flow{url="localhost"}
data_processor_input_total{url="localhost"}

Types

type ChannelMetrics

type ChannelMetrics struct {
	Metrics
	Total    *metrics.Counter
	OverFlow *metrics.Counter
}

func (*ChannelMetrics) AddLength

func (channelMetrics *ChannelMetrics) AddLength(getLen func() float64)

func (*ChannelMetrics) Reset

func (channelMetrics *ChannelMetrics) Reset()

type Metrics

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

func (*Metrics) AddGauge

func (g *Metrics) AddGauge(suffix string, getValue func() float64) error

Add register gauge. Function return error if gauge with same prefix already exist. Function is safe to call repeatably amd concurrently.

func (*Metrics) AddOrReplace

func (g *Metrics) AddOrReplace(suffix string, getValue func() float64) error

AddOrReplace register gauge with suffix if Gauge with same prefix exist it is unregistered first. Function is safe to call repeatably amd concurrently.

func (*Metrics) Destroy

func (g *Metrics) Destroy(suffix string) error

Destroy unregister gauge with suffix. Function return error if gauge does not exist. Function is safe to call repeatably amd concurrently.

func (*Metrics) DestroyAll

func (g *Metrics) DestroyAll() error

DestroyAll unregister and remove all gauges. Function is safe to call repeatably amd concurrently.

func (*Metrics) Name

func (g *Metrics) Name() string

Name

type NameBuilder

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

func GetGlobalBuilder

func GetGlobalBuilder() NameBuilder

func NewNameBuilder

func NewNameBuilder(prefix string) NameBuilder

func (NameBuilder) Error

func (b NameBuilder) Error() error

func (NameBuilder) LastSuffix

func (b NameBuilder) LastSuffix() string

func (NameBuilder) String

func (b NameBuilder) String() (string, error)

func (NameBuilder) WithParameter

func (b NameBuilder) WithParameter(name string, value string) NameBuilder

func (NameBuilder) WithSuffix

func (b NameBuilder) WithSuffix(name string) NameBuilder

Jump to

Keyboard shortcuts

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