-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathstatsd.go
66 lines (52 loc) · 1.52 KB
/
statsd.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
package middleware
import (
"net/http"
"strings"
"fmt"
"regexp"
"github.com/sirupsen/logrus"
"gopkg.in/alexcesaro/statsd.v2"
)
// Statsd is statsd metrics middleware.
type Statsd struct {
logger *logrus.Logger
client *statsd.Client
withLog bool
}
// NewStatsd construct Statsd.
func NewStatsd(logger *logrus.Logger, client *statsd.Client, withLog bool) *Statsd {
return &Statsd{
logger: logger,
client: client,
withLog: withLog,
}
}
// RegisterMetrics send metrics to statsd
func (s *Statsd) RegisterMetrics(handler http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
path := req.URL.Path
handlerName := prepareHandlerName(path)
requestTimer := s.client.NewTiming()
lrw := &LoggedResponseWriter{responseWriter: resp}
handler.ServeHTTP(lrw, req)
requestTimer.Send(fmt.Sprintf(
"request.%v.%v.%v.request_time",
req.Method,
lrw.Status(),
handlerName,
))
if s.withLog {
//Example: 200 POST /rec/ (127.0.0.1) 1.460s
s.logger.Infof("%v %v %v (%v) %.3fs",
lrw.Status(), req.Method, path, req.RemoteAddr, requestTimer.Duration().Seconds())
}
})
}
func prepareHandlerName(name string) string {
// todo: часть одного метода проебываем, но пока забьем на это
r := regexp.MustCompile("(/session|/element|/window|/cookie|/attribute|/equals|/css|/key)(/[^/]*)")
name = r.ReplaceAllString(name, "$1")
name = strings.Trim(name, "/")
name = strings.Replace(name, "/", "_", -1)
return name
}