From abaa1bbcac9c0714903f3e586e50fddd91213571 Mon Sep 17 00:00:00 2001 From: JessonChan Date: Wed, 13 Apr 2016 09:05:16 +0800 Subject: [PATCH] file rotate file test --- logs/file.go | 4 ++++ logs/file_test.go | 39 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/logs/file.go b/logs/file.go index 37edecf0..8cf20372 100644 --- a/logs/file.go +++ b/logs/file.go @@ -267,6 +267,10 @@ func (w *fileLogWriter) deleteOldLog() { } }() + if info == nil { + return + } + if !info.IsDir() && info.ModTime().Add(24*time.Hour*time.Duration(w.MaxDays)).Before(time.Now()) { if strings.HasPrefix(filepath.Base(path), filepath.Base(w.fileNameOnly)) && strings.HasSuffix(filepath.Base(path), w.suffix) { diff --git a/logs/file_test.go b/logs/file_test.go index 1fa6cdaa..176f4c1e 100644 --- a/logs/file_test.go +++ b/logs/file_test.go @@ -89,7 +89,7 @@ func TestFile2(t *testing.T) { os.Remove("test2.log") } -func TestFileRotate(t *testing.T) { +func TestFileRotate_01(t *testing.T) { log := NewLogger(10000) log.SetLogger("file", `{"filename":"test3.log","maxlines":4}`) log.Debug("debug") @@ -110,6 +110,43 @@ func TestFileRotate(t *testing.T) { os.Remove("test3.log") } +func TestFileRotate_02(t *testing.T) { + fn1 := "rotate_day.log" + fn2 := "rotate_day." + time.Now().Add(-24*time.Hour).Format("2006-01-02") + ".log" + testFileRotate(t, fn1, fn2) +} + +func TestFileRotate_03(t *testing.T) { + fn1 := "rotate_day.log" + fn := "rotate_day." + time.Now().Add(-24*time.Hour).Format("2006-01-02") + ".log" + os.Create(fn) + fn2 := "rotate_day." + time.Now().Add(-24*time.Hour).Format("2006-01-02") + ".001.log" + testFileRotate(t, fn1, fn2) + os.Remove(fn) +} + +func testFileRotate(t *testing.T, fn1, fn2 string) { + fw := &fileLogWriter{ + Daily: true, + MaxDays: 7, + Rotate: true, + Level: LevelTrace, + Perm: 0660, + } + fw.Init(fmt.Sprintf(`{"filename":"%v","maxdays":1}`, fn1)) + fw.dailyOpenTime = time.Now().Add(-24 * time.Hour) + fw.dailyOpenDate = fw.dailyOpenTime.Day() + fw.WriteMsg(time.Now(), "this is a msg for test", LevelDebug) + + for _, file := range []string{fn1, fn2} { + _, err := os.Stat(file) + if err != nil { + t.FailNow() + } + os.Remove(file) + } +} + func exists(path string) (bool, error) { _, err := os.Stat(path) if err == nil {