package main /** 日志文件自动切换,默认保留15天内日志 **/ import ( "log" "os" "path/filepath" "regexp" "time" "github.com/go-xweb/xweb" "github.com/robfig/cron" ) // 日志格式 var fileReg = regexp.MustCompile("^(\\d{4}_[0-9_]{14})\\.log$") // 当前日志文件句柄 var LogFile *os.File // 时间格式 var FMT = "2006_01_02_15_04_05" // 日志目录 var LogPath = "./jylog" func init() { os.Mkdir(LogPath, os.ModePerm) //默认保留15天内的日志,-1为永久保留 initLog(15) } func initLog(saveDay int) { go logfile() task := cron.New() task.Start() task.AddFunc("0 0 0/2 * * ?", func() { go logfile() time.Sleep(50 * time.Second) if saveDay > 0 { filepath.Walk(LogPath, func(path string, info os.FileInfo, err error) error { str := fileReg.FindStringSubmatch(info.Name()) if len(str) == 2 { t, er := time.ParseInLocation(FMT, str[1], time.Local) if er == nil { if (time.Now().Unix()-t.Unix())/86400 > int64(saveDay) { log.Println("delete log file:", path, os.Remove(path)) } } } return nil }) } }) } // 创建并切换输出文件 func logfile() { now := time.Now().Format(FMT) file, _ := os.Create(LogPath + "/" + now + ".log") log.SetOutput(file) xweb.RootApp().Logger.SetOutput(file) go func(file *os.File) { time.Sleep(5 * time.Second) if LogFile != nil { LogFile.Close() } LogFile = file }(file) }