1. Paquete de importación
go get github.com/prometheus/client_golang
2. Código
Inicializar prometeo
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)
}
Agregar métricas a la ruta
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. Inicie el proyecto para ver los datos predeterminados
4. Agrega plantillas a Grafana
Visitas: aumento (http_requests_total{service="iris-gateway"}[5m])
Tiempo de respuesta de la interfaz: rate(http_request_duration_seconds_sum[5m])/rate(http_request_duration_seconds_count[5m])*1000