-
Notifications
You must be signed in to change notification settings - Fork 0
/
access_log.go
48 lines (41 loc) · 989 Bytes
/
access_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
package midddleware
import (
"bytes"
"github.com/gin-gonic/gin"
"github.com/hayuzi/blogserver/global"
"github.com/hayuzi/blogserver/pkg/logger"
"time"
)
type AccessLogWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (w AccessLogWriter) Write(p []byte) (int, error) {
if n, err := w.body.Write(p); err != nil {
return n, err
}
return w.ResponseWriter.Write(p)
}
func AccessLog() gin.HandlerFunc {
return func(c *gin.Context) {
bodyWriter := &AccessLogWriter{
body: bytes.NewBufferString(""),
ResponseWriter: c.Writer,
}
c.Writer = bodyWriter
beginTime := time.Now().Unix()
c.Next()
endTime := time.Now().Unix()
fields := logger.Fields{
"request": c.Request.PostForm.Encode(),
"response": bodyWriter.body.String(),
}
global.Logger.WithFields(fields).
Infof(c, "access log: method: %s, statusCode: %d, beginTime: %d, endTime: %d",
c.Request.Method,
bodyWriter.Status(),
beginTime,
endTime,
)
}
}