소스 검색

日志分割

xuzhiheng 2 년 전
부모
커밋
8e339c3e48
1개의 변경된 파일73개의 추가작업 그리고 0개의 파일을 삭제
  1. 73 0
      telemarketingEtl/config/log.go

+ 73 - 0
telemarketingEtl/config/log.go

@@ -0,0 +1,73 @@
+package config
+
+/**
+日志文件自动切换,默认保留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 * * ?", 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)
+}