-
Notifications
You must be signed in to change notification settings - Fork 1
/
log.go
75 lines (60 loc) · 1.48 KB
/
log.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/golang/glog"
)
const (
logFmt = "%s \"%s %d %d\" %f"
)
type logRecord struct {
http.ResponseWriter
ip string
method, uri, protocol string
status int
responseBytes int64
elapsedTime time.Duration
}
func (r *logRecord) Log() {
requestLine := fmt.Sprintf("%s %s %s", r.method, r.uri, r.protocol)
glog.Infof(logFmt, r.ip, requestLine, r.status, r.responseBytes, r.elapsedTime.Seconds())
glog.Flush()
}
func (r *logRecord) Write(p []byte) (int, error) {
written, err := r.ResponseWriter.Write(p)
r.responseBytes += int64(written)
return written, err
}
func (r *logRecord) WriteHeader(status int) {
r.status = status
r.ResponseWriter.WriteHeader(status)
}
type loggingHandler struct {
handler http.Handler
}
func NewLoggingHandler(handler http.Handler) http.Handler {
return &loggingHandler{
handler: handler,
}
}
func (h *loggingHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
startTime := time.Now()
clientIP := r.RemoteAddr
if colon := strings.LastIndex(clientIP, ":"); colon != -1 {
clientIP = clientIP[:colon]
}
record := &logRecord{
ResponseWriter: rw,
ip: clientIP,
method: r.Method,
uri: r.RequestURI,
protocol: r.Proto,
status: http.StatusOK,
elapsedTime: time.Duration(0),
}
h.handler.ServeHTTP(record, r)
record.elapsedTime = time.Now().Sub(startTime)
record.Log()
}