【GO】26. golang iris prometheus grafana 监控

1.引入包

go get github.com/prometheus/client_golang

2.代码

初始化prometheus

package common

import (
	"github.com/kataras/iris/context"
	"github.com/prometheus/client_golang/prometheus"
	"strconv"
	"time"
)

// 接口访问量统计
var HttpServerCounterVec *prometheus.CounterVec
// 接口相应时间统计
var HttpServerTimerVec *prometheus.HistogramVec

// 初始化prometheus(main函数调用此函数)
func InitPrometheus() {
	constLabels := map[string]string{"service": "iris-gateway", "env": "test", "host": "0.0.0.0"}

	HttpServerTimerVec = prometheus.NewHistogramVec(
		prometheus.HistogramOpts{
			Name:        "http_request_duration_seconds",
			Help:        "How long it took to process the HTTP request, partitioned by status code, method and HTTP path.",
			ConstLabels: constLabels,
			Buckets:     []float64{0.3, 1.2, 5.0},
		},
		[]string{"code", "method", "path"},
	)

	HttpServerCounterVec = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name:        "http_requests_total",
			Help:        "How many HTTP requests processed, partitioned by status code, method and HTTP path.",
			ConstLabels: constLabels,
		},
		[]string{"code", "method", "path"},
	)

	prometheus.MustRegister(HttpServerTimerVec, HttpServerCounterVec)
}

// iris中间件metrics统计
func HttpInterceptor(ctx context.Context) {
	start := time.Now()
	ctx.Next()

	r := ctx.Request()
	statusCode := strconv.Itoa(ctx.GetStatusCode())
	duration := float64(time.Since(start).Nanoseconds()) / 1000000000
	labels := []string{statusCode, r.Method, r.URL.Path}

	HttpServerCounterVec.WithLabelValues(labels...).Inc()
	HttpServerTimerVec.WithLabelValues(labels...).Observe(duration)
}

路径添加metrics

func (r *router) RegHttpHandler(app *iris.Application) {
        // metrics中间件
	app.Use(common.HttpInterceptor)
	app.Any("/health", ctrl.Health)

	app.Options("/{route:path}", middleware.CrossDomain)
        // metrics路径注册
	app.Get("/metrics", http.UnGzip, iris.FromStd(promhttp.Handler()))

	// user group
	userParty := app.Party("/user")
	{
		userParty.Post("/login", ctrl.User.Login)
	}

	// user group
	kafkaParty := app.Party("/kafka")
	{
		kafkaParty.Post("/push", ctrl.Message.PushKafkaMessage)
	}

	// test grpc group
	testGrpcParty := app.Party("/test")
	{
		testGrpcParty.Post("/grpc/push", ctrl.TestGrpc.Push)
	}
}

3.启动项目查看默认数据

4.Grafana添加模版

点击量:increase(http_requests_total{service="iris-gateway"}[5m])

接口相应时间:rate(http_request_duration_seconds_sum[5m])/rate(http_request_duration_seconds_count[5m])*1000

猜你喜欢

转载自blog.csdn.net/chen_peng7/article/details/108757810