Hits

golang集成grafana监控系统

首先用golang获得电脑CPU信息

  • grafana_demo.go
package main

import (
    "time"
    "math"
    "math/rand"
    "log"
    "github.com/christophberger/grada"
)

func newFakeDataFunc(max int, volatility float64, responseTime int) func() float64 {
    value := rand.Float64()
    return func() float64 {
        time.Sleep(time.Duration(responseTime) * time.Millisecond) // simulate response time
        rnd := 2 * (rand.Float64() - 0.5)
        change := volatility * rnd
        change += (0.5 - value) * 0.1
        value += change
        return math.Max(0, value*float64(max))
    }
}

func main() {
    dash := grada.GetDashboard()
    CPU1metric, err := dash.CreateMetric("CPU1", 5*time.Minute, time.Second)
    if err != nil {
        log.Fatalln(err)
    }
    CPU2metric, err := dash.CreateMetricWithBufSize("CPU2", 300)
    if err != nil {
        log.Fatalln(err)
    }
    CPU1stats := newFakeDataFunc(100, 0.2, 1000)
    CPU2stats := newFakeDataFunc(100, 0.1, 1000)
    trading := func(metric *grada.Metric, dataFunc func() float64) {
        for {
            metric.Add(dataFunc())
        }
    }
    go trading(CPU1metric, CPU1stats)
    go trading(CPU2metric, CPU2stats)

    select {}
}
  • 运行grafana_demo.go
$ go run grafana_demo.go

安装grafana

  • mac
$ brew install grafana 
  • install grafana simple json plugin
$ grafana-cli plugins install grafana-simple-json-datasource
  • run grafana and configuration

  • add data source and configuration

  • add a dashboard

    • first set time range that this dashboard requests from our source
    • set zoom out “last 5 minutes”
    • add a gragh and click panel title to edit
    • select metric and select CPU1 and CPU2

https://img.lg1024.com/blog%2Fimg%2Fgrafana-golang.png

Congrats! Your personal dashboard is up and running.

本文链接:参与评论 »

--EOF--

提醒:本文最后更新于 370 天前,文中所描述的信息可能已发生改变,请谨慎使用。

Comments