package metrics
import (
"errors"
"fmt"
"strings"
"sync"
)
type Family struct {
mu sync .Mutex
name string
typ MetricType
labelNames []string
children map [string ]*FamilyMetric
}
type FamilyMetric struct {
mu sync .Mutex
labels []Label
counter uint64
gauge float64
}
func NewFamily (name string , typ MetricType , labelNames ...string ) *Family {
return &Family {
name : name ,
typ : typ ,
labelNames : append ([]string (nil ), labelNames ...),
children : make (map [string ]*FamilyMetric ),
}
}
func (f *Family ) With (labelValues ...string ) (*FamilyMetric , error ) {
if f == nil {
return nil , errors .New ("metrics: nil family" )
}
if len (labelValues ) != len (f .labelNames ) {
return nil , fmt .Errorf ("metrics: got %d label values, want %d" , len (labelValues ), len (f .labelNames ))
}
labels := make ([]Label , len (labelValues ))
for i := range labelValues {
labels [i ] = Label {Name : f .labelNames [i ], Value : labelValues [i ]}
}
key := familyKey (labelValues )
f .mu .Lock ()
defer f .mu .Unlock ()
m := f .children [key ]
if m == nil {
m = &FamilyMetric {labels : labels }
f .children [key ] = m
}
return m , nil
}
func (m *FamilyMetric ) Add (delta uint64 ) {
if m == nil {
return
}
m .mu .Lock ()
m .counter += delta
m .mu .Unlock ()
}
func (m *FamilyMetric ) Set (value float64 ) {
if m == nil {
return
}
m .mu .Lock ()
m .gauge = value
m .mu .Unlock ()
}
func (f *Family ) StructuredSnapshot () StructuredSnapshot {
if f == nil {
return nil
}
f .mu .Lock ()
children := make (map [string ]*FamilyMetric , len (f .children ))
for key , child := range f .children {
children [key ] = child
}
f .mu .Unlock ()
out := make (StructuredSnapshot , len (children ))
for key , child := range children {
child .mu .Lock ()
value := MetricValue {
Name : f .name ,
Type : f .typ ,
Labels : append ([]Label (nil ), child .labels ...),
Counter : child .counter ,
Gauge : child .gauge ,
}
child .mu .Unlock ()
out [f .name +"\x00" +key ] = value
}
return out
}
func familyKey(values []string ) string {
return strings .Join (values , "\x00" )
}
The pages are generated with Golds v0.8.4 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .