log.go
1.5 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
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 RequestId:%s BodyData:%s \n Header:%v", requestId, body, ctx.Request.Header))
}
}
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) > 1000 {
body = body[:1000]
}
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()
}
//if len(ctx.Input.RequestBody) == 0 {
//
//} else {
// ctx.Input.SetData("requestBody", ctx.Input.RequestBody)
//}
}
}