├── getSysInfo ├── getSysInfo.exe ├── README.md └── getSysInfo.go /getSysInfo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lifay9092/SysInfoRealTime/HEAD/getSysInfo -------------------------------------------------------------------------------- /getSysInfo.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lifay9092/SysInfoRealTime/HEAD/getSysInfo.exe -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SysInfoRealTime 2 | 实时监控服务器信息:OS、内存、CPU等信息,并生成JSON格式的日志文件 3 | 4 | ##### 学习一下Golang,语法不过关还在慢慢摸索 5 | 6 | 基于[gopsutil](https://github.com/shirou/gopsutil)写了一个可以在不同os环境定时运行的监控程序,可以定期记录该服务器配置、实时CPU、实时内存等信息。后期本人应用主要是通过Web方式采集并可视化多个服务器的性能信息,结合服务请求数据、提供服务器性能瓶颈和扩展的基础数据支撑,以下为生成的JSON格式文件样例(按日期生成Log文件) 7 | 8 | 9 | 10 | ![image.png](https://upload-images.jianshu.io/upload_images/17879100-3b6b37f040fd2ae2.png?imageMogr2/auto-orient/strip|imageView2/2/w/1200/format/webp) 11 | ![image.png](https://upload-images.jianshu.io/upload_images/17879100-243be2ea1915071a.png?imageMogr2/auto-orient/strip|imageView2/2/w/285/format/webp) 12 | 13 | 目前程序默认间隔时间为15秒,空置时间为每天21点-次日8点,需要调整的可以自行修改 14 | -------------------------------------------------------------------------------- /getSysInfo.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "github.com/shirou/gopsutil/cpu" 8 | "github.com/shirou/gopsutil/disk" 9 | "github.com/shirou/gopsutil/host" 10 | "github.com/shirou/gopsutil/mem" 11 | "os" 12 | "time" 13 | ) 14 | //获取内存信息 15 | func getMemInfo() (map[string]string) { 16 | memdata := make(map[string]string) 17 | 18 | v, _ := mem.VirtualMemory() 19 | 20 | total := handerUnit(v.Total,NUM_GB,"G") 21 | available := handerUnit(v.Available,NUM_GB,"G") 22 | used := handerUnit(v.Used,NUM_GB,"G") 23 | free := handerUnit(v.Free,NUM_GB,"G") 24 | userPercent := fmt.Sprintf("%.2f",v.UsedPercent) 25 | 26 | memdata["总量"] = total 27 | memdata["可用"] = available 28 | memdata["已使用"] = used 29 | memdata["空闲"] = free 30 | memdata["使用率"] = userPercent + "%" 31 | 32 | return memdata 33 | } 34 | //获取CPU信息 35 | func getCpuInfo(percent string) []map[string]string { 36 | cpudatas := []map[string]string{} 37 | 38 | infos, err := cpu.Info() 39 | if err != nil { 40 | fmt.Printf("get cpu info failed, err:%v", err) 41 | } 42 | for _, ci := range infos { 43 | cpudata := make(map[string]string) 44 | cpudata["型号"] = ci.ModelName 45 | cpudata["数量"] = fmt.Sprint(ci.Cores) 46 | cpudata["使用率"] = percent + "%" 47 | 48 | cpudatas = append(cpudatas, cpudata) 49 | } 50 | return cpudatas 51 | } 52 | //获取主机信息 53 | func getHostInfo() map[string]string { 54 | hostdata := make(map[string]string) 55 | 56 | hInfo, _ := host.Info() 57 | hostdata["主机名称"] = hInfo.Hostname 58 | hostdata["系统"] = hInfo.OS 59 | hostdata["平台"] = hInfo.Platform + "-" + hInfo.PlatformVersion + " " + hInfo.PlatformFamily 60 | hostdata["内核"] = hInfo.KernelArch 61 | 62 | return hostdata 63 | //fmt.Printf("host info:%v uptime:%v boottime:%v\n", hInfo, hInfo.Uptime, hInfo.BootTime) 64 | } 65 | // disk info 66 | func getDiskInfo() { 67 | parts, err := disk.Partitions(true) 68 | if err != nil { 69 | fmt.Printf("get Partitions failed, err:%v\n", err) 70 | return 71 | } 72 | for _, part := range parts { 73 | fmt.Printf("part:%v\n", part.String()) 74 | diskInfo, _ := disk.Usage(part.Mountpoint) 75 | fmt.Printf("disk info:used:%v free:%v\n", diskInfo.UsedPercent, diskInfo.Free) 76 | } 77 | 78 | ioStat, _ := disk.IOCounters() 79 | for k, v := range ioStat { 80 | fmt.Printf("%v:%v\n", k, v) 81 | } 82 | } 83 | 84 | const ( 85 | NUM_KB = 1000.0000 86 | NUM_MIB = 1000000.0000 87 | NUM_GB = 1000000000.0000 88 | ) 89 | 90 | func handerUnit(num uint64, numtype float64,typename string) (newnum string) { 91 | 92 | f :=fmt.Sprintf("%.2f", float64(num)/numtype) 93 | return f + typename 94 | } 95 | 96 | //处理日志 97 | func saveToLocalFile(filename string, data []byte) { 98 | //line := []byte("\n") 99 | //检查是否存在 存在则追加内容 100 | file,err := os.OpenFile(filename,os.O_RDWR,0666) 101 | 102 | if err != nil && os.IsNotExist(err) { 103 | //println("文件不存在")//需要加[] 104 | 105 | start := []byte("[") 106 | end := []byte("]") 107 | newdata := BytesCombine(start,data,end) 108 | 109 | file, _ = os.Create(filename) 110 | file.Write(newdata) 111 | file.Seek(-1,2) 112 | }else { 113 | //println("文件存在 追加") 114 | //fmt.Println(file.Seek(0, 2)) 115 | 116 | start := []byte(",") 117 | end := []byte("]") 118 | newdata := BytesCombine(start,data,end) 119 | 120 | file.Seek(-1,2) 121 | file.Write(newdata) 122 | } 123 | 124 | file.Close() 125 | } 126 | 127 | //BytesCombine 多个[]byte数组合并成一个[]byte 128 | func BytesCombine(pBytes ...[]byte) []byte { 129 | len := len(pBytes) 130 | s := make([][]byte, len) 131 | for index := 0; index < len; index++ { 132 | s[index] = pBytes[index] 133 | } 134 | sep := []byte("") 135 | return bytes.Join(s, sep) 136 | } 137 | 138 | func main(){ 139 | println("客户端监控任务开启...")//windows 140 | 141 | var logdate string 142 | // CPU使用率 143 | for { 144 | //限制检测时间 145 | nowdatetime := time.Now() 146 | hour := nowdatetime.Hour() 147 | if hour >= 21 || hour <8{//设置空置时间 148 | println("进入睡眠。。。") 149 | time.Sleep(time.Minute) 150 | continue 151 | } 152 | 153 | datas := make(map[string]interface{}) 154 | //获取内存使用率 同时定时 155 | percent, _ := cpu.Percent(time.Second * 14, false)//设置间隔时间 156 | 157 | nowtime := nowdatetime.Format("2006-01-02 15:04:05")//当前时间 158 | 159 | nowdate := nowdatetime.Format("2006-01-02") 160 | if logdate == "" || nowdate != logdate { 161 | logdate = nowdate 162 | } 163 | datas["当前时间"] = nowtime 164 | 165 | memdata := getMemInfo() 166 | datas["内存信息"] = memdata 167 | 168 | //getDiskInfo() 169 | 170 | hostdata := getHostInfo() 171 | datas["主机信息"] = hostdata 172 | 173 | cpudata := getCpuInfo(fmt.Sprintf("%.2f",percent[0])) 174 | datas["CPU信息"] = cpudata 175 | 176 | //写入文件 177 | jsonStr, err := json.Marshal(datas) 178 | 179 | if err != nil { 180 | fmt.Println("MapToJsonDemo err: ", err) 181 | } 182 | //println(time.Now().Format("2006-01-02 15:04:05")) 183 | saveToLocalFile(logdate + ".syslog",jsonStr) 184 | //fmt.Println(string(jsonStr)) 185 | } 186 | } --------------------------------------------------------------------------------