diff --git a/config.go b/config.go index 6fe17d9e0..eae1d237f 100644 --- a/config.go +++ b/config.go @@ -21,6 +21,7 @@ package zap import ( + "fmt" "sort" "time" @@ -174,6 +175,10 @@ func (cfg Config) Build(opts ...Option) (*Logger, error) { return nil, err } + if cfg.Level == (AtomicLevel{}) { + return nil, fmt.Errorf("missing Level") + } + log := New( zapcore.NewCore(enc, sink, cfg.Level), cfg.buildOptions(errSink)..., diff --git a/config_test.go b/config_test.go index 7a875703b..0fa4b1efc 100644 --- a/config_test.go +++ b/config_test.go @@ -27,6 +27,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "go.uber.org/zap/zapcore" ) func TestConfig(t *testing.T) { @@ -106,3 +107,40 @@ func TestConfigWithInvalidPaths(t *testing.T) { }) } } + +func TestConfigWithMissingAttributes(t *testing.T) { + tests := []struct { + desc string + cfg Config + expectErr string + }{ + { + desc: "missing level", + cfg: Config{ + Encoding: "json", + }, + expectErr: "missing Level", + }, + { + desc: "missing encoder time in encoder config", + cfg: Config{ + Level: NewAtomicLevelAt(zapcore.InfoLevel), + Encoding: "json", + EncoderConfig: zapcore.EncoderConfig{ + MessageKey: "msg", + TimeKey: "ts", + }, + }, + expectErr: "missing EncodeTime in EncoderConfig", + }, + } + + for _, tt := range tests { + t.Run(tt.desc, func(t *testing.T) { + cfg := tt.cfg + _, err := cfg.Build() + require.Error(t, err) + assert.Equal(t, tt.expectErr, err.Error()) + }) + } +} diff --git a/encoder.go b/encoder.go index 2e9d3c341..08ed83354 100644 --- a/encoder.go +++ b/encoder.go @@ -62,6 +62,10 @@ func RegisterEncoder(name string, constructor func(zapcore.EncoderConfig) (zapco } func newEncoder(name string, encoderConfig zapcore.EncoderConfig) (zapcore.Encoder, error) { + if encoderConfig.TimeKey != "" && encoderConfig.EncodeTime == nil { + return nil, fmt.Errorf("missing EncodeTime in EncoderConfig") + } + _encoderMutex.RLock() defer _encoderMutex.RUnlock() if name == "" {