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) +}