log.go
1.6 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
package middleware
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
"io/ioutil"
"net/http"
"time"
)
func CreateRequstLogFilter() gin.HandlerFunc {
return func(ctx *gin.Context) {
requestId := fmt.Sprintf("%v.%v", ctx.Request.Method, ctx.Request.RequestURI)
ctx.Set("requestId", requestId)
var body string = "{}"
if _, ok := ctx.Get("requestBody"); ok {
data, _ := ctx.Get("requestBody")
body = string(data.([]byte))
}
start := time.Now()
ctx.Next()
end := time.Now()
latency := end.Sub(start)
v, _ := ctx.Get("outputData")
rspBody, _ := json.Marshal(v)
if len(rspBody) > 500 {
rspBody = rspBody[:500]
}
log.Debug(fmt.Sprintf("====>Recv User:%v | %v | %s | %v | \nAuth=%v \nReqBody:%s \nRspBody:%v", ctx.Query("UserId"), ctx.ClientIP(), requestId, latency, ctx.Query("x-mmm-accesstoken"), body, string(rspBody)))
}
}
func CreateResponseLogFilter() func(ctx *gin.Context) {
return func(ctx *gin.Context) {
requestId, _ := ctx.Get("requestId")
v, _ := ctx.Get("outputData")
body, _ := json.Marshal(v)
if len(body) > 1000 {
body = body[:1000]
}
log.Debug(fmt.Sprintf("<====Send RequestId:%v BodyData:%s", requestId, body))
}
}
func CreateRequestBodyFilter() func(ctx *gin.Context) {
return func(ctx *gin.Context) {
if ctx.Request.Method == http.MethodPost || ctx.Request.Method == http.MethodPut {
body, _ := ioutil.ReadAll(ctx.Request.Body)
if len(body) == 0 {
body = []byte("{}")
}
ctx.Set("requestBody", body)
ctx.Request.Body.Close()
}
}
}