Skip to content

Commit 97c15dd

Browse files
committed
log/rollwriter: skip buffer and write directly when data packet exceeds expected size
1 parent c56a795 commit 97c15dd

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

log/rollwriter/async_roll_writer.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,17 @@ func (w *AsyncRollWriter) batchWriteLog() {
117117
buffer.Reset()
118118
}
119119
case data := <-w.logQueue:
120+
if len(data) >= w.opts.WriteLogSize {
121+
// If the length of the current data exceeds the expected maximum value,
122+
// we directly write it to the underlying logger instead of placing it into the buffer.
123+
// This prevents the buffer from being overwhelmed by excessively large data,
124+
// which could lead to memory leaks.
125+
// Prior to that, we need to write the existing data in the buffer to the underlying logger.
126+
_, _ = w.logger.Write(buffer.Bytes())
127+
buffer.Reset()
128+
_, _ = w.logger.Write(data)
129+
continue
130+
}
120131
buffer.Write(data)
121132
if buffer.Len() >= w.opts.WriteLogSize {
122133
_, err := w.logger.Write(buffer.Bytes())

log/rollwriter/roll_writer_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,16 @@ func TestAsyncRollWriterSyncTwice(t *testing.T) {
376376
require.Nil(t, w.Close())
377377
}
378378

379+
func TestAsyncRollWriterDirectWrite(t *testing.T) {
380+
logSize := 1
381+
w := NewAsyncRollWriter(&noopWriteCloser{}, WithWriteLogSize(logSize))
382+
_, _ = w.Write([]byte("hello"))
383+
time.Sleep(time.Millisecond)
384+
require.Nil(t, w.Sync())
385+
require.Nil(t, w.Sync())
386+
require.Nil(t, w.Close())
387+
}
388+
379389
func TestRollWriterError(t *testing.T) {
380390
logDir := t.TempDir()
381391
t.Run("reopen file", func(t *testing.T) {

0 commit comments

Comments
 (0)