2019-03-26 微信群讨论

来源:《Go 夜读》微信群 时间:未知

背景

先前由于公司这边要做一些基础指标的监控上报,因此之前在夜读群里和大家聊了下。经推荐最后使用了第三方库 gopsutil

今天我把之前查的资料重新翻了出来,大家有兴趣的可以看看。以备不时之需及学习一下

例子

package main

import (
	"time"
	"log"

	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/disk"
	"github.com/shirou/gopsutil/host"
	"github.com/shirou/gopsutil/load"
	"github.com/shirou/gopsutil/mem"
)

type StatusServer struct {
	Percent  StatusPercent
	CPU      []CPUInfo
	Mem      MemInfo
	Swap     SwapInfo
	Load     *load.AvgStat
	BootTime uint64
	Uptime   uint64
}
type StatusPercent struct {
	CPU  float64
	Disk float64
	Mem  float64
	Swap float64
}

type CPUInfo struct {
	ModelName string
	Cores     int32
}

type MemInfo struct {
	Total     uint64
	Used      uint64
	Available uint64
}

type SwapInfo struct {
	Total     uint64
	Used      uint64
	Available uint64
}

func main() {
	v, _ := mem.VirtualMemory()
	s, _ := mem.SwapMemory()
	c, _ := cpu.Info()
	cc, _ := cpu.Percent(time.Second, false)
	d, _ := disk.Usage("/")
	n, _ := host.Info()
	l, _ := load.Avg()
	ss := new(StatusServer)
	ss.Load = l
	ss.Uptime = n.Uptime
	ss.BootTime = n.BootTime
	ss.Percent.Mem = v.UsedPercent
	ss.Percent.CPU = cc[0]
	ss.Percent.Swap = s.UsedPercent
	ss.Percent.Disk = d.UsedPercent
	ss.CPU = make([]CPUInfo, len(c))
	for i, ci := range c {
		ss.CPU[i].ModelName = ci.ModelName
		ss.CPU[i].Cores = ci.Cores
	}
	ss.Mem.Total = v.Total
	ss.Mem.Available = v.Available
	ss.Mem.Used = v.Used
	ss.Swap.Total = s.Total
	ss.Swap.Available = s.Free
	ss.Swap.Used = s.Used

	log.Printf("Server: %+v", ss)
}

输出结果

2019/03/26 20:59:33 Server: &{
Percent:{CPU:46.38403990024938 Disk:77.4866172890781 Mem:67.66278743743896 Swap:95.16252790178571} 
CPU:[{ModelName:Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz Cores:2}] 
Mem:{Total:17179869184 Used:11624378368 Available:5555490816} 
Swap:{Total:7516192768 Used:7152599040 Available:363593728} 
Load:{"load1":4.28,"load5":3.37,"load15":3.21} 
BootTime:1550416891 
Uptime:3188282
}