com.snow.auto_monitor/app/http/middlewares/request_log.go

34 lines
841 B
Go

package middlewares
import (
"bytes"
"io/ioutil"
"time"
"github.com/gin-gonic/gin"
"github.com/qit-team/snow-core/log/logger"
)
func RequestLog() gin.HandlerFunc {
return func(c *gin.Context) {
bodyBytes, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
logger.Info(c, "LogRequset", "Failed to read request body:"+err.Error())
c.Next()
return
}
// 将请求体重置,以便后续处理可以再次读取
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
infstr := "Date: " + time.Now().Format("2006-01-02 15:04:05") + " "
// 构建日志信息
infstr += "Request: " + c.Request.Method + " " + c.Request.URL.Path + " "
infstr += "From: " + c.ClientIP() + " "
infstr += "Body: " + string(bodyBytes)
logger.Info(c, "LogRequset", infstr)
// 调用下一个中间件
c.Next()
}
}