forked from thoas/stats
-
Notifications
You must be signed in to change notification settings - Fork 1
/
stats.go
179 lines (152 loc) · 5.21 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package stats
import (
"fmt"
"log"
"net/http"
"os"
"runtime"
"sync"
"time"
)
type reformatURL func(string, string) string
type Stats struct {
mu sync.RWMutex
Uptime time.Time
Pid int
ResponseCounts map[string]int
TotalResponseTime time.Time
BadRoutes map[string]int
SlowRoutes map[string]SlowRoutesData
TimeoutRoutes map[string]int
Logger *log.Logger
Latency time.Duration
TimeoutLimit time.Duration
GetKey reformatURL
}
type SlowRoutesData struct {
Count int
AvgTime time.Duration
MaxTime time.Duration
}
func New(logger *log.Logger, allowedLatency time.Duration, timeout time.Duration, fn reformatURL) *Stats {
stats := &Stats{
Uptime: time.Now(),
Pid: os.Getpid(),
ResponseCounts: map[string]int{},
TotalResponseTime: time.Time{},
BadRoutes: map[string]int{},
SlowRoutes: map[string]SlowRoutesData{},
TimeoutRoutes: map[string]int{},
Logger: logger,
Latency: allowedLatency,
TimeoutLimit: timeout,
}
//This function can be used to properly group the routes (for example - cases where variable parameters exist in URLs)
if fn != nil {
stats.GetKey = fn
}
return stats
}
// Negroni compatible interface
func (mw *Stats) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if r.Method == "OPTIONS" {
next(w, r)
return
}
beginning, recorder := mw.Begin(w)
currentRoute := mw.GetKey(r.URL.Path, r.Method)
defer func(currentRoute string) {
if err := recover(); err != nil {
w.WriteHeader(http.StatusInternalServerError)
stack := make([]byte, 1024*8)
stack = stack[:runtime.Stack(stack, false)]
mw.EndWithStatus(beginning, currentRoute, http.StatusInternalServerError)
f := time.Now().UTC().String() + "PANIC: %s\n%s"
mw.Logger.Printf(f, err, stack)
} else {
mw.EndWithStatus(beginning, currentRoute, recorder.Status())
}
}(currentRoute)
next(recorder, r)
}
func (mw *Stats) Begin(w http.ResponseWriter) (time.Time, Recorder) {
start := time.Now()
writer := &RecorderResponseWriter{w, 200, 0}
return start, writer
}
func (mw *Stats) EndWithStatus(start time.Time, currentRoute string, status int) {
end := time.Now()
responseTime := end.Sub(start)
mw.mu.Lock()
defer mw.mu.Unlock()
statusCode := fmt.Sprintf("%d", status)
mw.ResponseCounts[statusCode]++
mw.TotalResponseTime = mw.TotalResponseTime.Add(responseTime)
if status >= http.StatusInternalServerError {
mw.BadRoutes[currentRoute] = mw.BadRoutes[currentRoute] + 1
}
if responseTime > mw.TimeoutLimit {
mw.TimeoutRoutes[currentRoute] = mw.TimeoutRoutes[currentRoute] + 1
} else if responseTime > mw.Latency {
if _, ok := mw.SlowRoutes[currentRoute]; !ok {
mw.SlowRoutes[currentRoute] = SlowRoutesData{Count: 1, AvgTime: responseTime, MaxTime: responseTime}
} else {
srd := mw.SlowRoutes[currentRoute]
if responseTime > srd.MaxTime {
srd.MaxTime = responseTime
}
srd.AvgTime = ((srd.AvgTime * time.Duration(srd.Count)) + responseTime) / (time.Duration(srd.Count + 1))
srd.Count += 1
mw.SlowRoutes[currentRoute] = srd
}
}
}
type data struct {
Pid int `json:"pid"`
UpTime string `json:"uptime"`
UpTimeSec float64 `json:"uptime_sec"`
Time string `json:"time"`
TimeUnix int64 `json:"unixtime"`
StatusCodeCount map[string]int `json:"status_code_count"`
Count int `json:"count"`
TotalResponseTime string `json:"total_response_time"`
TotalResponseTimeSec float64 `json:"total_response_time_sec"`
AverageResponseTime string `json:"average_response_time"`
AverageResponseTimeSec float64 `json:"average_response_time_sec"`
BadRoutes map[string]int `json:"bad_routes"`
SlowRoutes map[string]SlowRoutesData `json:"slow_routes"`
TimeoutRoutes map[string]int `json:timeout_routes`
}
func (mw *Stats) Data() *data {
mw.mu.RLock()
now := time.Now()
uptime := now.Sub(mw.Uptime)
count := 0
for _, current := range mw.ResponseCounts {
count += current
}
totalResponseTime := mw.TotalResponseTime.Sub(time.Time{})
averageResponseTime := time.Duration(0)
if count > 0 {
avgNs := int64(totalResponseTime) / int64(count)
averageResponseTime = time.Duration(avgNs)
}
r := &data{
Pid: mw.Pid,
UpTime: uptime.String(),
UpTimeSec: uptime.Seconds(),
Time: now.String(),
TimeUnix: now.Unix(),
StatusCodeCount: mw.ResponseCounts,
Count: count,
TotalResponseTime: totalResponseTime.String(),
TotalResponseTimeSec: totalResponseTime.Seconds(),
AverageResponseTime: averageResponseTime.String(),
AverageResponseTimeSec: averageResponseTime.Seconds(),
BadRoutes: mw.BadRoutes,
SlowRoutes: mw.SlowRoutes,
TimeoutRoutes: mw.TimeoutRoutes,
}
mw.mu.RUnlock()
return r
}