48 lines
829 B
Go
48 lines
829 B
Go
package util
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"time"
|
|
)
|
|
|
|
var (
|
|
logFile *os.File
|
|
logReady bool
|
|
)
|
|
|
|
// InitLogFile sets up a log file inside the agent directory.
|
|
// Called from main.go (optional).
|
|
func InitLogFile(path string) error {
|
|
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
logFile = f
|
|
logReady = true
|
|
return nil
|
|
}
|
|
|
|
func CloseLog() {
|
|
if logReady && logFile != nil {
|
|
logFile.Close()
|
|
}
|
|
}
|
|
|
|
// Log writes a timestamped line to stdout AND to log file (if enabled).
|
|
func Log(format string, v ...any) {
|
|
line := fmt.Sprintf("[%s] %s",
|
|
time.Now().Format("2006-01-02 15:04:05"),
|
|
fmt.Sprintf(format, v...),
|
|
)
|
|
|
|
// Always print to stdout
|
|
log.Println(line)
|
|
|
|
// Optionally also write to file
|
|
if logReady && logFile != nil {
|
|
logFile.WriteString(line + "\n")
|
|
}
|
|
}
|