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

EncoderConfig and AtomicLevel validation added #791

Merged
merged 9 commits into from Mar 4, 2020
5 changes: 5 additions & 0 deletions config.go
Expand Up @@ -21,6 +21,7 @@
package zap

import (
"fmt"
"sort"
"time"

Expand Down Expand Up @@ -174,6 +175,10 @@ func (cfg Config) Build(opts ...Option) (*Logger, error) {
return nil, err
}

if cfg.Level == (AtomicLevel{}) {
abhinav marked this conversation as resolved.
Show resolved Hide resolved
return nil, fmt.Errorf("missing Level")
}

log := New(
zapcore.NewCore(enc, sink, cfg.Level),
cfg.buildOptions(errSink)...,
Expand Down
38 changes: 38 additions & 0 deletions config_test.go
Expand Up @@ -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) {
Expand Down Expand Up @@ -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()
abhinav marked this conversation as resolved.
Show resolved Hide resolved
require.Error(t, err)
assert.Equal(t, tt.expectErr, err.Error())
})
}
}
4 changes: 4 additions & 0 deletions encoder.go
Expand Up @@ -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 == "" {
Expand Down