Files
common/log/dao/log_dao.go
2026-03-12 08:51:59 +08:00

78 lines
2.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package dao
import (
"context"
"gitea.com/red-future/common/beans"
"gitea.com/red-future/common/db/mongo"
"strings"
"time"
"gitea.com/red-future/common/log/consts"
"gitea.com/red-future/common/log/model/dto"
"gitea.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
}