Golang获取系统资源信息

代码笔记 | 📅 2021-01-27 | golang

介绍

项目位置: https://github.com/shirou/gopsutil 文档位置:http://godoc.org/github.com/shirou/gopsutil

This is a port of psutil (https://github.com/giampaolo/psutil). The challenge is porting all psutil functions on some architectures.

意思是这个库移植自psutil,要实现其所有功能。

使用

talk is cheap

func SystemResources() map[string]interface{} {
    result := map[string]interface{}{}
    percent, _ := cpu.Percent(time.Second*3, true)
    result["cpu_used_percent"] = percent
    memInfo, _ := mem.VirtualMemory()
    result["memory_used_percent"] = memInfo.UsedPercent

    // 磁盘
    disks := []map[string]interface{}{}
    parts, _ := disk.Partitions(true)
    for _, part := range parts {
        if strings.HasPrefix(part.Device, "/dev/") {
            usage, _ := disk.Usage(part.Mountpoint)
            disks = append(disks, map[string]interface{}{"device": part.Device, "mount_point": part.Mountpoint, "used_percent": usage.UsedPercent, "inodes_used_percent": usage.InodesUsedPercent})
        }
    }
    result["disks"] = disks

    // 网络
    interfaces, _ := net.IOCounters(true)
    nets := []map[string]interface{}{}
    for _, inte := range interfaces {
        nets = append(nets, map[string]interface{}{"name": inte.Name, "bytes_sent": inte.BytesSent, "bytes_recv": inte.BytesRecv})
    }
    result["net"] = nets
    return result
}

上述代码将返回如下数据:

{
    "cpu_used_percent": [
        7.046979865786559,
        4.304635761596584,
        2.01342281884848
    ],
    "disks": [
        {
            "device": "/dev/sda1",
            "inodes_used_percent": 6.301271950879583,
            "mount_point": "/",
            "used_percent": 19.380184817204057
        }
    ],
    "memory_used_percent": 41.11186087644503,
    "net": [
        {
            "bytes_recv": 6035882499,
            "bytes_sent": 6035882499,
            "name": "lo"
        },
        {
            "bytes_recv": 897458846,
            "bytes_sent": 5788731489,
            "name": "eth0"
        },
        {
            "bytes_recv": 404561,
            "bytes_sent": 69195902,
            "name": "docker0"
        }
    ]
}

需要注意的是

在获取 CPU 使用率时,需要一个时间参数。实际上CPU使用率统计的是指定时间范围内的CPU平均使用率。这个操作并不会直接返回数据,而是会等待参数指定的时间之后在返回。

其它

这个库功能多,我上面仅做个记录。其他功能可以参考文档 http://godoc.org/github.com/shirou/gopsutil

Enjoy~