Skip to content

Commit

Permalink
Add Must(*Logger, error) *Logger function (#1105)
Browse files Browse the repository at this point in the history
  • Loading branch information
Craig Pastro authored Jun 3, 2022
1 parent 41970cf commit e06e09a
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 8 deletions.
10 changes: 2 additions & 8 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,7 @@ func Example_basicConfiguration() {
if err := json.Unmarshal(rawJSON, &cfg); err != nil {
panic(err)
}
logger, err := cfg.Build()
if err != nil {
panic(err)
}
logger := zap.Must(cfg.Build())
defer logger.Sync()

logger.Info("logger construction succeeded")
Expand Down Expand Up @@ -278,10 +275,7 @@ func ExampleAtomicLevel_config() {
if err := json.Unmarshal(rawJSON, &cfg); err != nil {
panic(err)
}
logger, err := cfg.Build()
if err != nil {
panic(err)
}
logger := zap.Must(cfg.Build())
defer logger.Sync()

logger.Info("info logging enabled")
Expand Down
13 changes: 13 additions & 0 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,19 @@ func NewDevelopment(options ...Option) (*Logger, error) {
return NewDevelopmentConfig().Build(options...)
}

// Must is a helper that wraps a call to a function returning (*Logger, error)
// and panics if the error is non-nil. It is intended for use in variable
// initialization such as:
//
// var logger := zap.Must(zap.NewProduction())
func Must(logger *Logger, err error) *Logger {
if err != nil {
panic(err)
}

return logger
}

// NewExample builds a Logger that's designed for use in zap's testable
// examples. It writes DebugLevel and above logs to standard out as JSON, but
// omits the timestamp and calling function to keep example output
Expand Down
10 changes: 10 additions & 0 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,16 @@ func TestNopLogger(t *testing.T) {
})
}

func TestMust(t *testing.T) {
t.Run("must without an error does not panic", func(t *testing.T) {
assert.NotPanics(t, func() { Must(NewNop(), nil) }, "must paniced with no error")
})

t.Run("must with an error panics", func(t *testing.T) {
assert.Panics(t, func() { Must(nil, errors.New("an error")) }, "must did not panic with an error")
})
}

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

0 comments on commit e06e09a

Please sign in to comment.