Skip to content

Commit

Permalink
fix error handler on WrapNew/NopLogger cause nil pointer exception (#81)
Browse files Browse the repository at this point in the history
  • Loading branch information
qneyrat authored Apr 14, 2022
1 parent 1fd9085 commit bef535c
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
4 changes: 2 additions & 2 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,12 +115,12 @@ func (l *Logger) WrapNew(middlewares ...MiddlewareInterface) LoggerInterface {
for _, middleware := range middlewares {
handler = middleware(handler)
}
return &Logger{handler: handler}
return &Logger{handler: handler, ErrorHandler: l.ErrorHandler}
}

// NewNopLogger will create a new no operating logger that log nowhere
func NewNopLogger() *Logger {
return &Logger{handler: NopHandler}
return NewLogger(NopHandler)
}

// NewLogger will return a new logger
Expand Down
36 changes: 36 additions & 0 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"log"
"log/syslog"
"os"
"reflect"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -251,6 +252,41 @@ func TestNewLogger_WrapNew(t *testing.T) {
assert.Equal(t, 4, i)
}

func TestNewLogger_WrapNewErrorHandler(t *testing.T) {
mockHandlerCalled := false
mockHandler := func(entry logger.Entry) error {
mockHandlerCalled = true
assert.Equal(t, "l message", entry.Message)
assert.Equal(t, logger.DebugLevel, entry.Level)
assert.Equal(t, logger.Context{}, *entry.Context)

return errors.New("my handler error")
}
errorHandlerCalled := false
l := logger.NewLogger(mockHandler)
l.ErrorHandler = func(err error, entry logger.Entry) {
errorHandlerCalled = true
assert.EqualError(t, err, "my handler error")
}

l2 := l.WrapNew()

ptr1 := reflect.ValueOf(l.ErrorHandler).Pointer()
ptr2 := reflect.ValueOf(l2.(*logger.Logger).ErrorHandler).Pointer()
assert.Equal(t, ptr1, ptr2)

l.Debug("l message")
assert.True(t, mockHandlerCalled)
assert.True(t, errorHandlerCalled)

mockHandlerCalled = false
errorHandlerCalled = false

l2.Debug("l message")
assert.True(t, mockHandlerCalled)
assert.True(t, errorHandlerCalled)
}

// =====================================================================================================================
// ================================================= EXAMPLES ==========================================================
// =====================================================================================================================
Expand Down

0 comments on commit bef535c

Please sign in to comment.