mtchuyen / Golang-Tips

Tips in Golang programming
3 stars 2 forks source link

The expvar package - Metrics for Go #21

Open mtchuyen opened 2 years ago

mtchuyen commented 2 years ago

https://www.mikeperham.com/2014/12/17/expvar-metrics-for-golang/

https://sysdig.com/blog/golang-expvar-custom-metrics/

https://medium.com/@piotrrojek/monitoring-apps-with-expvar-and-go-6d314267ee9f

func snapshotMap(varsMap map[string]int64, path string, mp *expvar.Map) {
    mp.Do(func(kv expvar.KeyValue) {
        switch kv.Value.(type) {
        case *expvar.Int:
            varsMap[path+"."+kv.Key], _ = strconv.ParseInt(kv.Value.String(), 10, 64)
        case *expvar.Map:
            snapshotMap(varsMap, path+"."+kv.Key, kv.Value.(*expvar.Map))
        }
    })
}
func resetVarMap(varMap *expvar.Map) {
    // There is no easy way to delete/clear expvar.Map.  As such there is a slight
    // race here.  *sigh*
    keys := []string{}
    varMap.Do(func(kv expvar.KeyValue) {
        keys = append(keys, kv.Key)
    })

    for _, key := range keys {
        varMap.Set(key, new(expvar.Int))
    }
}

https://github.com/FiloSottile/whoami.filippo.io/blob/7464e26635ec2a31289eb80b73a0312764690137/influxdb.go


            fields := make(map[string]interface{})
            var do func(string, expvar.KeyValue)
            do = func(prefix string, kv expvar.KeyValue) {
                switch v := kv.Value.(type) {
                case *expvar.Int:
                    fields[prefix+kv.Key] = v.Value()
                case *expvar.Float:
                    fields[prefix+kv.Key] = v.Value()
                case *expvar.String:
                    fields[prefix+kv.Key] = v.Value()
                case *expvar.Map:
                    v.Do(func(x expvar.KeyValue) { do(kv.Key+".", x) })
                default:
                    fields[prefix+kv.Key] = v.String()
                }
            }
            expvar.Do(func(kv expvar.KeyValue) { do("", kv) })

            if len(fields) == 0 {
                continue
            }