-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging_handler.go
More file actions
48 lines (43 loc) · 1 KB
/
logging_handler.go
File metadata and controls
48 lines (43 loc) · 1 KB
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 handler
import (
log "github.com/sirupsen/logrus"
"net/http"
"time"
)
type statusWriter struct {
http.ResponseWriter
status int
length int
}
func (w *statusWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func (w *statusWriter) Write(b []byte) (int, error) {
if w.status == 0 {
w.status = 200
}
n, err := w.ResponseWriter.Write(b)
w.length += n
return n, err
}
func LogRequests(handler http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
sw := statusWriter{ResponseWriter: w}
handler.ServeHTTP(&sw, r)
duration := time.Now().Sub(start)
userAgent := r.Header.Get("User-Agent")
log.WithFields(log.Fields{
"Host": r.Host,
"RemoteAddr": r.RemoteAddr,
"Method": r.Method,
"RequestURI": r.RequestURI,
"Proto": r.Proto,
"Status": sw.status,
"Length": sw.length,
"UserAgent": userAgent,
"Duration": duration,
}).Info("RequestLogging")
}
}