rotate log files each week

use the current timestamp rather than the startup timestamp for new log files
This commit is contained in:
Azareal 2021-04-07 11:07:24 +10:00
parent 7b3cf6877f
commit b5e8cbf87c
1 changed files with 12 additions and 10 deletions

View File

@ -9,6 +9,7 @@ import (
"strings" "strings"
"sync" "sync"
"sync/atomic" "sync/atomic"
"time"
c "github.com/Azareal/Gosora/common" c "github.com/Azareal/Gosora/common"
) )
@ -56,26 +57,27 @@ type RouterLog struct {
} }
func (r *GenRouter) DailyTick() error { func (r *GenRouter) DailyTick() error {
currentTime := time.Now()
rotateLog := func(l *RouterLog, name string) error { rotateLog := func(l *RouterLog, name string) error {
l.Lock() l.Lock()
defer l.Unlock() defer l.Unlock()
f := l.FileVal.Load().(*os.File) f := l.FileVal.Load().(*os.File)
stat, err := f.Stat() stat, e := f.Stat()
if err != nil { if e != nil {
return nil return nil
} }
if stat.Size() < int64(c.Megabyte) { if (stat.Size() < int64(c.Megabyte)) && (currentTime.Sub(c.StartTime).Hours() >= (24 * 7)) {
return nil return nil
} }
if err = f.Close(); err != nil { if e = f.Close(); e != nil {
return err return e
} }
stimestr := strconv.FormatInt(c.StartTime.Unix(), 10) stimestr := strconv.FormatInt(currentTime.Unix(), 10)
f, err = os.OpenFile(c.Config.LogDir+name+stimestr+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0755) f, e = os.OpenFile(c.Config.LogDir+name+stimestr+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0755)
if err != nil { if e != nil {
return err return e
} }
lval := log.New(f, "", log.LstdFlags) lval := log.New(f, "", log.LstdFlags)
l.FileVal.Store(f) l.FileVal.Store(f)