add: access log

This commit is contained in:
viletyy 2021-06-12 22:26:04 +08:00
parent 8640d56ce2
commit 3c3a5bf722
2 changed files with 52 additions and 1 deletions

View File

@ -0,0 +1,50 @@
/*
* @Date: 2021-06-12 21:55:50
* @LastEditors: viletyy
* @LastEditTime: 2021-06-12 22:22:31
* @FilePath: /potato/internal/middleware/access_log.go
*/
package middleware
import (
"bytes"
"time"
"github.com/gin-gonic/gin"
"github.com/viletyy/potato/global"
"go.uber.org/zap"
)
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()
global.GO_LOG.With(
zap.String("request", c.Request.PostForm.Encode()),
zap.String("response", bodyWriter.body.String()),
).Sugar().Infof("access log: method: %s, status_code: %d, begin_time: %d, end_time: %d",
c.Request.Method,
bodyWriter.Status(),
beginTime,
endTime,
)
}
}

View File

@ -1,7 +1,7 @@
/*
* @Date: 2021-03-21 19:54:57
* @LastEditors: viletyy
* @LastEditTime: 2021-06-11 17:57:21
* @LastEditTime: 2021-06-12 22:24:53
* @FilePath: /potato/internal/routers/router.go
*/
package routers
@ -34,6 +34,7 @@ func InitRouter() *gin.Engine {
gin.SetMode(global.GO_CONFIG.App.RunMode)
Engine.Use(middleware.CORS())
Engine.Use(middleware.AccessLog())
Engine.StaticFS("/static", http.Dir(global.GO_CONFIG.App.UploadSavePath))
Engine.POST("/api/v1/auth", v1.GetAuth)