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

log: SyncLogger: defer mutex unlocks for panic safety #974

Merged
merged 1 commit into from
Apr 12, 2020
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
15 changes: 6 additions & 9 deletions log/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,8 @@ type syncWriter struct {
// progress, the calling goroutine blocks until the syncWriter is available.
func (w *syncWriter) Write(p []byte) (n int, err error) {
w.Lock()
n, err = w.Writer.Write(p)
w.Unlock()
return n, err
defer w.Unlock()
return w.Writer.Write(p)
}

// fdWriter is an io.Writer that also has an Fd method. The most common
Expand All @@ -87,9 +86,8 @@ type fdSyncWriter struct {
// progress, the calling goroutine blocks until the fdSyncWriter is available.
func (w *fdSyncWriter) Write(p []byte) (n int, err error) {
w.Lock()
n, err = w.fdWriter.Write(p)
w.Unlock()
return n, err
defer w.Unlock()
return w.fdWriter.Write(p)
}

// syncLogger provides concurrent safe logging for another Logger.
Expand All @@ -110,7 +108,6 @@ func NewSyncLogger(logger Logger) Logger {
// progress, the calling goroutine blocks until the syncLogger is available.
func (l *syncLogger) Log(keyvals ...interface{}) error {
l.mu.Lock()
err := l.logger.Log(keyvals...)
l.mu.Unlock()
return err
defer l.mu.Unlock()
return l.logger.Log(keyvals...)
}
18 changes: 18 additions & 0 deletions log/sync_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,21 @@ func TestSyncWriterFd(t *testing.T) {
t.Error("NewSyncWriter does not pass through Fd method")
}
}

func TestSyncLoggerPanic(t *testing.T) {
var logger log.Logger
logger = log.LoggerFunc(func(...interface{}) error { panic("!") })
logger = log.NewSyncLogger(logger)

f := func() {
defer func() {
if x := recover(); x != nil {
t.Log(x)
}
}()
logger.Log("hello", "world")
}

f()
f() // without defer Unlock, this one can deadlock
}