-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
51 lines (43 loc) · 920 Bytes
/
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
48
49
50
51
package main
import (
"log"
"net/http"
"time"
)
type loggedResponseWriter struct {
http.ResponseWriter
status int
size int
}
func logger(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
lrw := newLoggedResponseWriter(w)
h.ServeHTTP(lrw, r)
log.Println(
r.RemoteAddr,
start.UTC().Format(time.RFC1123Z),
r.Method,
r.URL.Path,
r.Proto,
time.Since(start).String(),
r.UserAgent(),
lrw.status,
lrw.size,
)
})
}
func (c *loggedResponseWriter) WriteHeader(status int) {
c.status = status
c.ResponseWriter.WriteHeader(status)
}
func (c *loggedResponseWriter) Write(b []byte) (int, error) {
size, err := c.ResponseWriter.Write(b)
c.size += size
return size, err
}
func newLoggedResponseWriter(w http.ResponseWriter) *loggedResponseWriter {
return &loggedResponseWriter{
ResponseWriter: w,
}
}