-
Notifications
You must be signed in to change notification settings - Fork 17
/
logging_handler.go
37 lines (30 loc) · 893 Bytes
/
logging_handler.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
package handler
import (
"husniadil/gsm/util/logger"
"net/http"
"net/http/httptest"
"time"
)
func LoggingHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, req *http.Request) {
start := time.Now()
logger.Info("Request: %s %q", req.Method, req.URL.String())
res := httptest.NewRecorder()
next.ServeHTTP(res, req)
for k, v := range res.HeaderMap {
w.Header()[k] = v
}
w.WriteHeader(res.Code)
body := res.Body.String()
code := res.Code / 100
elapsed := time.Since(start).Seconds() * 1000
switch code {
case 2:
logger.Info("Response: %s %q returned %v and took %.0fms", req.Method, req.URL.String(), res.Code, elapsed)
default:
logger.Warn("Response: %s %q returned %v and took %.0fms with response body: %s", req.Method, req.URL.String(), res.Code, elapsed, body)
}
res.Body.WriteTo(w)
}
return http.HandlerFunc(fn)
}