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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
package logcap
import (
"cmp"
"context"
"io"
"log/slog"
"os"
"path/filepath"
"slices"
"strings"
"time"
"github.com/fsnotify/fsnotify"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/debounce"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/fswatch"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/opt"
)
const (
DefaultCap = 64 << 20
DefaultEvery = time.Minute
OldSuffix = ".1"
)
func Rotate(path string, capBytes int64) (bool, error) {
if capBytes <= 0 {
return false, nil
}
st, err := os.Stat(path)
if err != nil || !st.Mode().IsRegular() || st.Size() <= capBytes {
return false, nil
}
in, err := os.Open(path)
if err != nil {
return false, err
}
defer in.Close()
if _, err := in.Seek(-capBytes, io.SeekEnd); err != nil {
return false, err
}
out, err := os.OpenFile(path+OldSuffix, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, st.Mode().Perm())
if err != nil {
return false, err
}
_, cerr := io.Copy(out, in)
if err := out.Close(); cerr == nil {
cerr = err
}
if cerr != nil {
return false, cerr
}
return true, os.Truncate(path, 0)
}
type Config struct {
Dirs []string
Files []string
Cap int64
Every time.Duration
Log *slog.Logger
}
func (c Config) paths() []string {
out := append([]string(nil), c.Files...)
for _, d := range c.Dirs {
entries, err := os.ReadDir(d)
if err != nil {
continue
}
for _, e := range entries {
if e.Type().IsRegular() && strings.HasSuffix(e.Name(), ".log") {
out = append(out, filepath.Join(d, e.Name()))
}
}
}
return out
}
func (c Config) Pass() []string {
capBytes := c.Cap
capBytes = cmp.Or(capBytes, DefaultCap)
var rotated []string
for _, p := range c.paths() {
ok, err := Rotate(p, capBytes)
if err != nil && c.Log != nil {
c.Log.Warn("a log file over its cap was not rotated", "file", p, "err", err.Error())
}
if ok {
rotated = append(rotated, p)
}
}
return rotated
}
func (c Config) watched() []string {
dirs := append([]string(nil), c.Dirs...)
for _, f := range c.Files {
if d := filepath.Dir(f); !slices.Contains(dirs, d) {
dirs = append(dirs, d)
}
}
return dirs
}
func (c Config) tracked(path string) bool {
if slices.Contains(c.Files, path) {
return true
}
return strings.HasSuffix(path, ".log") && slices.Contains(c.Dirs, filepath.Dir(path))
}
func (c Config) warn(msg string, args ...any) {
if c.Log != nil {
c.Log.Warn(msg, args...)
}
}
func Keep(ctx context.Context, c Config) {
pass := func() {
if rotated := c.Pass(); len(rotated) > 0 && c.Log != nil {
c.Log.Info("log files over their cap were rotated; each keeps its newest bytes in a .1 copy", "files", rotated)
}
}
pass()
w, err := fswatch.Shared().Subscribe()
if err != nil {
c.warn("log files are not watched; they are capped only at start", "err", err.Error())
return
}
defer w.Close()
for _, d := range c.watched() {
if err := w.Add(d); err != nil {
c.warn("a log directory is not watched", "dir", d, "err", err.Error())
}
}
d := debounce.New(opt.Positive(c.Every, DefaultEvery), pass)
defer d.Stop()
for {
select {
case <-ctx.Done():
return
case ev, ok := <-w.Events():
if !ok {
return
}
if ev.Has(fsnotify.Write|fsnotify.Create) && c.tracked(ev.Name) {
d.Mark()
}
case err, ok := <-w.Errors():
if !ok {
return
}
c.warn("watching the log files", "err", err.Error())
d.Mark()
}
}
}