/
log_record.go
64 lines (54 loc) · 1.38 KB
/
log_record.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
package main
import (
"net/http"
"time"
"go.uber.org/zap"
)
// LogRecord warps a http.ResponseWriter and records the status
type LogRecord struct {
http.ResponseWriter
status int
}
func (r *LogRecord) Write(p []byte) (int, error) {
return r.ResponseWriter.Write(p)
}
// WriteHeader overrides ResponseWriter.WriteHeader to keep track of the response code
func (r *LogRecord) WriteHeader(status int) {
r.status = status
r.ResponseWriter.WriteHeader(status)
}
// withHTTPLogging adds HTTP request logging to the Handler h
func withHTTPLogging(log *zap.Logger) func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
url := r.URL.String()
isMetric := url == "/metrics"
if !isMetric {
log.Info("REQ",
zap.String("ident", r.Host),
zap.String("method", r.Method),
zap.String("url", url),
)
}
start := time.Now()
record := &LogRecord{
ResponseWriter: w,
status: 200,
}
h.ServeHTTP(record, r)
level := log.Info
if record.status >= 500 {
level = log.Error
}
if !(isMetric && record.status == 200) {
level("RES",
zap.String("ident", r.Host),
zap.String("method", r.Method),
zap.String("url", url),
zap.Int("status_code", record.status),
zap.Duration("duration", time.Since(start)),
)
}
})
}
}