forked from krakend/krakend-gologging
/
request_log.go
88 lines (75 loc) · 2.09 KB
/
request_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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package gologging
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"time"
"github.com/MagalixTechnologies/core/logger"
"github.com/gin-gonic/gin"
"github.com/luraproject/lura/logging"
)
const healthEndPoint = "/__health"
func getRequestId(r *http.Request) interface{} {
reqID := r.Header.Get("X-Request-Id")
if reqID == "" {
reqID = shortID()
}
return reqID
}
func shortID() string {
b := make([]byte, 6)
io.ReadFull(rand.Reader, b)
return base64.RawURLEncoding.EncodeToString(b)
}
func NewRequestLogger(log logging.Logger) gin.HandlerFunc {
lg := log.(Logger)
level := lg.GetLogLevel()
return func(c *gin.Context) {
request := c.Request
endpoint := request.URL.String()
if endpoint == healthEndPoint {
return
}
reqID := getRequestId(request)
sugar := logger.New(lg.GetLogLevel())
sugarLogger := sugar.With("requestId", reqID)
started := time.Now()
c.Next()
if level == logger.DebugLevel {
// copy request payload in case we will show it
buf, _ := ioutil.ReadAll(request.Body)
rdr1 := ioutil.NopCloser(bytes.NewBuffer(buf))
rdr2 := ioutil.NopCloser(bytes.NewBuffer(buf))
request.Body = rdr2 // OK since rdr2 implements the io.ReadCloser interface
var payload map[string]interface{}
json.NewDecoder(rdr1).Decode(&payload)
headers := make(map[string][]string)
for name, values := range request.Header {
switch name {
case "Accept", "X-Request-Id", "Content-Length", "Content-Type", "User-Agent", "X-B3-Parentspanid", "X-B3-Sampled", "X-B3-Spanid", "X-B3-Traceid", "X-Envoy-Attempt-Count", "X-Forwarded-Client-Cert", "X-Forwarded-Proto":
continue
default:
headers[name] = values
}
}
sugarLogger.Debugw("Default Log",
"method", request.Method,
"endpoint", request.URL.String(),
"payload", payload,
"headers", headers,
)
}
defer sugarLogger.Sync()
sugarLogger.Infow("Default Log",
"method", request.Method,
"endpoint", endpoint,
"StatusCode", c.Writer.Status(),
"bytes", c.Writer.Size(),
"duration", time.Since(started).String(),
)
}
}