-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
48 lines (42 loc) · 1.22 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
package middleware
import (
"net/http"
"time"
"github.com/felixge/httpsnoop"
"github.com/fredbi/go-trace/log"
"go.uber.org/zap"
)
// LogRequests provides a middleware that logs http requests with a tracing-aware logger Factory.
func LogRequests(lf log.Factory) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
start := time.Now()
lg := lf.For(r.Context())
status := http.StatusOK
rw = httpsnoop.Wrap(rw, httpsnoop.Hooks{
WriteHeader: func(next httpsnoop.WriteHeaderFunc) httpsnoop.WriteHeaderFunc {
// will update the trace status when the chain of middlewares has completed
return func(code int) {
status = code
next(code)
}
},
})
defer func() {
lg.Info(
"http request",
zap.String("scheme", r.URL.Scheme),
zap.Int("status", status),
zap.String("method", r.Method),
zap.String("uri", r.RequestURI),
zap.Bool("tls", r.TLS != nil),
zap.String("protocol", r.Proto),
zap.String("host", r.Host),
zap.String("remote_addr", r.RemoteAddr),
zap.Duration("elapsed", time.Since(start)),
)
}()
next.ServeHTTP(rw, r)
})
}
}