You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

52 lines
1.1 KiB

package middleware
import (
"bytes"
"gofaster/internal/model"
"io"
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"gorm.io/gorm"
)
func LoggerMiddleware(logger *zap.Logger, db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
query := c.Request.URL.RawQuery
// 记录请求体
var requestBody string
if c.Request.Body != nil {
bodyBytes, _ := io.ReadAll(c.Request.Body)
c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
requestBody = string(bodyBytes)
}
// 处理请求
c.Next()
// 记录日志
latency := time.Since(start).Milliseconds()
actionLog := model.ActionLog{
UserID: getUserIdFromContext(c),
Action: getActionFromPath(path),
IP: c.ClientIP(),
UserAgent: c.Request.UserAgent(),
Path: path,
Method: c.Request.Method,
Request: requestBody,
Status: c.Writer.Status(),
Latency: latency,
}
// 异步保存日志
go func() {
if err := db.Create(&actionLog).Error; err != nil {
logger.Error("保存操作日志失败", zap.Error(err))
}
}()
}
}