penambahan dan perbaikan untuk log
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -20,19 +21,25 @@ type SyncLog struct {
|
||||
ResponseMs int64 `json:"response_ms,omitempty"`
|
||||
}
|
||||
|
||||
var logPath = "./logs/sync.log"
|
||||
// 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 sync.log
|
||||
// WriteLog menulis 1 entry log ke file berdasarkan tanggal hari ini
|
||||
func WriteLog(entry SyncLog) {
|
||||
entry.Timestamp = time.Now().Format(time.RFC3339)
|
||||
writeToFile(entry)
|
||||
logPath := getLogPath()
|
||||
writeToFile(entry, logPath)
|
||||
}
|
||||
|
||||
// WriteBatchLog menulis ringkasan 1 run sync
|
||||
// WriteBatchLog menulis ringkasan 1 run sync ke file berdasarkan tanggal hari ini
|
||||
func WriteBatchLog(result *SyncResult) {
|
||||
if result == nil {
|
||||
return
|
||||
@@ -57,6 +64,7 @@ func WriteBatchLog(result *SyncResult) {
|
||||
"errors": result.Errors,
|
||||
}
|
||||
|
||||
logPath := getLogPath()
|
||||
f, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -66,11 +74,10 @@ func WriteBatchLog(result *SyncResult) {
|
||||
line, _ := json.Marshal(summary)
|
||||
_, _ = f.Write(append(line, '\n'))
|
||||
|
||||
// Rotasi log — jaga ukuran file max 5MB
|
||||
rotateLogs()
|
||||
// Rotasi log tidak diperlukan karena sudah otomatis terpisah per hari
|
||||
}
|
||||
|
||||
func writeToFile(entry SyncLog) {
|
||||
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)
|
||||
@@ -82,15 +89,4 @@ func writeToFile(entry SyncLog) {
|
||||
_, _ = f.Write(append(line, '\n'))
|
||||
}
|
||||
|
||||
// rotateLogs — kalau file > 5MB, rename jadi sync.log.old
|
||||
func rotateLogs() {
|
||||
info, err := os.Stat(logPath)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 5MB
|
||||
if info.Size() > 5*1024*1024 {
|
||||
_ = os.Rename(logPath, logPath+".old")
|
||||
}
|
||||
}
|
||||
// rotateLogs dihapus karena sudah otomatis terpisah per hari
|
||||
Reference in New Issue
Block a user