/
accessLog.go
101 lines (91 loc) · 3.23 KB
/
accessLog.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
package server
import (
"fmt"
"github.com/felixge/httpsnoop"
"github.com/go-chi/chi/v5/middleware"
"github.com/prometheus/client_golang/prometheus"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"net/http"
"strconv"
"strings"
)
var DomainLabel = "domain"
var StatusLabel = "status"
// PrometheusRegistration wraps a prometheus registerer and corresponding registered types.
type PrometheusRegistration struct {
bytesSend *prometheus.CounterVec
statusCode *prometheus.CounterVec
}
// AccessMetricsRegister registrates the relevant prometheus types and returns a custom registration type
func AccessMetricsRegister(registerer prometheus.Registerer, prometheusNamespace string) (*PrometheusRegistration, error) {
var bytesSend = prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: prometheusNamespace,
Subsystem: "access",
Name: "egress_bytes",
Help: "Number of bytes send out from this application.",
}, []string{DomainLabel})
var statusCode = prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: prometheusNamespace,
Subsystem: "access",
Name: "http_statuscode",
Help: "HTTP Response status code.",
}, []string{DomainLabel, StatusLabel})
err := registerer.Register(bytesSend)
if err != nil {
return nil, fmt.Errorf("failed to register egress_bytes metric: %v", err)
}
err = registerer.Register(statusCode)
if err != nil {
return nil, fmt.Errorf("failed to register http_statuscode metric: %v", err)
}
return &PrometheusRegistration{
bytesSend: bytesSend,
statusCode: statusCode,
}, nil
}
// AccessMetricsHandler collects the bytes send out as well as the status codes as prometheus metrics and writes them
// to the registry. The registerer has to be prepared via the AccessMetricsRegister function.
func AccessMetricsHandler(next http.Handler, registration *PrometheusRegistration) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
m := httpsnoop.CaptureMetrics(next, w, r)
registration.statusCode.With(map[string]string{DomainLabel: r.Host, StatusLabel: strconv.Itoa(m.Code)}).Inc()
registration.bytesSend.With(map[string]string{DomainLabel: r.Host}).Add(float64(m.Written))
})
}
// AccessLogHandler returns a http.Handler that adds access-logging on the info level.
func AccessLogHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
m := httpsnoop.CaptureMetrics(next, w, r)
logEvent := log.Info()
requestId := r.Context().Value(middleware.RequestIDKey)
if requestId != nil {
logEvent = logEvent.Str("requestId", requestId.(string))
}
logEvent.Dict("httpRequest", zerolog.Dict().
Str("requestMethod", r.Method).
Str("requestUrl", getFullUrl(r)).
Int("status", m.Code).
Int64("responseSize", m.Written).
Str("userAgent", r.UserAgent()).
Str("remoteIp", r.RemoteAddr).
Str("referer", r.Referer()).
Str("latency", m.Duration.String())).
Msg("")
})
}
func getFullUrl(r *http.Request) string {
var sb strings.Builder
if r.TLS == nil {
sb.WriteString("http")
} else {
sb.WriteString("https")
}
sb.WriteString("://")
sb.WriteString(r.Host)
if !strings.HasPrefix(r.URL.Path, "/") {
sb.WriteString("/")
}
sb.WriteString(r.URL.Path)
return sb.String()
}