package service import ( "context" "gitee.com/red-future---jilin-g/common/log/consts" "gitee.com/red-future---jilin-g/common/log/dao" "gitee.com/red-future---jilin-g/common/log/model/dto" logEntity "gitee.com/red-future---jilin-g/common/log/model/entity" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/util/gconv" ) type operationLog struct{} // OperationLog 操作日志服务 var OperationLog = &operationLog{} // RecordCreate 记录创建操作 func (s *operationLog) RecordCreate(ctx context.Context, serviceName, collection, collectionID string, data map[string]interface{}) error { return s.record(ctx, serviceName, collection, collectionID, string(consts.OperationCreate), data) } // RecordUpdate 记录更新操作 func (s *operationLog) RecordUpdate(ctx context.Context, serviceName, collection, collectionID string, data map[string]interface{}) error { return s.record(ctx, serviceName, collection, collectionID, string(consts.OperationUpdate), data) } // RecordDelete 记录删除操作 func (s *operationLog) RecordDelete(ctx context.Context, serviceName, collection, collectionID string, data map[string]interface{}) error { return s.record(ctx, serviceName, collection, collectionID, string(consts.OperationDelete), data) } // BatchRecordCreate 批量记录创建操作 func (s *operationLog) BatchRecordCreate(ctx context.Context, logs []*logEntity.OperationLog) error { return dao.Log.CreateBatch(ctx, logs) } // GetByID 根据ID获取操作日志 func (s *operationLog) GetByID(ctx context.Context, id string) (*dto.OperationLogInfo, error) { log, err := dao.Log.GetByID(ctx, id) if err != nil { return nil, err } var logInfo dto.OperationLogInfo if err := gconv.Struct(log, &logInfo); err != nil { return nil, err } logInfo.ID = log.Id.Hex() return &logInfo, nil } // List 查询操作日志列表 func (s *operationLog) List(ctx context.Context, req *dto.ListLogsReq) ([]dto.OperationLogInfo, int64, error) { logs, total, err := dao.Log.List(ctx, req) if err != nil { return nil, 0, err } var logInfos []dto.OperationLogInfo err = gconv.Structs(logs, &logInfos) if err != nil { return nil, 0, err } // 处理特殊字段 for i, log := range logs { logInfos[i].ID = log.Id.Hex() } return logInfos, total, nil } // record 记录操作日志的通用方法 func (s *operationLog) record(ctx context.Context, serviceName, collection, collectionID, operation string, data map[string]interface{}) error { // 获取请求信息 ipAddress := getHTTPRequestInfo(ctx) log := &logEntity.OperationLog{ ServiceName: serviceName, Collection: collection, CollectionID: collectionID, Operation: operation, IPAddress: ipAddress, Data: data, } return dao.Log.Create(ctx, log) } // getHTTPRequestInfo 从上下文中获取HTTP请求信息 func getHTTPRequestInfo(ctx context.Context) string { request := g.RequestFromCtx(ctx) if request != nil { return request.GetClientIp() } return "" }