Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

logging: Fix file rotation mechanism. #7133

Merged
merged 2 commits into from
Mar 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions internal/rotate/file_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,11 @@ func (w *FileWriter) openCurrent() (err error) {
// With time.now() as a reference we'd never rotate the file.
if fileInfo, err := w.current.Stat(); err == nil {
w.expireTime = fileInfo.ModTime().Add(w.interval)
w.bytesWritten = fileInfo.Size()
}

if err = w.rotateIfNeeded(); err != nil {
return err
}
return nil
}
Expand Down
33 changes: 33 additions & 0 deletions internal/rotate/file_writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,22 @@ func TestFileWriter_TimeRotation(t *testing.T) {
assert.Equal(t, 2, len(files))
}

func TestFileWriter_ReopenTimeRotation(t *testing.T) {
tempDir, err := ioutil.TempDir("", "RotationTime")
require.NoError(t, err)
interval, _ := time.ParseDuration("1s")
filePath := filepath.Join(tempDir, "test.log")
err = ioutil.WriteFile(filePath, []byte("Hello World"), 0644)
time.Sleep(1 * time.Second)
assert.NoError(t, err)
writer, err := NewFileWriter(filepath.Join(tempDir, "test.log"), interval, 0, -1)
require.NoError(t, err)
defer func() { writer.Close(); os.RemoveAll(tempDir) }()

files, _ := ioutil.ReadDir(tempDir)
assert.Equal(t, 2, len(files))
}

func TestFileWriter_SizeRotation(t *testing.T) {
tempDir, err := ioutil.TempDir("", "RotationSize")
require.NoError(t, err)
Expand All @@ -59,6 +75,23 @@ func TestFileWriter_SizeRotation(t *testing.T) {
assert.Equal(t, 2, len(files))
}

func TestFileWriter_ReopenSizeRotation(t *testing.T) {
tempDir, err := ioutil.TempDir("", "RotationSize")
require.NoError(t, err)
maxSize := int64(12)
filePath := filepath.Join(tempDir, "test.log")
err = ioutil.WriteFile(filePath, []byte("Hello World"), 0644)
assert.NoError(t, err)
writer, err := NewFileWriter(filepath.Join(tempDir, "test.log"), 0, maxSize, -1)
require.NoError(t, err)
defer func() { writer.Close(); os.RemoveAll(tempDir) }()

_, err = writer.Write([]byte("Hello World Again"))
require.NoError(t, err)
files, _ := ioutil.ReadDir(tempDir)
assert.Equal(t, 2, len(files))
}

func TestFileWriter_DeleteArchives(t *testing.T) {
tempDir, err := ioutil.TempDir("", "RotationDeleteArchives")
require.NoError(t, err)
Expand Down