You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
877 B

package log
import (
"fmt"
"github.com/robfig/cron"
"log"
"sync"
"time"
)
var (
logPath string
once sync.Once
Spec = "@daily"
)
// RegisterRotationWithSpec set up crontab scheduler for log rotation
//
// spec, "* * * * * *"; "@daily"
func RegisterRotationWithSpec(path, spec string) {
if "" == spec {
spec = Spec
}
listening(path, spec)
}
func RegisterRotation(path string) {
listening(path, Spec)
}
func listening(path, spec string) {
once.Do(func() {
logPath = path
rotate()
go _listening(spec)
})
}
func _listening(spec string) {
_c := cron.New()
if err := _c.AddFunc(spec, rotate); nil != err {
panic(fmt.Sprintf("failed to establish crontab job: %s", err.Error()))
} else {
log.Println("log rotation started ...")
}
_c.Start()
select {}
}
func rotate() {
RotateLogger(New(logPath+time.Now().Format("2006-01-02"), logPath))
}