Ariver
2026-07-12 24f551a39eae849d891da26cc91f90d354e3a2db
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package logger
 
import (
    "fmt"
    "os"
    "path/filepath"
    "sync"
    "time"
    "voicesnap/internal/paths"
)
 
var (
    mu      sync.Mutex
    logFile *os.File
)
 
const (
    maxLogBytes   = 10 * 1024 * 1024
    maxLogBackups = 3
)
 
// Init initializes the file logger in the persistent app data directory.
func Init() {
    mu.Lock()
    if logFile != nil {
        logFile.Close()
        logFile = nil
    }
    mu.Unlock()
 
    dir := paths.AppSupportDir()
    if err := os.MkdirAll(dir, 0755); err != nil {
        fmt.Fprintf(os.Stderr, "failed to create log dir: %v\n", err)
        return
    }
    path := filepath.Join(dir, "app.log")
    if err := rotateIfNeeded(path); err != nil {
        fmt.Fprintf(os.Stderr, "failed to rotate log file: %v\n", err)
    }
 
    f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
    if err != nil {
        fmt.Fprintf(os.Stderr, "failed to open log file: %v\n", err)
        return
    }
    mu.Lock()
    defer mu.Unlock()
    logFile = f
}
 
func rotateIfNeeded(path string) error {
    info, err := os.Stat(path)
    if err != nil {
        if os.IsNotExist(err) {
            return nil
        }
        return err
    }
    if info.Size() < maxLogBytes {
        return nil
    }
 
    oldest := fmt.Sprintf("%s.%d", path, maxLogBackups)
    if err := os.Remove(oldest); err != nil && !os.IsNotExist(err) {
        return err
    }
    for i := maxLogBackups - 1; i >= 1; i-- {
        from := fmt.Sprintf("%s.%d", path, i)
        to := fmt.Sprintf("%s.%d", path, i+1)
        if err := os.Rename(from, to); err != nil && !os.IsNotExist(err) {
            return err
        }
    }
    return os.Rename(path, path+".1")
}
 
func write(level, format string, args ...interface{}) {
    msg := fmt.Sprintf(format, args...)
    ts := time.Now().Format("2006-01-02 15:04:05")
    line := fmt.Sprintf("[%s] %s %s\n", ts, level, msg)
 
    mu.Lock()
    defer mu.Unlock()
 
    if logFile != nil {
        logFile.WriteString(line)
    }
    fmt.Fprint(os.Stderr, line)
}
 
// Info logs an informational message.
func Info(format string, args ...interface{}) {
    write("INFO", format, args...)
}
 
// Error logs an error message.
func Error(format string, args ...interface{}) {
    write("ERROR", format, args...)
}
 
// Close closes the log file.
func Close() {
    mu.Lock()
    defer mu.Unlock()
    if logFile != nil {
        logFile.Close()
        logFile = nil
    }
}