fix: avoid losing logs before closing (#3573)

master
xt-inking 1 year ago committed by GitHub
parent 0dcede6457
commit 5e435b6a76
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -381,9 +381,17 @@ func (l *RotateLogger) startWorker() {
case event := <-l.channel: case event := <-l.channel:
l.write(event) l.write(event)
case <-l.done: case <-l.done:
// avoid losing logs before closing.
for {
select {
case event := <-l.channel:
l.write(event)
default:
return return
} }
} }
}
}
}() }()
} }

@ -206,6 +206,27 @@ func TestRotateLoggerClose(t *testing.T) {
_, err := logger.Write([]byte("foo")) _, err := logger.Write([]byte("foo"))
assert.ErrorIs(t, err, ErrLogFileClosed) assert.ErrorIs(t, err, ErrLogFileClosed)
}) })
t.Run("close without losing logs", func(t *testing.T) {
text := "foo"
filename, err := fs.TempFilenameWithText(text)
assert.Nil(t, err)
if len(filename) > 0 {
defer os.Remove(filename)
}
logger, err := NewLogger(filename, new(DailyRotateRule), false)
assert.Nil(t, err)
msg := []byte("foo")
n := 100
for i := 0; i < n; i++ {
_, err = logger.Write(msg)
assert.Nil(t, err)
}
assert.Nil(t, logger.Close())
bs, err := os.ReadFile(filename)
assert.Nil(t, err)
assert.Equal(t, len(msg)*n+len(text), len(bs))
})
} }
func TestRotateLoggerGetBackupFilename(t *testing.T) { func TestRotateLoggerGetBackupFilename(t *testing.T) {

Loading…
Cancel
Save