log.go
1.4 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
package middleware
import (
"encoding/json"
"fmt"
"github.com/astaxie/beego/context"
"github.com/astaxie/beego/logs"
"io/ioutil"
"net/http"
"time"
)
func CreateRequstLogFilter(logger *logs.BeeLogger) func(ctx *context.Context) {
return func(ctx *context.Context) {
requestId := fmt.Sprintf("%v.%v.%v ", ctx.Input.Method(), ctx.Input.URI(), time.Now().UnixNano())
ctx.Request.Header.Add("requestId", requestId)
var body string = "{}"
if ctx.Input.GetData("requestBody") != nil {
body = string(ctx.Input.GetData("requestBody").([]byte))
}
logger.Debug(fmt.Sprintf("====>Recv User:%v RequestId:%s \n Auth=%v \n BodyData:%s", ctx.Input.GetData("UserId"), requestId, ctx.Input.Header("x-mmm-accesstoken"), body))
}
}
func CreateResponseLogFilter(logger *logs.BeeLogger) func(ctx *context.Context) {
return func(ctx *context.Context) {
requestId := ctx.Request.Header.Get("requestId")
body, _ := json.Marshal(ctx.Input.GetData("outputData"))
if len(body) > 100000 {
body = body[:100000]
}
logger.Debug(fmt.Sprintf("<====Send RequestId:%v BodyData:%s", requestId, body))
}
}
func CreateRequestBodyFilter() func(ctx *context.Context) {
return func(ctx *context.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.Input.SetData("requestBody", body)
ctx.Request.Body.Close()
}
}
}