93 lines
2.3 KiB
Go
93 lines
2.3 KiB
Go
package aplicare
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"time"
|
|
)
|
|
|
|
type SyncLog struct {
|
|
Timestamp string `json:"timestamp"`
|
|
KodeRuang string `json:"kode_ruang,omitempty"`
|
|
NamaRuang string `json:"nama_ruang,omitempty"`
|
|
KodeKelas string `json:"kode_kelas,omitempty"`
|
|
Kapasitas int `json:"kapasitas,omitempty"`
|
|
Tersedia int `json:"tersedia,omitempty"`
|
|
Action string `json:"action"`
|
|
Status string `json:"status"`
|
|
Error string `json:"error,omitempty"`
|
|
ResponseMs int64 `json:"response_ms,omitempty"`
|
|
}
|
|
|
|
// logPath sekarang fungsi yang mengembalikan path berdasarkan tanggal
|
|
func getLogPath() string {
|
|
// Format tanggal: 2026-06-11
|
|
dateStr := time.Now().Format("2006-01-02")
|
|
return filepath.Join("./logs", fmt.Sprintf("sync-%s.log", dateStr))
|
|
}
|
|
|
|
func init() {
|
|
_ = os.MkdirAll("./logs", 0755)
|
|
}
|
|
|
|
// WriteLog menulis 1 entry log ke file berdasarkan tanggal hari ini
|
|
func WriteLog(entry SyncLog) {
|
|
entry.Timestamp = time.Now().Format(time.RFC3339)
|
|
logPath := getLogPath()
|
|
writeToFile(entry, logPath)
|
|
}
|
|
|
|
// WriteBatchLog menulis ringkasan 1 run sync ke file berdasarkan tanggal hari ini
|
|
func WriteBatchLog(result *SyncResult) {
|
|
if result == nil {
|
|
return
|
|
}
|
|
|
|
status := "sukses"
|
|
if len(result.Errors) > 0 {
|
|
status = "partial"
|
|
}
|
|
if result.Posted == 0 && result.Changed > 0 {
|
|
status = "gagal"
|
|
}
|
|
|
|
summary := map[string]interface{}{
|
|
"timestamp": time.Now().Format(time.RFC3339),
|
|
"action": "batch_sync",
|
|
"total_rooms": result.TotalRooms,
|
|
"changed": result.Changed,
|
|
"posted": result.Posted,
|
|
"dry_run": result.DryRun,
|
|
"status": status,
|
|
"errors": result.Errors,
|
|
}
|
|
|
|
logPath := getLogPath()
|
|
f, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer f.Close()
|
|
|
|
line, _ := json.Marshal(summary)
|
|
_, _ = f.Write(append(line, '\n'))
|
|
|
|
// Rotasi log tidak diperlukan karena sudah otomatis terpisah per hari
|
|
}
|
|
|
|
func writeToFile(entry SyncLog, logPath string) {
|
|
f, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
|
if err != nil {
|
|
fmt.Printf("gagal buka log file: %v\n", err)
|
|
return
|
|
}
|
|
defer f.Close()
|
|
|
|
line, _ := json.Marshal(entry)
|
|
_, _ = f.Write(append(line, '\n'))
|
|
}
|
|
|
|
// rotateLogs dihapus karena sudah otomatis terpisah per hari
|