-
Notifications
You must be signed in to change notification settings - Fork 6
/
logger.go
56 lines (44 loc) · 1.16 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
48
49
50
51
52
53
54
55
56
package main
import (
"log"
"net/http"
"os"
"time"
)
// Logger is a middleware handler that logs HTTP call information.
type Logger struct {
// Logger inherits from log.Logger used to log messages with the Logger middleware
*log.Logger
next http.Handler
}
// newLogger returns a new Logger instance
func newLogger(next http.Handler) *Logger {
return &Logger{
Logger: log.New(os.Stdout, "[apimock] ", 3),
next: next,
}
}
type responseWriterRecorder struct {
http.ResponseWriter
status int
}
func (rr *responseWriterRecorder) WriteHeader(code int) {
rr.status = code
rr.ResponseWriter.WriteHeader(code)
}
func (rr *responseWriterRecorder) Write(b []byte) (int, error) {
if rr.status == 0 {
rr.status = 200
}
return rr.ResponseWriter.Write(b)
}
func (l *Logger) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
start := time.Now()
rr := &responseWriterRecorder{ResponseWriter: rw}
l.next.ServeHTTP(rr, req)
address := req.RemoteAddr
if realIP := req.Header.Get("X-REAL-IP"); realIP != "" {
address = realIP
}
l.Printf("%s %s %d %s in %v (%s)", req.Method, req.URL.Path, rr.status, http.StatusText(rr.status), time.Since(start), address)
}