forked from semihalev/gin-stats
-
Notifications
You must be signed in to change notification settings - Fork 1
/
stats.go
56 lines (44 loc) · 1.45 KB
/
stats.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package stats
import (
"fmt"
"strings"
"time"
"github.com/gin-gonic/gin"
metrics "github.com/rcrowley/go-metrics"
)
const (
ginLatencyMetric = "gin.latency"
ginStatusMetric = "gin.status"
ginRequestMetric = "gin.request"
)
//Report from default metric registry
func Report() metrics.Registry {
return metrics.DefaultRegistry
}
//RequestStats middleware
func RequestStats() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
c.Next()
handlerName := strings.Replace(c.Request.URL.Path, "/", "-", -1)
handlerName = handlerName[1:len(handlerName)]
if len(handlerName) == 0 {
handlerName = "root"
}
// Requests Per Second (total and per-handler)
totalReq := metrics.GetOrRegisterMeter(ginRequestMetric, nil)
totalReq.Mark(1)
req := metrics.GetOrRegisterMeter(fmt.Sprintf("%s.%s", ginRequestMetric, handlerName), nil)
req.Mark(1)
// Latency (total and per-handler)
totalLatency := metrics.GetOrRegisterTimer(ginLatencyMetric, nil)
totalLatency.UpdateSince(start)
latency := metrics.GetOrRegisterTimer(fmt.Sprintf("%s.%s", ginLatencyMetric, handlerName), nil)
latency.UpdateSince(start)
// HTTP Status, e.g. 200, 404, 500 (total and per-handler)
totalStatus := metrics.GetOrRegisterMeter(fmt.Sprintf("%s.%d", ginStatusMetric, c.Writer.Status()), nil)
totalStatus.Mark(1)
status := metrics.GetOrRegisterMeter(fmt.Sprintf("%s.%s.%d", ginStatusMetric, handlerName, c.Writer.Status()), nil)
status.Mark(1)
}
}