-
Notifications
You must be signed in to change notification settings - Fork 53
/
http_logger.go
61 lines (51 loc) · 1.17 KB
/
http_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
52
53
54
55
56
57
58
59
60
61
package main
import (
"fmt"
"io"
"net/http"
"strings"
"time"
)
type LoggedRequest struct {
http.ResponseWriter
req *http.Request
output io.Writer
code int
start time.Time
finish time.Time
}
func (l *LoggedRequest) WriteHeader(code int) {
l.code = code
l.ResponseWriter.WriteHeader(code)
}
func (l *LoggedRequest) printLog() {
ip := l.req.RemoteAddr
if colon := strings.LastIndex(ip, ":"); colon > -1 {
ip = ip[:colon]
}
elapsed := l.finish.Sub(l.start).Nanoseconds() / 1000
finish := l.finish.Format("010206.150405")
fmt.Fprintf(l.output, "%s %s %s %s [%d] %dms\n", ip, finish, l.req.Method, l.req.RequestURI, l.code, elapsed)
}
type LoggingHandler struct {
handler http.Handler
output io.Writer
}
func (h *LoggingHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
entry := &LoggedRequest{
ResponseWriter: rw,
output: h.output,
req: r,
start: time.Now(),
}
entry.start = time.Now()
h.handler.ServeHTTP(entry, r)
entry.finish = time.Now()
entry.printLog()
}
func newLoggedHandler(handler http.Handler, output io.Writer) http.Handler {
return &LoggingHandler{
handler: handler,
output: output,
}
}