package models import ( "LAPP_GAAS_GFrame_BACKEND/conf" "LAPP_GAAS_GFrame_BACKEND/db" "LAPP_GAAS_GFrame_BACKEND/utils" "context" "fmt" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo/options" "log" "strings" "time" ) type LeitServerLog struct { Level string `bson:"level" json:"leit_server_log-level"` //日志类别 TimeStamp string `bson:"timestamp" json:"leit_server_log-timestamp"` //时间戳 Message string `bson:"message" json:"leit_server_log-message"` //出错信息提示 Function string `bson:"function" json:"leit_server_log-function"` //出错函数 File string `bson:"file" json:"leit_server_log-file"` //出错文件 Operator string `bson:"operator" json:"leit_server_log-operator"` //操作人员 } type SerchData struct { Key string Val string Userid string } func (t *LeitServerLog) InsertRecord() (insertID primitive.ObjectID) { //1.初始化链接 client := db.MgoDb() //2.选择数据库,数据表 collect := client.Database(conf.DbConfig.Mongdbname).Collection("leit_server") insertRest, err := collect.InsertOne(context.TODO(), t) if err != nil { fmt.Println(err) return } insertID = insertRest.InsertedID.(primitive.ObjectID) return insertID } func (t *LeitServerLog) FindLog(logred SerchData, skip int64, limit int64) ([]*LeitServerLog, int64) { res := bson.M{} // 创建需要过滤的条件 if logred.Key == "level" { res = bson.M{"level": primitive.Regex{Pattern: logred.Val}} } if logred.Key == "message" { res = bson.M{"message": primitive.Regex{Pattern: logred.Val}} } if logred.Key == "function" { res = bson.M{"function": primitive.Regex{Pattern: logred.Val}} } if logred.Key == "file" { res = bson.M{"file": primitive.Regex{Pattern: logred.Val}} } if logred.Key == "operator" { res = bson.M{"operator": primitive.Regex{Pattern: logred.Val}} } if logred.Key == "timestamp" { times := strings.Split(logred.Val, "-") stime := time.Unix(int64(utils.ValueToInt(times[0], 0)), 0) etime := time.Unix(int64(utils.ValueToInt(times[1], 0)), 0) stimestr := utils.TimeFormat(stime, "yyyyMMddHHmmss") etimestr := utils.TimeFormat(etime, "yyyyMMddHHmmss") res = bson.M{"timestamp": bson.M{"$lte": etimestr, "$gte": stimestr}} } if logred.Userid != "admin" { res = bson.M{"operator": logred.Userid} } //1.初始化链接 client := db.MgoDb() //2.选择数据库,数据表 collect := client.Database(conf.DbConfig.Mongdbname).Collection("leit_server") //var skip int64 = 0//从那个开始 //var limit int64 = 2//炼制几个输出字段 cursor, err := collect.Find(context.TODO(), res, &options.FindOptions{ Skip: &skip, Limit: &limit, Sort: bson.D{{"timestamp", -1}}, }) if err != nil { fmt.Println(err) return nil, 0 } defer cursor.Close(context.TODO()) //创建需要反序列化成什么样子的结构体对象 records := make([]*LeitServerLog, 0) for cursor.Next(context.TODO()) { record := &LeitServerLog{} //反序列化 err = cursor.Decode(record) if err != nil { fmt.Println(err) return nil, 0 } //追加 records = append(records, record) } // 获取数据总数 count, err := collect.CountDocuments(context.Background(), bson.D{}) if err != nil { log.Fatal(count) } return records, count }