JSON转换放在内置函数里

This commit is contained in:
2025-09-28 00:37:20 +08:00
parent 1c7e13b965
commit 3c8b91ff6a
2 changed files with 40 additions and 23 deletions

View File

@@ -2,14 +2,12 @@
package audit
import (
"encoding/json"
"time"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/logs"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/repository"
"github.com/gin-gonic/gin"
"gorm.io/datatypes"
)
const (
@@ -49,29 +47,23 @@ func (s *service) LogAction(c *gin.Context, actionType, description string, targ
return
}
// 将 targetResource 转换为 JSONB如果失败则记录错误但继续
var targetResourceJSON datatypes.JSON
if targetResource != nil {
bytes, err := json.Marshal(targetResource)
if err != nil {
s.logger.Errorw("无法记录审计日志:序列化 targetResource 失败", "error", err)
} else {
targetResourceJSON = bytes
}
log := &models.UserActionLog{
Time: time.Now(),
UserID: user.ID,
Username: user.Username, // 用户名快照
SourceIP: c.ClientIP(),
ActionType: actionType,
Description: description,
Status: status,
HTTPPath: c.Request.URL.Path,
HTTPMethod: c.Request.Method,
ResultDetails: resultDetails,
}
log := &models.UserActionLog{
Time: time.Now(),
UserID: user.ID,
Username: user.Username, // 用户名快照
SourceIP: c.ClientIP(),
ActionType: actionType,
TargetResource: targetResourceJSON,
Description: description,
Status: status,
HTTPPath: c.Request.URL.Path,
HTTPMethod: c.Request.Method,
ResultDetails: resultDetails,
// 使用模型提供的方法来设置 TargetResource
if err := log.SetTargetResource(targetResource); err != nil {
s.logger.Errorw("无法记录审计日志:序列化 targetResource 失败", "error", err)
// 即使序列化失败,我们可能仍然希望记录操作本身,所以不在此处 return
}
// 异步写入数据库,不阻塞当前请求