Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(logger): Make MockLogger threadsafe #441

Merged
merged 1 commit into from
Aug 16, 2024
Merged
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
23 changes: 20 additions & 3 deletions internals/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,27 @@ func Debugf(format string, v ...interface{}) {
logger.Debug(msg)
}

type lockedBytesBuffer struct {
buffer bytes.Buffer
mutex sync.Mutex
}

func (b *lockedBytesBuffer) Write(p []byte) (int, error) {
b.mutex.Lock()
defer b.mutex.Unlock()
return b.buffer.Write(p)
}

func (b *lockedBytesBuffer) String() string {
b.mutex.Lock()
defer b.mutex.Unlock()
return b.buffer.String()
}

// MockLogger replaces the existing logger with a buffer and returns
// the log buffer and a restore function.
func MockLogger(prefix string) (buf *bytes.Buffer, restore func()) {
buf = &bytes.Buffer{}
// a Stringer returning the log buffer content and a restore function.
func MockLogger(prefix string) (fmt.Stringer, func()) {
buf := &lockedBytesBuffer{}
oldLogger := SetLogger(New(buf, prefix))
return buf, func() {
SetLogger(oldLogger)
Expand Down
20 changes: 19 additions & 1 deletion internals/logger/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@ package logger_test

import (
"bytes"
"fmt"
"os"
"testing"

. "gopkg.in/check.v1"
"gopkg.in/tomb.v2"

"github.com/canonical/pebble/internals/logger"
)
Expand All @@ -30,7 +32,7 @@ func Test(t *testing.T) { TestingT(t) }
var _ = Suite(&LogSuite{})

type LogSuite struct {
logbuf *bytes.Buffer
logbuf fmt.Stringer
restoreLogger func()
}

Expand Down Expand Up @@ -75,3 +77,19 @@ func (s *LogSuite) TestPanicf(c *C) {
c.Check(func() { logger.Panicf("xyzzy") }, Panics, "xyzzy")
c.Check(s.logbuf.String(), Matches, `20\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ PREFIX: PANIC xyzzy\n`)
}

func (s *LogSuite) TestMockLoggerReadWriteThreadsafe(c *C) {
var t tomb.Tomb
t.Go(func() error {
for i := 0; i < 100; i++ {
logger.Noticef("foo")
logger.Noticef("bar")
}
return nil
})
for i := 0; i < 10; i++ {
logger.Noticef(s.logbuf.String())
}
err := t.Wait()
c.Check(err, IsNil)
}
Loading