forked from ant0ine/go-json-rest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
67 lines (58 loc) · 1.38 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
package rest
import (
"encoding/json"
"log"
"os"
"time"
)
// logMiddleware manages the Logger.
// It depends on request.Env["STATUS_CODE"] and request.Env["ELAPSED_TIME"].
type logMiddleware struct {
Logger *log.Logger
EnableLogAsJson bool
}
func (mw *logMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
// set a default Logger
if mw.Logger == nil {
mw.Logger = log.New(os.Stderr, "", log.LstdFlags)
}
return func(w ResponseWriter, r *Request) {
// call the handler
h(w, r)
mw.logResponseRecord(&responseLogRecord{
r.Env["STATUS_CODE"].(int),
r.Env["ELAPSED_TIME"].(*time.Duration),
r.Method,
r.URL.RequestURI(),
})
}
}
type responseLogRecord struct {
StatusCode int
ResponseTime *time.Duration
HttpMethod string
RequestURI string
}
func (mw *logMiddleware) logResponseRecord(record *responseLogRecord) {
if mw.EnableLogAsJson {
b, err := json.Marshal(record)
if err != nil {
panic(err)
}
mw.Logger.Printf("%s", b)
} else {
statusCodeColor := "0;32"
if record.StatusCode >= 400 && record.StatusCode < 500 {
statusCodeColor = "1;33"
} else if record.StatusCode >= 500 {
statusCodeColor = "0;31"
}
mw.Logger.Printf("\033[%sm%d\033[0m \033[36;1m%.2fms\033[0m %s %s",
statusCodeColor,
record.StatusCode,
float64(record.ResponseTime.Nanoseconds()/1e4)/100.0,
record.HttpMethod,
record.RequestURI,
)
}
}