针对第一点,我用了一个库:github.com/shirou/gopsutil,里面有关于cpu使用率以及内存使用率的相关方法,比较简单。
代码如下:
func visor() {
for {
per, _ := cpu.Percent(time.Duration(config.GetConfig().Interval)*time.Second, false)
if per[0] > config.GetConfig().AlterLimit {
record(per[0])
}
}
}
func record(per float64) {
now := time.Now().Format("2006-01-02-15-04-05")
logFile := config.GetConfig().SnapPath + now + ".log"
f, _ := os.Create(logFile)
defer f.Close()
f.Write([]byte{‘\n‘})
f.Write([]byte("此时cpu占用率:" + strconv.FormatFloat(per, ‘f‘, 10, 64)))
f.Write([]byte{‘\n‘})
topCmd := exec.Command("top", "-H", "-n", "1", "-b")
topOutput, _ := topCmd.Output()
f.Write(topOutput)
}
使用方法示例如下:
# 后台启动
visor -start -config=./config/config.yaml -d
# 结束进程
visor -stop
完整代码请见:https://github.com/TomatoMr/visor。
欢迎关注我的公众号:onepunchgo,给我留言。
原文:https://blog.51cto.com/14664952/2489169