Skip to content

Commit

Permalink
goroutine-safe BufferLogger
Browse files Browse the repository at this point in the history
  • Loading branch information
gwinn authored Apr 22, 2022
2 parents e7d06fa + 7124c80 commit 27aee62
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
14 changes: 14 additions & 0 deletions core/util/testutil/buffer_logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"io"
"os"
"sync"

"github.com/op/go-logging"

Expand All @@ -29,6 +30,7 @@ type BufferedLogger interface {
// BufferLogger is an implementation of the BufferedLogger.
type BufferLogger struct {
buf bytes.Buffer
rw sync.RWMutex
}

// NewBufferedLogger returns new BufferedLogger instance.
Expand All @@ -38,29 +40,41 @@ func NewBufferedLogger() BufferedLogger {

// Read bytes from the logger buffer. io.Reader implementation.
func (l *BufferLogger) Read(p []byte) (n int, err error) {
defer l.rw.RUnlock()
l.rw.RLock()
return l.buf.Read(p)
}

// String contents of the logger buffer. fmt.Stringer implementation.
func (l *BufferLogger) String() string {
defer l.rw.RUnlock()
l.rw.RLock()
return l.buf.String()
}

// Bytes is a shorthand for the underlying bytes.Buffer method. Returns byte slice with the buffer contents.
func (l *BufferLogger) Bytes() []byte {
defer l.rw.RUnlock()
l.rw.RLock()
return l.buf.Bytes()
}

// Reset is a shorthand for the underlying bytes.Buffer method. It will reset buffer contents.
func (l *BufferLogger) Reset() {
defer l.rw.Unlock()
l.rw.Lock()
l.buf.Reset()
}

func (l *BufferLogger) write(level logging.Level, args ...interface{}) {
defer l.rw.Unlock()
l.rw.Lock()
l.buf.WriteString(fmt.Sprintln(append([]interface{}{level.String(), "=>"}, args...)...))
}

func (l *BufferLogger) writef(level logging.Level, format string, args ...interface{}) {
defer l.rw.Unlock()
l.rw.Lock()
l.buf.WriteString(fmt.Sprintf(level.String()+" => "+format, args...))
}

Expand Down
18 changes: 14 additions & 4 deletions core/util/testutil/buffer_logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,6 @@ func (t *BufferLoggerTest) SetupTest() {
t.logger.Reset()
}

func (t *BufferLoggerTest) Log() string {
return t.logger.String()
}

func (t *BufferLoggerTest) Test_Read() {
t.logger.Debug("test")

Expand All @@ -41,3 +37,17 @@ func (t *BufferLoggerTest) Test_Bytes() {
t.logger.Debug("test")
t.Assert().Equal([]byte(logging.DEBUG.String()+" => test\n"), t.logger.Bytes())
}

func (t *BufferLoggerTest) Test_String() {
t.logger.Debug("test")
t.Assert().Equal(logging.DEBUG.String()+" => test\n", t.logger.String())
}

func (t *BufferLoggerTest) TestRace() {
go func() {
t.logger.Debug("test")
}()
go func() {
t.logger.String()
}()
}

0 comments on commit 27aee62

Please sign in to comment.