-
Notifications
You must be signed in to change notification settings - Fork 178
/
logging.go
50 lines (44 loc) · 1.34 KB
/
logging.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
package middleware
import (
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/rs/zerolog"
)
// LoggingMiddleware creates a middleware which adds a logger interceptor to each request to log the request method, uri,
// duration and response code
func LoggingMiddleware(logger zerolog.Logger) mux.MiddlewareFunc {
return func(inner http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
// record star time
start := time.Now()
// modify the writer
respWriter := newResponseWriter(w)
// continue to the next handler
inner.ServeHTTP(respWriter, req)
log := logger.Info()
if respWriter.statusCode != http.StatusOK {
log = logger.Error()
}
log.Str("method", req.Method).
Str("uri", req.RequestURI).
Str("client_ip", req.RemoteAddr).
Str("user_agent", req.UserAgent()).
Dur("duration", time.Since(start)).
Int("response_code", respWriter.statusCode).
Msg("api")
})
}
}
// responseWriter is a wrapper around http.ResponseWriter and helps capture the response code
type responseWriter struct {
http.ResponseWriter
statusCode int
}
func newResponseWriter(w http.ResponseWriter) *responseWriter {
return &responseWriter{w, http.StatusOK}
}
func (rw *responseWriter) WriteHeader(code int) {
rw.statusCode = code
rw.ResponseWriter.WriteHeader(code)
}