Repository navigation
Expand file tree
/
Copy pathlogs.go
More file actions
103 lines (85 loc) · 2.08 KB
/
Copy pathlogs.go
File metadata and controls
103 lines (85 loc) · 2.08 KB
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 logs provides HTTP request and response logging.
package logs
import (
"net/http"
"strconv"
"time"
"github.com/apex/log"
"github.com/apex/up"
"github.com/apex/up/internal/logs"
"github.com/apex/up/internal/util"
)
// TODO: optional verbose mode with req/res header etc?
// log context.
var ctx = logs.Plugin("logs")
// response wrapper.
type response struct {
http.ResponseWriter
written int
code int
duration time.Duration
}
// Write implementation.
func (r *response) Write(b []byte) (int, error) {
n, err := r.ResponseWriter.Write(b)
r.written += n
return n, err
}
// WriteHeader implementation.
func (r *response) WriteHeader(code int) {
r.code = code
r.ResponseWriter.WriteHeader(code)
}
// New logs handler.
func New(c *up.Config, next http.Handler) (http.Handler, error) {
if c.Logs.Disable {
return next, nil
}
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := logContext(r)
logRequest(ctx, r)
start := time.Now()
res := &response{ResponseWriter: w, code: 200}
next.ServeHTTP(res, r)
res.duration = time.Since(start)
logResponse(ctx, res, r)
})
return h, nil
}
// logContext returns the common log context for a request.
func logContext(r *http.Request) log.Interface {
return ctx.WithFields(log.Fields{
"stage": r.Header.Get("X-Stage"),
"id": r.Header.Get("X-Request-Id"),
"method": r.Method,
"path": r.URL.Path,
"query": r.URL.Query().Encode(),
"ip": r.RemoteAddr,
})
}
// logRequest logs the request.
func logRequest(ctx log.Interface, r *http.Request) {
if s := r.Header.Get("Content-Length"); s != "" {
n, err := strconv.Atoi(s)
if err == nil {
ctx = ctx.WithField("size", n)
}
}
ctx.Info("request")
}
// logResponse logs the response.
func logResponse(ctx log.Interface, res *response, r *http.Request) {
ctx = ctx.WithFields(log.Fields{
"duration": util.Milliseconds(res.duration),
"size": res.written,
"status": res.code,
})
switch {
case res.code >= 500:
ctx.Error("response")
case res.code >= 400:
ctx.Warn("response")
default:
ctx.Info("response")
}
}