Skip to content
Snippets Groups Projects
Commit 1290c552 authored by Alena Petraki's avatar Alena Petraki :nail_care_tone1:
Browse files

Предложения по рефакторингу метрик

parent ff64e0fd
No related tags found
No related merge requests found
......@@ -8,6 +8,7 @@ package middleware
import (
"context"
"strings"
"git.perx.ru/perxis/perxis-go/pkg/items"
"git.perx.ru/perxis/perxis-go/pkg/metrics"
......@@ -17,6 +18,7 @@ import (
// metricsMiddleware implements items.Items that is instrumented with metrics
type metricsMiddleware struct {
serviceName string
requestMetrics *metrics.RequestMetrics
next items.Items
}
......@@ -25,6 +27,7 @@ type metricsMiddleware struct {
func MetricsMiddleware(requestMetrics *metrics.RequestMetrics) Middleware {
return func(next items.Items) items.Items {
return &metricsMiddleware{
serviceName: strings.ToLower("Items"), // эта строка для генерации по шаблону для всех сервисов, там ServiceName с заглавной буквы
requestMetrics: requestMetrics,
next: next,
}
......@@ -35,7 +38,8 @@ func MetricsMiddleware(requestMetrics *metrics.RequestMetrics) Middleware {
func (m metricsMiddleware) Aggregate(ctx context.Context, spaceId string, envId string, collectionId string, filter *items.Filter, options ...*items.AggregateOptions) (result map[string]interface{}, err error) {
timer := prometheus.NewTimer(m.requestMetrics.DurationSeconds.WithLabelValues("Aggregate"))
defer timer.ObserveDuration()
m.requestMetrics.Total.WithLabelValues("Aggregate").Inc()
m.requestMetrics.Total.With(prometheus.Labels{"service": m.serviceName, "method": "Aggregate"}).Inc() // тут как больше нравится. Мне нравится более явно
// m.requestMetrics.Total.WithLabelValues(m.serviceName, "Aggregate").Inc()
result, err = m.next.Aggregate(ctx, spaceId, envId, collectionId, filter, options...)
if err != nil {
m.requestMetrics.FailedTotal.WithLabelValues("Aggregate").Inc()
......
......@@ -4,12 +4,26 @@ import (
"github.com/prometheus/client_golang/prometheus"
)
var (
RequestLabels = []string{
"service",
"method",
}
)
type RequestMetrics struct {
Total *prometheus.CounterVec
FailedTotal *prometheus.CounterVec
DurationSeconds *prometheus.HistogramVec
}
// Пример использования:
// ...
// requestMetrics := metrics.NewRequestMetrics("content")
// s.Items = itemsMiddleware.MetricsMiddleware(requestMetrics)
// s.Collections = collectionsMiddleware.MetricsMiddleware(requestMetrics)
// ...
// NewRequestMetrics возвращает метрики для подсчета количества удачных/неудачных запросов, а так же длительности ответов.
//
// subsystem указывает подсистему, к которой принадлежат метрики.
......@@ -19,29 +33,26 @@ type RequestMetrics struct {
// Значения меток должны быть уникальными в рамках одной subsystem.
//
// Метрики записываются в prometheus.DefaultRegisterer
func NewRequestMetrics(subsystem string, durationBuckets []float64, labels ...string) *RequestMetrics {
if len(durationBuckets) == 0 {
durationBuckets = prometheus.DefBuckets
}
func NewRequestMetrics(subsystem string) *RequestMetrics {
metrics := &RequestMetrics{
Total: prometheus.NewCounterVec(prometheus.CounterOpts{
Subsystem: subsystem,
Name: "service_requests_total",
Help: "Количество запросов.",
}, []string{"method"}),
}, RequestLabels),
FailedTotal: prometheus.NewCounterVec(prometheus.CounterOpts{
Subsystem: subsystem,
Name: "service_requests_failed_total",
Help: "Количество запросов, вернувших ошибку.",
}, []string{"method"}),
}, RequestLabels),
DurationSeconds: prometheus.NewHistogramVec(prometheus.HistogramOpts{
Subsystem: subsystem,
Name: "service_request_duration_seconds",
Help: "Длительность обработки запроса.",
Buckets: durationBuckets,
}, []string{"method"}),
Buckets: prometheus.DefBuckets,
}, RequestLabels),
}
prometheus.WrapRegistererWith(GetLabelsFromKV(labels), prometheus.DefaultRegisterer).MustRegister(
prometheus.MustRegister(
metrics.Total,
metrics.FailedTotal,
metrics.DurationSeconds,
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment