Skip to content

Commit

Permalink
NopLogger: Fix nil Clock panic
Browse files Browse the repository at this point in the history
In #897, we added a `zap.Clock` option to control the source of time
but neglected to set this field on the logger constructed by
`zap.NewNop`. This has the effect of panicking the Nop logger with a nil
dereference.

Fix the nil dereference and add checks for the behavior of the Nop
logger.

Verified that these are the only instantiations of `Logger` in this
package:

```
$ rg '\bLogger\{' *.go
logger_test.go
67:                     for _, logger := range []*Logger{grandparent, parent, child} {

logger.go
71:     log := &Logger{
86:     return &Logger{
```

Refs GO-684
  • Loading branch information
abhinav committed Jun 28, 2021
1 parent 35f15d1 commit 7ea57ce
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
1 change: 1 addition & 0 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ func NewNop() *Logger {
core: zapcore.NewNopCore(),
errorOutput: zapcore.AddSync(ioutil.Discard),
addStack: zapcore.FatalLevel + 1,
clock: zapcore.DefaultClock,
}
}

Expand Down
22 changes: 21 additions & 1 deletion logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,6 @@ func TestLoggerCustomOnFatal(t *testing.T) {
for _, tt := range tests {
t.Run(tt.msg, func(t *testing.T) {
withLogger(t, InfoLevel, opts(OnFatal(tt.onFatal)), func(logger *Logger, logs *observer.ObservedLogs) {

var finished bool
recovered := make(chan interface{})
go func() {
Expand All @@ -580,6 +579,27 @@ func TestLoggerCustomOnFatal(t *testing.T) {
}
}

func TestNopLogger(t *testing.T) {
logger := NewNop()

t.Run("basic levels", func(t *testing.T) {
logger.Debug("foo", String("k", "v"))
logger.Info("bar", Int("x", 42))
logger.Warn("baz", Strings("ks", []string{"a", "b"}))
logger.Error("qux", Error(errors.New("great sadness")))
})

t.Run("DPanic", func(t *testing.T) {
logger.With(String("component", "whatever")).DPanic("stuff")
})

t.Run("Panic", func(t *testing.T) {
assert.Panics(t, func() {
logger.Panic("great sadness")
}, "Nop logger should still cause panics.")
})
}

func infoLog(logger *Logger, msg string, fields ...Field) {
logger.Info(msg, fields...)
}
Expand Down

0 comments on commit 7ea57ce

Please sign in to comment.