Skip to content

Commit

Permalink
Config: Validate Level and EncoderConfig (#791)
Browse files Browse the repository at this point in the history
This adds validation for Level and EncoderConfig.EncoderTime when
building a logger from a zap.Config.

Resolves #777

Co-authored-by: Abhinav Gupta <abg@uber.com>
  • Loading branch information
YashishDua and abhinav authored Mar 4, 2020
1 parent c89bd3c commit 2c14fe6
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
5 changes: 5 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
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{}) {
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
Original file line number Diff line number Diff line change
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()
require.Error(t, err)
assert.Equal(t, tt.expectErr, err.Error())
})
}
}
4 changes: 4 additions & 0 deletions encoder.go
Original file line number Diff line number Diff line change
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

0 comments on commit 2c14fe6

Please sign in to comment.