Skip to content

Commit

Permalink
Fix log rotation to use actual file size instead of bytes written (in…
Browse files Browse the repository at this point in the history
  • Loading branch information
HarshitOnGitHub authored Mar 10, 2020
1 parent bd1b582 commit d63c7ff
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
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

0 comments on commit d63c7ff

Please sign in to comment.