Files
YaeMikoBot/database/mdb/logs.go
2026-02-05 15:14:47 +03:00

78 lines
2.4 KiB
Go

package mdb
import (
"context"
"kurumibot/database"
"time"
"git.nix13.pw/scuroneko/extypes"
"git.nix13.pw/scuroneko/laniakea"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
type ConsoleLogEntry struct {
Level string `bson:"level" json:"level"`
Prefix string `bson:"prefix" json:"prefix"`
Traceback string `bson:"traceback" json:"traceback"`
Message string `bson:"message" json:"message"`
Time time.Time `bson:"time" json:"time"`
TimeStamp int64 `bson:"timeStamp" json:"time_stamp"`
}
func WriteConsoleLog(db *laniakea.DatabaseContext, e *ConsoleLogEntry) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
col := database.GetMongoCollection(db, "logs")
_, err := col.InsertOne(ctx, e)
return err
}
func GetConsoleLogs(db *laniakea.DatabaseContext) (extypes.Slice[*ConsoleLogEntry], error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
col := database.GetMongoCollection(db, "logs")
opts := options.Find()
opts.SetLimit(5)
opts.SetSort(bson.D{{"_id", 1}})
cursor, err := col.Find(ctx, bson.D{}, opts)
if err != nil {
return nil, err
}
defer cursor.Close(ctx)
result := make(extypes.Slice[*ConsoleLogEntry], 0)
err = cursor.All(ctx, &result)
return result, nil
}
type MessageLogEntry struct {
MessageID int `bson:"messageId" json:"message_id"`
SenderID int `bson:"senderId" json:"sender_id"`
ChatID int `bson:"chatId" json:"chat_id"`
Text string `bson:"text" json:"text"`
TimeStamp int64 `bson:"timestamp" json:"timestamp"`
}
func WriteMessageLog(db *laniakea.DatabaseContext, e *MessageLogEntry) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
col := database.GetMongoCollection(db, "msg_logs")
_, err := col.InsertOne(ctx, e)
return err
}
func GetMessageLogs(db *laniakea.DatabaseContext) (extypes.Slice[*MessageLogEntry], error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
col := database.GetMongoCollection(db, "msg_logs")
opts := options.Find()
opts.SetLimit(5)
opts.SetSort(bson.D{{"_id", 1}})
cursor, err := col.Find(ctx, bson.D{}, opts)
if err != nil {
return nil, err
}
defer cursor.Close(ctx)
result := make(extypes.Slice[*MessageLogEntry], 0)
err = cursor.All(ctx, &result)
return result, nil
}