Skip to content
Open
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
9 changes: 8 additions & 1 deletion lumberjack.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ type Logger struct {
// using gzip. The default is not to perform compression.
Compress bool `json:"compress" yaml:"compress"`

// BeforeDeleteFunc, if provided, will be called just before an old log file is deleted
BeforeDeleteFunc func(path string)

size int64
file *os.File
mu sync.Mutex
Expand Down Expand Up @@ -357,7 +360,11 @@ func (l *Logger) millRunOnce() error {
}

for _, f := range remove {
errRemove := os.Remove(filepath.Join(l.dir(), f.Name()))
path := filepath.Join(l.dir(), f.Name())
if l.BeforeDeleteFunc != nil {
l.BeforeDeleteFunc(path)
}
errRemove := os.Remove(path)
if err == nil && errRemove != nil {
err = errRemove
}
Expand Down
64 changes: 64 additions & 0 deletions lumberjack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,70 @@ func TestCleanupExistingBackups(t *testing.T) {
fileCount(dir, 2, t)
}

func TestCleanupExistingBackups_CallsCallback(t *testing.T) {
// test that if we start with more backup files than we're supposed to have
// in total, that extra ones get cleaned up when we rotate.

currentTime = fakeTime
megabyte = 1

dir := makeTempDir("TestCleanupExistingBackups", t)
defer os.RemoveAll(dir)

// make 3 backup files

data := []byte("data")
backup := backupFile(dir)
err := ioutil.WriteFile(backup, data, 0644)
isNil(err, t)

newFakeTime()

backup = backupFile(dir)
err = ioutil.WriteFile(backup+compressSuffix, data, 0644)
isNil(err, t)

newFakeTime()

backup = backupFile(dir)
err = ioutil.WriteFile(backup, data, 0644)
isNil(err, t)

// now create a primary log file with some data
filename := logFile(dir)
err = ioutil.WriteFile(filename, data, 0644)
isNil(err, t)

beforeDeleteFuncCallCount := 0

l := &Logger{
Filename: filename,
MaxSize: 10,
MaxBackups: 1,
BeforeDeleteFunc: func(path string) {
beforeDeleteFuncCallCount++
},
}
defer l.Close()

newFakeTime()

b2 := []byte("foooooo!")
n, err := l.Write(b2)
isNil(err, t)
equals(len(b2), n, t)

// we need to wait a little bit since the files get deleted on a different
// goroutine.
<-time.After(time.Millisecond * 10)

// now we should only have 2 files left - the primary and one backup
fileCount(dir, 2, t)

// The BeforeDeleteFunc should have also been called exactly 3 times
equals(3, beforeDeleteFuncCallCount, t)
}

func TestMaxAge(t *testing.T) {
currentTime = fakeTime
megabyte = 1
Expand Down