diff --git a/core/logx/rotatelogger.go b/core/logx/rotatelogger.go index c8ef43a7..58a609d1 100644 --- a/core/logx/rotatelogger.go +++ b/core/logx/rotatelogger.go @@ -381,7 +381,15 @@ func (l *RotateLogger) startWorker() { case event := <-l.channel: l.write(event) case <-l.done: - return + // avoid losing logs before closing. + for { + select { + case event := <-l.channel: + l.write(event) + default: + return + } + } } } }() diff --git a/core/logx/rotatelogger_test.go b/core/logx/rotatelogger_test.go index 68269f6e..ff0fdea1 100644 --- a/core/logx/rotatelogger_test.go +++ b/core/logx/rotatelogger_test.go @@ -206,6 +206,27 @@ func TestRotateLoggerClose(t *testing.T) { _, err := logger.Write([]byte("foo")) 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) {