From 9597798ebc7034af8b026e644b7bd7c746d1eda7 Mon Sep 17 00:00:00 2001 From: Thomas Roehl Date: Thu, 18 Mar 2021 18:01:59 +0100 Subject: [PATCH] memavg collector in Go --- collectors/memavg/read_memavg.go | 48 ++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100755 collectors/memavg/read_memavg.go diff --git a/collectors/memavg/read_memavg.go b/collectors/memavg/read_memavg.go new file mode 100755 index 0000000..9590878 --- /dev/null +++ b/collectors/memavg/read_memavg.go @@ -0,0 +1,48 @@ +package main +import ( + "strings" + "io/ioutil" + "fmt" + "time" + "os" + "strconv" + ) + +func main() { + t := time.Now() + hostname, err := os.Hostname() + if err != nil { + fmt.Println("#", err) + os.Exit(1) + } + hostname = strings.Split(hostname, ".")[0] + data, err := ioutil.ReadFile("/proc/meminfo") + if err != nil { + fmt.Println("#", err) + os.Exit(1) + return + } + lines := strings.Split(string(data), "\n") + for _, l := range lines { + if strings.HasPrefix(l, "MemTotal") { + f := strings.Fields(l) + v, err := strconv.ParseInt(f[1], 10, 0) + if err == nil { + fmt.Printf("mem_total,hostname=%s value=%v %v\n", hostname, v*1024, t.UnixNano()) + } + } else if strings.HasPrefix(l, "MemAvailable") { + f := strings.Fields(l) + v, err := strconv.ParseInt(f[1], 10, 0) + if err == nil { + fmt.Printf("mem_avail,hostname=%s value=%v %v\n", hostname, v*1024, t.UnixNano()) + } + } else if strings.HasPrefix(l, "MemFree") { + f := strings.Fields(l) + v, err := strconv.ParseInt(f[1], 10, 0) + if err == nil { + fmt.Printf("mem_free,hostname=%s value=%v %v\n", hostname, v*1024, t.UnixNano()) + } + } + } + return +}