From 29f118d2b195b4ccb5b5119b2ec1330fd88b9a58 Mon Sep 17 00:00:00 2001 From: evilolipop Date: Wed, 28 Aug 2024 18:26:12 +0800 Subject: [PATCH] feat: create file after remove --- rotate_file.go | 5 +++++ rotate_file_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/rotate_file.go b/rotate_file.go index 593bfda..55d9e78 100644 --- a/rotate_file.go +++ b/rotate_file.go @@ -64,6 +64,11 @@ func (r *RotateFile) Write(p []byte) (int, error) { r.count++ if r.count >= r.checkEveryN { r.count = 0 + _, err := os.Open(r.file.Name()) + if err != nil { + r.rotate() + } + if r.rotateAtMidnight { if time.Now().Day() != r.lastRotate.Day() { r.rotate() diff --git a/rotate_file_test.go b/rotate_file_test.go index 7583a30..b0e0e67 100644 --- a/rotate_file_test.go +++ b/rotate_file_test.go @@ -71,3 +71,32 @@ func TestRotateInterval(t *testing.T) { require.NoError(t, err) require.Len(t, dir, 2) } + +func TestCreateFileAfterRemove(t *testing.T) { + path, err := os.MkdirTemp("", "loghtest-TestRotateInterval") + require.NoError(t, err) + defer os.RemoveAll(path) + + file, err := NewRotateFile(path, "test", 1024*1024*1024, WithCheckEveryN(3)) + require.NoError(t, err) + + b := []byte("test\n") + for range 5 { + _, err = file.Write(b) + require.NoError(t, err) + } + + os.Remove(file.file.Name()) + dir, err := os.ReadDir(path) + require.NoError(t, err) + require.Len(t, dir, 0) + + for range 5 { + _, err = file.Write(b) + require.NoError(t, err) + } + + dir, err = os.ReadDir(path) + require.NoError(t, err) + require.Len(t, dir, 1) +}