Aggregate Counters With The Expvar Package

Register in-process metrics with expvar Ints and Maps, retrieve them by name with Get, and walk every published variable with Do — no metrics library.

GoCli Tooling

Code

gosnippet
34 lines
package main

import (
	"expvar"
	"fmt"
)

func main() {
	requests := expvar.NewInt("requests")
	requests.Add(1)
	requests.Add(1)

	failures := expvar.NewInt("failures")
	failures.Add(1)

	// Map 变量按字符串键聚合:每个键自动挂一个 Int 子计数器
	counters := expvar.NewMap("counters")
	counters.Add("timeout", 2)
	counters.Add("refused", 1)

	// Get 按名取回已注册变量,类型断言回具体 Var 后继续读写
	if v := expvar.Get("failures"); v != nil {
		if counter, ok := v.(*expvar.Int); ok {
			counter.Add(1)
		}
	}

	// Do 遍历全部已发布变量:Key 是名字,Value 是具体 Var
	expvar.Do(func(kv expvar.KeyValue) {
		fmt.Printf("%s = %s\n", kv.Key, kv.Value.String())
	})

	fmt.Println("requests now:", requests.String())
}

Where the work happens

The snippet is organized around the function main.

Watch out for

  • Zero packages pulled in — the runtime ships every API this code touches.

Putting it to use

Entry signature: func main()

The output carries labels — requests now: — when the file runs.

Core lines

requests := expvar.NewInt("requests")

Interactive Tools for This Topic

FAQ

What does Aggregate Counters With The Expvar Package print when run?
Execute the whole file; each printed line is prefixed with a label like `requests now:`.