From 5621e17948a898b91943c172eac2dc5e5f0daa0a Mon Sep 17 00:00:00 2001 From: evilolipop Date: Mon, 18 Mar 2024 17:55:35 +0800 Subject: [PATCH] fix: rotating every line after first interval --- rotate_file.go | 1 + rotate_file_test.go | 35 +++++++++++++++++++---------------- 2 files changed, 20 insertions(+), 16 deletions(-) diff --git a/rotate_file.go b/rotate_file.go index 5af0886..77aa16d 100644 --- a/rotate_file.go +++ b/rotate_file.go @@ -88,6 +88,7 @@ func (r *RotateFile) rotate() { r.file.Close() } r.file = file + r.written = 0 r.lastRotate = now } } diff --git a/rotate_file_test.go b/rotate_file_test.go index 2df7d25..7583a30 100644 --- a/rotate_file_test.go +++ b/rotate_file_test.go @@ -28,17 +28,19 @@ func TestRotateSize(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(path) - file, err := NewRotateFile(path, "test", 10) + file, err := NewRotateFile(path, "test", 100) require.NoError(t, err) - _, err = file.Write([]byte("12345678901234567890")) - require.NoError(t, err) - _, err = file.Write([]byte("12345678901234567890")) - require.NoError(t, err) + b := []byte("test\n") + for range 100 { + require.NoError(t, err) + _, err = file.Write(b) + require.NoError(t, err) + } dir, err := os.ReadDir(path) require.NoError(t, err) - require.Len(t, dir, 3) + require.Len(t, dir, 5) } func TestRotateInterval(t *testing.T) { @@ -46,23 +48,24 @@ func TestRotateInterval(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(path) - file, err := NewRotateFile(path, "test", 1024, WithCheckEveryN(2), WithRotateInterval(1*time.Second)) + file, err := NewRotateFile(path, "test", 1024, WithCheckEveryN(1), WithRotateInterval(100*time.Millisecond)) require.NoError(t, err) - _, err = file.Write([]byte("1")) - require.NoError(t, err) - _, err = file.Write([]byte("2")) - require.NoError(t, err) + b := []byte("test\n") + 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) - time.Sleep(1 * time.Second) - _, err = file.Write([]byte("1")) - require.NoError(t, err) - _, err = file.Write([]byte("2")) - require.NoError(t, err) + time.Sleep(100 * time.Millisecond) + for range 5 { + _, err = file.Write(b) + require.NoError(t, err) + } dir, err = os.ReadDir(path) require.NoError(t, err)