Prometheus监控Golang服务-最简单的办法!!!

Prometheus监控Golang-WEB_server页面

1.Golang

1.1 go.mod文件
#创建go mod文件[hyxr]
go mod init hy.com/m
#编写mod文件
module hy.com/m
go 1.17
require (
	github.com/gin-gonic/gin v1.7.4
	github.com/prometheus/client_golang v1.11.0 // indirect
	github.com/zsais/go-gin-prometheus v0.1.0
)
#执行即可下载配置文件中需要的包.
go mod tidy
1.2 main.go文件
root@mkky:/opt/hy/go# cat main.go
package main

import (
        "fmt"
        "github.com/gin-gonic/gin"
        "github.com/prometheus/client_golang/prometheus"
        "github.com/prometheus/client_golang/prometheus/promhttp"
        "net/http"
        "os/exec"
        "time"
)

#创建监控项,并且用标签的形式区分
var(
        customMonitor = prometheus.NewCounterVec(prometheus.CounterOpts{
    
    
                Name: "custom_monitor",
                Help: "custom monitor some data",
        },[]string{
    
    "msg","time","program"})
)

#初始化Prometheus模型
func init()  {
    
    
        prometheus.MustRegister(customMonitor)
}

func main() {
    
    
        r := gin.Default()
        mytime:=time.Now()
        ok,_:=exec.Command("/bin/bash","/usr/bin/get.sh").Output()
        r.GET("/", func(c *gin.Context) {
    
    
                c.JSON(http.StatusOK, gin.H{
    
    "msg":c.Request.RemoteAddr,"time":mytime,"program":string(ok)})
        })
        r.Use(func(c *gin.Context) {
    
    
                customMonitor.With(prometheus.Labels{
    
    "msg":c.Request.RemoteAddr,
                        "time":fmt.Sprintf("%v",mytime),
                        "program":string(ok)}).Inc()
        })
        r.GET("/metrics",prometheusHandler())
        r.Run(":8888")
}
func prometheusHandler() gin.HandlerFunc {
    
    
        h := promhttp.Handler()
        return func(c *gin.Context) {
    
    
                h.ServeHTTP(c.Writer, c.Request)
        }
}
#原代码
func index (c *gin.Context) {
    
    
        r:=c.Request
        mytime:=time.Now()
        ok,_:=exec.Command("/bin/bash","/usr/bin/get.sh").Output()
        c.JSON(http.StatusOK, gin.H{
    
    "msg":r.RemoteAddr,"time":mytime,"program":string(ok)})
}
#启动
go run main.go

2.Prometheus监控取值

#192.168.24.148:9090--Prometheus主界面[hyxr]

www.hyithack.com/www.linuxhy.top
www.hyithack.com/www.linuxhy.top

3.Node_exporter查看取值

3.1 Json格式页面

www.hyithack.com/www.linuxhy.top

3.2 metrics格式页面

www.hyithack.com/www.linuxhy.top

4.Grafana页面监控

4.1 折线图

custom_monitor

www.hyithack.com/www.linuxhy.top

4.2 表格展示图

custom_monitor

在这里插入图片描述

4.3 成品图

www.hyithack.com/www.linuxhy.top

猜你喜欢

转载自blog.csdn.net/HYXRX/article/details/120293024