...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package metrics
17
18 import (
19 "strconv"
20 "time"
21
22 "github.com/gin-gonic/gin"
23 "github.com/prometheus/client_golang/prometheus"
24 )
25
26 const chaosDashboardSubsystem = "chaos_dashboard"
27
28
29 type ChaosDashboardMetricsCollector struct {
30 httpRequestDuration *prometheus.HistogramVec
31 }
32
33
34 func NewChaosDashboardMetricsCollector(engine *gin.Engine, registry *prometheus.Registry) *ChaosDashboardMetricsCollector {
35 collector := &ChaosDashboardMetricsCollector{
36 httpRequestDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
37 Subsystem: chaosDashboardSubsystem,
38 Name: "http_request_duration_seconds",
39 Help: "Time histogram for each HTTP query",
40 }, []string{"path", "method", "status"}),
41 }
42
43 engine.Use(collector.ginMetricsCollector())
44 registry.MustRegister(collector)
45
46 return collector
47 }
48
49
50 func (collector *ChaosDashboardMetricsCollector) Describe(ch chan<- *prometheus.Desc) {
51 collector.httpRequestDuration.Describe(ch)
52 }
53
54
55 func (collector *ChaosDashboardMetricsCollector) Collect(ch chan<- prometheus.Metric) {
56 collector.httpRequestDuration.Collect(ch)
57 }
58
59 func (collector *ChaosDashboardMetricsCollector) ginMetricsCollector() gin.HandlerFunc {
60 return func(ctx *gin.Context) {
61 begin := time.Now()
62
63 ctx.Next()
64
65 collector.httpRequestDuration.WithLabelValues(ctx.FullPath(), ctx.Request.Method, strconv.Itoa(ctx.Writer.Status())).
66 Observe(time.Since(begin).Seconds())
67 }
68 }
69