Skip to content

Commit

Permalink
Handle discard all logfiles properly
Browse files Browse the repository at this point in the history
Fixes #6892.

The [docs](https://www.consul.io/docs/agent/options.html#_log_rotate_max_files) are stating:

> -log-rotate-max-files - to specify the maximum number of older log
> file archives to keep. Defaults to 0 (no files are ever deleted). Set to
> -1 to disable rotation and discard all log files.

But the `-1` case was not implemented and led to a panic when being
used.
  • Loading branch information
hanshasselberg committed Dec 13, 2019
1 parent 9003f8b commit 640717d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
10 changes: 8 additions & 2 deletions logger/logfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,14 @@ func (l *LogFile) pruneFiles() error {
if err != nil {
return err
}
// Prune if there are more files stored than the configured max
stale := len(matches) - l.MaxFiles
var stale int
if l.MaxFiles == -1 {
// Prune everything
stale = len(matches)
} else {
// Prune if there are more files stored than the configured max
stale = len(matches) - l.MaxFiles
}
for i := 0; i < stale; i++ {
if err := os.Remove(matches[i]); err != nil {
return err
Expand Down
27 changes: 26 additions & 1 deletion logger/logfile_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ func TestLogFile_deleteArchives(t *testing.T) {

func TestLogFile_deleteArchivesDisabled(t *testing.T) {
t.Parallel()
tempDir := testutil.TempDir(t, "LogWriteDeleteArchivesDisabled")
tempDir := testutil.TempDir(t, t.Name())
defer os.Remove(tempDir)
filt := LevelFilter()
filt.MinLevel = logutils.LogLevel("INFO")
Expand All @@ -158,3 +158,28 @@ func TestLogFile_deleteArchivesDisabled(t *testing.T) {
return
}
}

func TestLogFile_rotationDisabled(t *testing.T) {
t.Parallel()
tempDir := testutil.TempDir(t, t.Name())
defer os.Remove(tempDir)
filt := LevelFilter()
filt.MinLevel = logutils.LogLevel("INFO")
logFile := LogFile{
logFilter: filt,
fileName: testFileName,
logPath: tempDir,
MaxBytes: testBytes,
duration: 24 * time.Hour,
MaxFiles: -1,
}
logFile.Write([]byte("[INFO] Hello World"))
logFile.Write([]byte("[INFO] Second File"))
logFile.Write([]byte("[INFO] Third File"))
want := 1
tempFiles, _ := ioutil.ReadDir(tempDir)
if got := tempFiles; len(got) != want {
t.Errorf("Expected %d files, got %v file(s)", want, len(got))
return
}
}

0 comments on commit 640717d

Please sign in to comment.