package dao import ( "context" "gitea.redpowerfuture.com/red-future/common/beans" "gitea.redpowerfuture.com/red-future/common/db/mongo" "strings" "time" "gitea.redpowerfuture.com/red-future/common/log/consts" "gitea.redpowerfuture.com/red-future/common/log/model/dto" "gitea.redpowerfuture.com/red-future/common/log/model/entity" "go.mongodb.org/mongo-driver/v2/bson" ) type log struct{} // Log 日志数据访问对象 var Log = &log{} // Create 创建日志记录 func (d *log) Create(ctx context.Context, log *entity.OperationLog) error { _, err := mongo.DB().Insert(ctx, []interface{}{log}, consts.OperationLogCollection) return err } // List 查询日志列表(通用方法,通过filter动态拼接查询条件) func (d *log) List(ctx context.Context, req *dto.ListLogsReq) (res []*entity.OperationLog, total int64, err error) { filter := buildFilter(req) req.OrderBy = []beans.OrderBy{ {Field: "createdAt", Order: beans.Desc}, } total, err = mongo.DB().Find(ctx, filter, &res, consts.OperationLogCollection, req.Page, req.OrderBy) return } // buildFilter 构建MongoDB查询过滤器 func buildFilter(filter interface{}) bson.M { bsonFilter := make(bson.M) // 从ListLogsReq结构体中提取字段值 if req, ok := filter.(*dto.ListLogsReq); ok { if req.ServiceName != "" { bsonFilter["service_name"] = req.ServiceName } if req.Collection != "" { bsonFilter["collection"] = req.Collection } if req.CollectionID != "" { bsonFilter["collection_id"] = bson.M{"$in": strings.Split(req.CollectionID, ",")} } if req.Operation != "" { bsonFilter["operation"] = req.Operation } // 处理时间范围字段 if req.StartTime != "" || req.EndTime != "" { timeFilter := bson.M{} if req.StartTime != "" { if startTime, err := time.Parse("2006-01-02 15:04:05", req.StartTime); err == nil { timeFilter["$gte"] = startTime } } if req.EndTime != "" { if endTime, err := time.Parse("2006-01-02 15:04:05", req.EndTime); err == nil { timeFilter["$lte"] = endTime } } if len(timeFilter) > 0 { bsonFilter["createdAt"] = timeFilter } } } return bsonFilter }