mirror of
https://github.com/safing/portmaster
synced 2025-09-01 18:19:12 +00:00
Delete old log files regularly
This commit is contained in:
parent
18cc0f2bf6
commit
8f898f4e32
2 changed files with 59 additions and 0 deletions
|
@ -55,5 +55,7 @@ func start() error {
|
|||
return err
|
||||
}
|
||||
|
||||
registerLogCleaner()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
57
core/logs.go
Normal file
57
core/logs.go
Normal file
|
@ -0,0 +1,57 @@
|
|||
package core
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/safing/portbase/dataroot"
|
||||
"github.com/safing/portbase/log"
|
||||
"github.com/safing/portbase/modules"
|
||||
)
|
||||
|
||||
const (
|
||||
logTTL = 30 * 24 * time.Hour
|
||||
logFileDir = "logs"
|
||||
logFileSuffix = ".log"
|
||||
)
|
||||
|
||||
func registerLogCleaner() {
|
||||
module.NewTask("log cleaner", logCleaner).
|
||||
Repeat(24 * time.Hour).
|
||||
Schedule(time.Now().Add(15 * time.Minute))
|
||||
}
|
||||
|
||||
func logCleaner(_ context.Context, _ *modules.Task) error {
|
||||
ageThreshold := time.Now().Add(-logTTL)
|
||||
|
||||
return filepath.Walk(
|
||||
filepath.Join(dataroot.Root().Path, logFileDir),
|
||||
func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
log.Warningf("core: failed to access %s while deleting old log files: %s", path, err)
|
||||
return nil
|
||||
}
|
||||
|
||||
switch {
|
||||
case !info.Mode().IsRegular():
|
||||
// Only delete regular files.
|
||||
case !strings.HasSuffix(path, logFileSuffix):
|
||||
// Only delete files that end with the correct suffix.
|
||||
case info.ModTime().After(ageThreshold):
|
||||
// Only delete files that are older that the log TTL.
|
||||
default:
|
||||
// Delete log file.
|
||||
err := os.Remove(path)
|
||||
if err != nil {
|
||||
log.Warningf("core: failed to delete old log file %s: %s", path, err)
|
||||
} else {
|
||||
log.Tracef("core: deleted old log file %s", path)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
Loading…
Add table
Reference in a new issue