Implement a simple monitoring tool with golang

The background is like this. Once my server hung up suddenly because the CPU usage was too high, but I didn't know which process caused it. So I wanted to find a monitoring tool to monitor my machine. I hope this tool is simple enough, without complicated configuration, out of the box, can monitor when the CPU load is too high, what happened and what process was causing The problem. It is a pity that I did not find such a tool (please let me know if there is such a convenient tool), but I really do not want to give the server a very heavy monitoring system. So, I decided to write a tool myself. The idea is as follows:

  1. Check the CPU occupancy rate every once in a while, and when it exceeds the set percentage, trigger the recording;
  2. Invoke the top command, arrange the CPU occupancy from high to low, record the output to a file, and the file is commanded by time;
  3. The program can run in the background.

For the first point, I used a library: github.com/shirou/gopsutil, which has related methods about CPU usage and memory usage, which is relatively simple.

code show as below:

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)
}

Examples of usage methods are as follows:

# 后台启动
visor -start -config=./config/config.yaml -d
# 结束进程
visor -stop

For the complete code, please see: https://github.com/TomatoMr/visor.


Welcome to pay attention to my public number: onepunchgo, leave me a message.

image

Published 20 original articles · Likes0 · Visits 757

Guess you like

Origin blog.csdn.net/qq_31362439/article/details/105666137