-
Notifications
You must be signed in to change notification settings - Fork 3
/
httplog.go
96 lines (78 loc) · 1.65 KB
/
httplog.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
package httplog
import (
"net/http"
"time"
"github.com/apex/log"
)
// New middleware wrapping `h`.
func New(h http.Handler) *Logger {
return &Logger{Handler: h}
}
// Logger middleware wrapping Handler.
type Logger struct {
http.Handler
}
// wrapper to capture status.
type wrapper struct {
http.ResponseWriter
http.Flusher
http.CloseNotifier
written int
status int
}
// WriteHeader wrapper to capture status code.
func (w *wrapper) WriteHeader(code int) {
w.status = code
w.ResponseWriter.WriteHeader(code)
}
// Write wrapper to capture response size.
func (w *wrapper) Write(b []byte) (int, error) {
n, err := w.ResponseWriter.Write(b)
w.written += n
return n, err
}
// Flush implementation.
func (w *wrapper) Flush() {
if w.Flusher != nil {
w.Flusher.Flush()
}
}
// ServeHTTP implementation.
func (l *Logger) ServeHTTP(w http.ResponseWriter, r *http.Request) {
start := time.Now()
res := &wrapper{
ResponseWriter: w,
written: 0,
status: 200,
}
if f, ok := w.(http.Flusher); ok {
res.Flusher = f
}
if c, ok := w.(http.CloseNotifier); ok {
res.CloseNotifier = c
}
ctx := log.WithFields(log.Fields{
"url": r.RequestURI,
"method": r.Method,
"remoteAddr": r.RemoteAddr,
})
ctx.Info("request")
l.Handler.ServeHTTP(res, r)
ctx = ctx.WithFields(log.Fields{
"status": res.status,
"size": res.written,
"duration": ms(time.Since(start)),
})
switch {
case res.status >= 500:
ctx.Error("response")
case res.status >= 400:
ctx.Warn("response")
default:
ctx.Info("response")
}
}
// ms returns the duration in milliseconds.
func ms(d time.Duration) int {
return int(d / time.Millisecond)
}