/
logger.go
48 lines (41 loc) · 1.14 KB
/
logger.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
package middleware
import (
"bytes"
"github.com/c2pc/go-pkg/logger"
"github.com/gin-gonic/gin"
"io"
)
type bodyLogWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (w bodyLogWriter) Write(b []byte) (int, error) {
w.body.Write(b)
return w.ResponseWriter.Write(b)
}
func GinResponseBodyLogMiddleware(module string, stdout bool) gin.HandlerFunc {
return func(c *gin.Context) {
blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
c.Writer = blw
c.Next()
if len(blw.body.String()) < 1000 {
logger.InfofLog(module, stdout, "Response: %s", blw.body.String())
} else {
logger.InfofLog(module, stdout, "Response: %s...", blw.body.String()[:1000])
}
}
}
func GinRequestBodyLogMiddleware(module string, stdout bool) gin.HandlerFunc {
return func(c *gin.Context) {
var buf bytes.Buffer
tee := io.TeeReader(c.Request.Body, &buf)
body, _ := io.ReadAll(tee)
c.Request.Body = io.NopCloser(&buf)
if len(string(body)) < 1000 {
logger.InfofLog(module, stdout, "Request: %s", string(body))
} else {
logger.InfofLog(module, stdout, "Request: %s...", string(body)[:1000])
}
c.Next()
}
}