This repository has been archived by the owner on Feb 24, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 575
/
request_logger.go
75 lines (68 loc) · 1.79 KB
/
request_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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package buffalo
import (
"crypto/rand"
"encoding/hex"
"net/http"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/gobuffalo/buffalo/internal/httpx"
)
// RequestLogger can be be overridden to a user specified
// function that can be used to log the request.
var RequestLogger = RequestLoggerFunc
func randString(i int) (string, error) {
if i == 0 {
i = 64
}
b := make([]byte, i)
_, err := rand.Read(b)
return hex.EncodeToString(b), err
}
// RequestLoggerFunc is the default implementation of the RequestLogger.
// By default it will log a uniq "request_id", the HTTP Method of the request,
// the path that was requested, the duration (time) it took to process the
// request, the size of the response (and the "human" size), and the status
// code of the response.
func RequestLoggerFunc(h Handler) Handler {
return func(c Context) error {
rs, err := randString(10)
if err != nil {
return err
}
var irid interface{}
if irid = c.Session().Get("requestor_id"); irid == nil {
rs, err := randString(10)
if err != nil {
return err
}
irid = rs
c.Session().Set("requestor_id", irid)
}
rid := irid.(string) + "-" + rs
c.Set("request_id", rid)
c.LogField("request_id", rid)
start := time.Now()
defer func() {
ws, ok := c.Response().(*Response)
if !ok {
ws = &Response{ResponseWriter: c.Response()}
ws.Status = http.StatusOK
}
req := c.Request()
ct := httpx.ContentType(req)
if ct != "" {
c.LogField("content_type", ct)
}
c.LogFields(map[string]interface{}{
"method": req.Method,
"path": req.URL.String(),
"duration": time.Since(start),
"size": ws.Size,
"human_size": humanize.Bytes(uint64(ws.Size)),
"status": ws.Status,
})
c.Logger().Info(req.URL.String())
}()
return h(c)
}
}