48 lines
1.6 KiB
Go
48 lines
1.6 KiB
Go
package mongoLogger
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
)
|
|
|
|
type LogEntry struct {
|
|
Level string `json:"level" bson:"level"`
|
|
Message string `json:"message" bson:"message"`
|
|
Timestamp string `json:"timestamp" bson:"timestamp"`
|
|
Fields map[string]interface{} `json:"fields" bson:"fields"`
|
|
Caller string `json:"caller" bson:"caller"`
|
|
Stack string `json:"stacktrace" bson:"stacktrace"`
|
|
Service string `json:"service" bson:"service"`
|
|
Env string `json:"env" bson:"env"`
|
|
}
|
|
|
|
func GetLogsHandler(appCtx context.Context) fiber.Handler {
|
|
return func(c *fiber.Ctx) error {
|
|
client, err := mongo.Connect(appCtx, options.Client().ApplyURI("mongodb://root:secret@mongo:27017/?authSource=admin"))
|
|
if err != nil {
|
|
return fiber.NewError(fiber.StatusInternalServerError, "MongoDB connection failed: "+err.Error())
|
|
}
|
|
|
|
collection := client.Database("logdb").Collection("applogs")
|
|
filter := bson.M{}
|
|
opts := options.Find().SetSort(bson.D{{Key: "timestamp", Value: -1}}).SetLimit(100)
|
|
|
|
cursor, err := collection.Find(appCtx, filter, opts)
|
|
if err != nil {
|
|
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch logs: "+err.Error())
|
|
}
|
|
defer cursor.Close(appCtx)
|
|
|
|
var logs []LogEntry
|
|
if err := cursor.All(appCtx, &logs); err != nil {
|
|
return fiber.NewError(fiber.StatusInternalServerError, "Cursor decoding error: "+err.Error())
|
|
}
|
|
|
|
return c.JSON(logs)
|
|
}
|
|
}
|