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
12 changes: 9 additions & 3 deletions zapcore/buffered_write_syncer.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ package zapcore

import (
"bufio"
"io"
"sync"
"time"

Expand Down Expand Up @@ -134,10 +135,15 @@ func (s *BufferedWriteSyncer) initialize() {

// Write writes log data into buffer syncer directly, multiple Write calls will be batched,
// and log data will be flushed to disk when the buffer is full or periodically.
// Write returns io.ErrClosedPipe after Stop has been called.
func (s *BufferedWriteSyncer) Write(bs []byte) (int, error) {
s.mu.Lock()
defer s.mu.Unlock()

if s.stopped {
return 0, io.ErrClosedPipe
}

if !s.initialized {
s.initialize()
}
Expand Down Expand Up @@ -193,14 +199,14 @@ func (s *BufferedWriteSyncer) Stop() (err error) {
s.mu.Lock()
defer s.mu.Unlock()

if !s.initialized {
if s.stopped {
return false
}
s.stopped = true

if s.stopped {
if !s.initialized {
return false
}
s.stopped = true

s.ticker.Stop()
close(s.stop) // tell flushLoop to stop
Expand Down
28 changes: 28 additions & 0 deletions zapcore/buffered_write_syncer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ package zapcore

import (
"bytes"
"io"
"testing"
"time"

Expand Down Expand Up @@ -146,3 +147,30 @@ func TestBufferWriterWithoutStart(t *testing.T) {
assert.NoError(t, ws.Sync(), "Sync must not fail")
})
}

func TestBufferedWriteSyncerWriteAfterStop(t *testing.T) {
for _, initialized := range []bool{false, true} {
name := "before first write"
if initialized {
name = "after first write"
}
t.Run(name, func(t *testing.T) {
buf := &bytes.Buffer{}
ws := &BufferedWriteSyncer{WS: AddSync(buf)}
t.Cleanup(func() { assert.NoError(t, ws.Stop()) })
if initialized {
requireWriteWorks(t, ws)
}
require.NoError(t, ws.Stop())
before := buf.String()
for attempt := 0; attempt < 2; attempt++ {
n, err := ws.Write([]byte("lost log"))
assert.Zero(t, n)
assert.ErrorIs(t, err, io.ErrClosedPipe)
require.NoError(t, ws.Stop())
}
require.NoError(t, ws.Sync())
assert.Equal(t, before, buf.String())
})
}
}