package collector //这个就相对简单。我们只需使用之前定义的函数方法。满足name以及Scrape 接口即可 然后通过chan <- prometheus.Metric只写管道来写入我们需要的指标, //这里需要注意的是我们之前提到的4中prometheus指标类型有一些在这里需要float64的值传入 //但是我们收集到的并不一定都是float64类型的那么我们在做类型转换的过程中需要考虑大转小溢出的问题 import ( "fmt" "github.com/prometheus/client_golang/prometheus" "github.com/shirou/gopsutil/host" "github.com/shirou/gopsutil/load" "log" "net" ) type CpuLoad struct{} // cpu info func (CpuLoad) Name() string { return namespace + "_cpu_load" } func (CpuLoad) Scrape(ch chan<- prometheus.Metric) error { //hostinfo := GetHost() hostinfo, err := host.Info() cpuload, err := load.Avg() if err != nil { log.Printf("cpu load is not ,%v\n", err) return err } ch <- prometheus.MustNewConstMetric( //这里的label是固定标签 我们可以通过 NewDesc("cpu_load", "one", "cpu load", []string{"type"}, prometheus.Labels{"host": hostinfo.Hostname, "ip": GetIP()}), prometheus.GaugeValue, cpuload.Load1, //动态标签的值 可以有多个动态标签 "metrics", ) ch <- prometheus.MustNewConstMetric( NewDesc("cpu_load", "five", "cpu load", nil, nil), prometheus.GaugeValue, cpuload.Load5, ) ch <- prometheus.MustNewConstMetric( NewDesc("cpu_load", "fifteen", "cpu load", nil, nil), prometheus.GaugeValue, cpuload.Load15, ) return nil } // 获取网络信息 func GetIP() string { addrs, err := net.InterfaceAddrs() if err != nil { fmt.Println(err) return "" } for _, address := range addrs { // 检查ip地址判断是否回环地址 if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { if ipnet.IP.To4() != nil { //fmt.Println(ipnet.Mask) //fmt.Println(ipnet.IP) return ipnet.IP.String() } } } return "" }