/
middleware.go
66 lines (56 loc) · 1.56 KB
/
middleware.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"
"time"
"go.uber.org/zap"
)
// AddLogger logs request/response pair
func AddLogger(logger *zap.Logger, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// We do not want to be spammed by Kubernetes health check.
// Do not log Kubernetes health check.
// You can change this behavior as you wish.
if r.Header.Get("X-Liveness-Probe") == "Healthz" {
h.ServeHTTP(w, r)
return
}
id := GetReqID(ctx)
// Prepare fields to log
var scheme string
if r.TLS != nil {
scheme = "https"
} else {
scheme = "http"
}
proto := r.Proto
method := r.Method
remoteAddr := r.RemoteAddr
userAgent := r.UserAgent()
uri := strings.Join([]string{scheme, "://", r.Host, r.RequestURI}, "")
// Log HTTP request
logger.Debug("request started",
zap.String("request-id", id),
zap.String("http-scheme", scheme),
zap.String("http-proto", proto),
zap.String("http-method", method),
zap.String("remote-addr", remoteAddr),
zap.String("user-agent", userAgent),
zap.String("uri", uri),
)
t1 := time.Now()
h.ServeHTTP(w, r)
// Log HTTP response
logger.Debug("request completed",
zap.String("request-id", id),
zap.String("http-scheme", scheme),
zap.String("http-proto", proto),
zap.String("http-method", method),
zap.String("remote-addr", remoteAddr),
zap.String("user-agent", userAgent),
zap.String("uri", uri),
zap.Float64("elapsed-ms", float64(time.Since(t1).Nanoseconds())/1000000.0),
)
})
}