forked from go-martini/martini
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
47 lines (38 loc) · 1.03 KB
/
logger.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
package martini
import (
"log"
"net/http"
"time"
)
// Logger returns a middleware handler that logs the request as it goes in and the response as it goes out.
func Logger() Handler {
return func(res http.ResponseWriter, req *http.Request, c Context, log *log.Logger) {
start := time.Now()
log.Printf("\033[32;1mStarted %s %s\033[0m\n", req.Method, req.URL.Path)
rl := &responseLogger{res, 200, 0}
c.MapTo(rl, (*http.ResponseWriter)(nil))
c.Next()
log.Printf("Completed %v %s in %v\n", rl.status, http.StatusText(rl.status), time.Now().Sub(start))
}
}
type responseLogger struct {
w http.ResponseWriter
status int
size int
}
func (l *responseLogger) Header() http.Header {
return l.w.Header()
}
func (l *responseLogger) Write(b []byte) (int, error) {
if l.status == 0 {
// The status will be StatusOK if WriteHeader has not been called yet
l.status = http.StatusOK
}
size, err := l.w.Write(b)
l.size += size
return size, err
}
func (l *responseLogger) WriteHeader(s int) {
l.w.WriteHeader(s)
l.status = s
}