package applog import ( "os" "path/filepath" "testing" "time" ) func TestDailyFileWriterRotatesAndCleans(t *testing.T) { dir := t.TempDir() logFile := filepath.Join(dir, "app.log") w, err := newDailyFileWriter(logFile) if err != nil { t.Fatalf("new writer: %v", err) } defer w.Close() // 写入当天日志,文件应按 app-YYYYMMDD.log 命名 today := time.Now().Format("20060102") if _, err := w.Write([]byte("line1\n")); err != nil { t.Fatalf("write: %v", err) } todayPath := filepath.Join(dir, "app-"+today+".log") if _, err := os.Stat(todayPath); err != nil { t.Fatalf("today log file missing: %v", err) } // 旧格式 app.log 不应被创建 if _, err := os.Stat(logFile); err == nil { t.Fatalf("old-style app.log should not be created") } // 构造过期文件,cleanup 应删除(保留 30 天,这里用 3 天验证) old := filepath.Join(dir, "app-20260701.log") if err := os.WriteFile(old, []byte("old"), 0o644); err != nil { t.Fatalf("create old file: %v", err) } w.cleanup(time.Now()) if _, err := os.Stat(old); err == nil { t.Fatalf("old log file should be cleaned") } // 当天的文件应保留 if _, err := os.Stat(todayPath); err != nil { t.Fatalf("today log file should be kept") } }