引言
GO语言本身拥有极强的性能,非常适合做一些后端的数据采集管理以及运维系统。
其中会面临对当前系统信息的采集,我在这里使用的是GO的工具包 gopsutil
python 上收集系统信息的著名模块是 psutil
使用
安装:
go get github.com/shirou/gopsutil
采集CPU相关信息
import "github.com/shirou/gopsutil/cpu"
// cpu info
func getCpuInfo() {
cpuInfos, err := cpu.Info()
if err != nil {
fmt.Printf("get cpu info failed, err:%v", err)
}
for _, ci := range cpuInfos {
fmt.Println(ci)
}
// CPU使用率
for {
percent, _ := cpu.Percent(time.Second, false)
fmt.Printf("cpu percent:%v\n", percent)
}
}
获取CPU负载信息
import "github.com/shirou/gopsutil/load"
func getCpuLoad() {
info, _ := load.Avg()
fmt.Printf("%v\n", info)
}
获取Memory信息
import "github.com/shirou/gopsutil/mem"
// mem info
func getMemInfo() {
memInfo, _ := mem.VirtualMemory()
fmt.Printf("mem info:%v\n", memInfo)
}
获取 Host信息
import "github.com/shirou/gopsutil/host"
// host info
func getHostInfo() {
hInfo, _ := host.Info()
fmt.Printf("host info:%v uptime:%v boottime:%v\n", hInfo, hInfo.Uptime, hInfo.BootTime)
}
获取Disk信息
import "github.com/shirou/gopsutil/disk"
// disk info
func getDiskInfo() {
parts, err := disk.Partitions(true)
if err != nil {
fmt.Printf("get Partitions failed, err:%v\n", err)
return
}
for _, part := range parts {
fmt.Printf("part:%v\n", part.String())
diskInfo, _ := disk.Usage(part.Mountpoint)
fmt.Printf("disk info:used:%v free:%v\n", diskInfo.UsedPercent, diskInfo.Free)
}
ioStat, _ := disk.IOCounters()
for k, v := range ioStat {
fmt.Printf("%v:%v\n", k, v)
}
}
获取net IO信息
import "github.com/shirou/gopsutil/net"
func getNetInfo() {
info, _ := net.IOCounters(true)
for index, v := range info {
fmt.Printf("%v:%v send:%v recv:%v\n", index, v, v.BytesSent, v.BytesRecv)
}
}