...
1 package authserver
2
3 import (
4 "fmt"
5 "time"
6
7 "github.com/gin-gonic/gin"
8 "github.com/penglongli/gin-metrics/ginmetrics"
9 )
10
11 const (
12 metricPath = "/metrics"
13 maxLatencySeconds = 1
14 authRequests = "auth_request_total"
15 authOperations = "auth_query_total"
16 authSlowReQuests = "auth_slow_request_total"
17 authResponseTime = "auth_query_duration"
18 )
19
20 func useMetrics(r gin.IRoutes) {
21
22 m := ginmetrics.GetMonitor()
23 m.SetMetricPath(metricPath)
24 m.SetSlowTime(maxLatencySeconds)
25
26 _ = m.AddMetric(&ginmetrics.Metric{
27 Type: ginmetrics.Counter,
28 Name: authRequests,
29 Description: "count all auth requests.",
30 Labels: nil,
31 })
32
33 _ = m.AddMetric(&ginmetrics.Metric{
34 Type: ginmetrics.Counter,
35 Name: authOperations,
36 Description: "count all auth requests by status.",
37 Labels: []string{"status"},
38 })
39
40 _ = m.AddMetric(&ginmetrics.Metric{
41 Type: ginmetrics.Counter,
42 Name: authSlowReQuests,
43 Description: fmt.Sprintf("count all auth slow requests by status. max_lentency=%d sec.", maxLatencySeconds),
44 Labels: []string{"status"},
45 })
46
47 m.SetDuration([]float64{0.1, 0.3, 1.2, 5, 10})
48 _ = m.AddMetric(&ginmetrics.Metric{
49 Type: ginmetrics.Histogram,
50 Name: authResponseTime,
51 Description: "the time auth server took handle the request by status.",
52 Labels: []string{"status"},
53 Buckets: []float64{0.1, 0.3, 1.2, 5, 10},
54 })
55
56 m.Use(r)
57 }
58
59 func handleMetrics(success bool, start time.Time) {
60 latency := time.Since(start)
61
62 _ = ginmetrics.GetMonitor().GetMetric(authRequests).Inc(nil)
63
64 status := "verified"
65 if !success {
66 status = "denied"
67 }
68
69 labels := []string{status}
70
71
72 _ = ginmetrics.GetMonitor().GetMetric(authOperations).Inc(labels)
73
74
75 if int32(latency.Seconds()) > maxLatencySeconds {
76 _ = ginmetrics.GetMonitor().GetMetric(authSlowReQuests).Inc(labels)
77 }
78
79
80 _ = ginmetrics.GetMonitor().GetMetric(authResponseTime).Observe([]string{status}, latency.Seconds())
81 }
82
View as plain text