rotate log files

This commit is contained in:
chrislu 2022-12-11 21:05:58 -08:00
parent fc6b9e6e0c
commit ac9dea0ad9
2 changed files with 36 additions and 2 deletions

View file

@ -25,6 +25,7 @@ import (
"os" "os"
"os/user" "os/user"
"path/filepath" "path/filepath"
"sort"
"strings" "strings"
"sync" "sync"
"time" "time"
@ -32,6 +33,7 @@ import (
// MaxSize is the maximum size of a log file in bytes. // MaxSize is the maximum size of a log file in bytes.
var MaxSize uint64 = 1024 * 1024 * 1800 var MaxSize uint64 = 1024 * 1024 * 1800
var MaxFileCount = 5
// logDirs lists the candidate directories for new log files. // logDirs lists the candidate directories for new log files.
var logDirs []string var logDirs []string
@ -43,8 +45,9 @@ var logDir = flag.String("logdir", "", "If non-empty, write log files in this di
func createLogDirs() { func createLogDirs() {
if *logDir != "" { if *logDir != "" {
logDirs = append(logDirs, *logDir) logDirs = append(logDirs, *logDir)
} } else {
logDirs = append(logDirs, os.TempDir()) logDirs = append(logDirs, os.TempDir())
}
} }
var ( var (
@ -96,6 +99,15 @@ func logName(tag string, t time.Time) (name, link string) {
return name, program + "." + tag return name, program + "." + tag
} }
func prefix(tag string) string {
return fmt.Sprintf("%s.%s.%s.log.%s.",
program,
host,
userName,
tag,
)
}
var onceLogDirs sync.Once var onceLogDirs sync.Once
// create creates a new log file and returns the file and its filename, which // create creates a new log file and returns the file and its filename, which
@ -108,8 +120,29 @@ func create(tag string, t time.Time) (f *os.File, filename string, err error) {
return nil, "", errors.New("log: no log dirs") return nil, "", errors.New("log: no log dirs")
} }
name, link := logName(tag, t) name, link := logName(tag, t)
logPrefix := prefix(tag)
var lastErr error var lastErr error
for _, dir := range logDirs { for _, dir := range logDirs {
// remove old logs
entries, _ := os.ReadDir(dir)
var previousLogs []string
for _, entry := range entries {
if strings.HasPrefix(entry.Name(), logPrefix) {
previousLogs = append(previousLogs, entry.Name())
}
}
if len(previousLogs) >= MaxFileCount {
sort.Strings(previousLogs)
for i, entry := range previousLogs {
if i > len(previousLogs)-MaxFileCount {
break
}
os.Remove(filepath.Join(dir, entry))
}
}
// create new log file
fname := filepath.Join(dir, name) fname := filepath.Join(dir, name)
f, err := os.Create(fname) f, err := os.Create(fname)
if err == nil { if err == nil {

View file

@ -46,7 +46,8 @@ func init() {
} }
func main() { func main() {
glog.MaxSize = 1024 * 1024 * 32 glog.MaxSize = 1024 * 1024 * 10
glog.MaxFileCount = 5
rand.Seed(time.Now().UnixNano()) rand.Seed(time.Now().UnixNano())
flag.Usage = usage flag.Usage = usage