94 lines
1.9 KiB
Go
94 lines
1.9 KiB
Go
package controller
|
|
|
|
import (
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/Caknoooo/go-gin-clean-starter/pkg/constants"
|
|
"github.com/Caknoooo/go-gin-clean-starter/pkg/utils"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/samber/do"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type (
|
|
LogsController interface {
|
|
GetLogs(ctx *gin.Context)
|
|
GetLogsByMonth(ctx *gin.Context)
|
|
}
|
|
|
|
logsController struct {
|
|
db *gorm.DB
|
|
}
|
|
)
|
|
|
|
func NewLogsController(injector *do.Injector) LogsController {
|
|
db := do.MustInvokeNamed[*gorm.DB](injector, constants.DB)
|
|
return &logsController{
|
|
db: db,
|
|
}
|
|
}
|
|
|
|
func (c *logsController) GetLogs(ctx *gin.Context) {
|
|
month := strings.ToLower(time.Now().Format("January"))
|
|
c.getLogsForMonth(ctx, month)
|
|
}
|
|
|
|
func (c *logsController) GetLogsByMonth(ctx *gin.Context) {
|
|
month := ctx.Param("month")
|
|
c.getLogsForMonth(ctx, month)
|
|
}
|
|
|
|
func (c *logsController) getLogsForMonth(ctx *gin.Context, month string) {
|
|
// Multiple possible log locations
|
|
logLocations := []string{
|
|
"/app/config/logs/query_log",
|
|
"./config/logs/query_log",
|
|
"/tmp/logs",
|
|
}
|
|
|
|
var logs []string
|
|
var found bool
|
|
|
|
for _, logDir := range logLocations {
|
|
logFile := filepath.Join(logDir, month+"_query.log")
|
|
|
|
content, err := os.ReadFile(logFile)
|
|
if err == nil {
|
|
// File found, parse content
|
|
logEntries := strings.Split(string(content), "\r\n")
|
|
for _, entry := range logEntries {
|
|
if strings.TrimSpace(entry) != "" {
|
|
logs = append(logs, entry)
|
|
}
|
|
}
|
|
found = true
|
|
break
|
|
}
|
|
}
|
|
|
|
if !found {
|
|
logs = []string{}
|
|
}
|
|
|
|
// Jika request Accept header adalah application/json, kembalikan JSON
|
|
if ctx.GetHeader("Accept") == "application/json" {
|
|
res := utils.BuildResponseSuccess("Success get logs", gin.H{
|
|
"month": month,
|
|
"logs": logs,
|
|
"total": len(logs),
|
|
})
|
|
ctx.JSON(http.StatusOK, res)
|
|
return
|
|
}
|
|
|
|
// Default kembalikan HTML page
|
|
ctx.HTML(http.StatusOK, "logs.html", gin.H{
|
|
"Month": month,
|
|
"Logs": logs,
|
|
})
|
|
}
|