-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrequest_logger.go
More file actions
49 lines (42 loc) · 1.03 KB
/
Copy pathrequest_logger.go
File metadata and controls
49 lines (42 loc) · 1.03 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
49
package gomw
import (
"fmt"
"log"
"net/http"
"os"
"time"
)
type logger interface {
Println(...interface{})
}
type requestLog struct {
start time.Time
end time.Time
r *http.Request
status int
}
func (rl *requestLog) String() string {
//TODO: could log status if its negroni.ResponseWriter
return fmt.Sprintf(`{"method: %s, url: %s, status: %d, requested_at: %v, response_at: %v, duration_ms: %v}`,
rl.r.Method, rl.r.URL.Path, rl.status, rl.start.Format(time.RFC3339), rl.end.Format(time.RFC3339), rl.end.Sub(rl.start))
}
func RequestLogger(next http.Handler, optloggers ...logger) http.HandlerFunc {
var clogger logger
if len(optloggers) > 0 {
clogger = optloggers[0]
} else {
clogger = log.New(os.Stdout, "", 0)
}
mw := func(w http.ResponseWriter, r *http.Request) {
rl := &requestLog{}
rl.start = time.Now()
rw := NewResponseWriter(w)
time.Sleep(time.Second)
next.ServeHTTP(rw, r)
rl.end = time.Now()
rl.r = r
rl.status = rw.StatusCode
clogger.Println(rl.String())
}
return http.HandlerFunc(mw)
}