-
Notifications
You must be signed in to change notification settings - Fork 325
/
timelog.go
103 lines (89 loc) · 2.61 KB
/
timelog.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package timelog
import (
"context"
"fmt"
"net/http"
"os"
"strconv"
"time"
"github.com/vouch/vouch-proxy/pkg/response"
log "github.com/Sirupsen/logrus"
isatty "github.com/mattn/go-isatty"
)
var (
useColor = false
green = string([]byte{27, 91, 57, 55, 59, 52, 50, 109})
white = string([]byte{27, 91, 57, 48, 59, 52, 55, 109})
yellow = string([]byte{27, 91, 57, 55, 59, 52, 51, 109})
red = string([]byte{27, 91, 57, 55, 59, 52, 49, 109})
blue = string([]byte{27, 91, 57, 55, 59, 52, 52, 109})
magenta = string([]byte{27, 91, 57, 55, 59, 52, 53, 109})
cyan = string([]byte{27, 91, 57, 55, 59, 52, 54, 109})
reset = string([]byte{27, 91, 48, 109})
req = int64(0)
avgLatency = int64(0)
)
func init() {
if isatty.IsTerminal(os.Stdout.Fd()) {
useColor = true
}
// useColor = false
}
// TimeLog records how long it takes to process the http request and produce the response (latency)
func TimeLog(nextHandler http.Handler) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
log.Debugf("Request received : %v", r)
start := time.Now()
// make the call
v := response.CaptureWriter{w, 0}
ctx := context.Background()
nextHandler.ServeHTTP(&v, r.WithContext(ctx))
// Stop timer
end := time.Now()
latency := end.Sub(start)
req++
avgLatency = avgLatency + ((int64(latency) - avgLatency) / req)
log.Debugf("Request handled successfully: %v", v.GetStatusCode())
var statusCode = v.GetStatusCode()
path := r.URL.Path
host := r.Host
referer := r.Header.Get("Referer")
clientIP := r.RemoteAddr
method := r.Method
log.WithFields(log.Fields{
"statusCode": statusCode,
"request": req,
"latency": fmt.Sprintf("%10v", time.Duration(latency)),
"avgLatency": fmt.Sprintf("%10v", time.Duration(avgLatency)),
"ipPort": clientIP,
"method": method,
"host": host,
"path": path,
"referer": referer,
}).Infof("|%s| %10v %s", colorStatus(statusCode), time.Duration(latency), path)
// log.Infof("|%s %3d %s| %d %10v %10v | %s | %s %s %s | %s",
// statusColor, statusCode, reset,
// req, latency, time.Duration(avgLatency),
// clientIP,
// method, host, path,
// referer)
}
}
func colorForStatus(code int) string {
switch {
case code >= 200 && code < 300:
return green
case code >= 300 && code < 400:
return white
case code >= 400 && code < 500:
return yellow
default:
return red
}
}
func colorStatus(code int) string {
if !useColor {
return strconv.Itoa(code)
}
return fmt.Sprintf("%s %3d %s", colorForStatus(code), code, reset)
}