/
request_log.go
78 lines (67 loc) · 1.82 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
package middleware
import (
"bytes"
"fmt"
"github.com/ebar-go/ego/component/log"
"github.com/ebar-go/ego/component/trace"
"github.com/ebar-go/egu"
"github.com/gin-gonic/gin"
"io/ioutil"
"net/http"
"time"
)
// bodyLogWriter 读取响应Writer
type bodyLogWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
// Write 读取响应数据
func (w bodyLogWriter) Write(b []byte) (int, error) {
w.body.Write(b)
return w.ResponseWriter.Write(b)
}
// RequestLog gin的请求日志中间件
func RequestLog(logger *log.Logger) gin.HandlerFunc {
return func(ctx *gin.Context) {
t := time.Now()
requestTime := egu.GetMicroTimeStampStr()
blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: ctx.Writer}
ctx.Writer = blw
ctx.Next()
// package log content
items := log.Context{}
items["request_uri"] = ctx.Request.RequestURI
items["request_method"] = ctx.Request.Method
items["refer_service_name"] = ctx.Request.Referer()
items["refer_request_host"] = ctx.ClientIP()
items["request_body"] = getRequestBody(ctx)
items["request_time"] = requestTime
items["response_time"] = egu.GetMicroTimeStampStr()
items["response_body"] = blw.body.String()
items["time_used"] = fmt.Sprintf("%v", time.Since(t))
// use goroutine
trace.Go(func() {
logger.Info("request_log", items)
})
}
}
// GetRequestBody 获取请求参数
func getRequestBody(ctx *gin.Context) interface{} {
switch ctx.Request.Method {
case http.MethodGet:
return ctx.Request.URL.Query()
case http.MethodPost:
fallthrough
case http.MethodPut:
fallthrough
case http.MethodPatch:
var bodyBytes []byte // 我们需要的body内容
bodyBytes, err := ioutil.ReadAll(ctx.Request.Body)
if err != nil {
return nil
}
ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
return string(bodyBytes)
}
return nil
}