Fix log rotation to use actual file size instead of bytes written (#7133)

This commit is contained in:
Harshit Bansal 2020-03-11 00:37:42 +05:30 committed by GitHub
parent 1ce56f8b59
commit 134af0fe4b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 38 additions and 0 deletions

View File

@ -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
}

View File

@ -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)
@ -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)