Skip to content

Commit

Permalink
Config: Validate Level and EncoderConfig (uber-go#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 uber-go#777

Co-authored-by: Abhinav Gupta <abg@uber.com>
  • Loading branch information
YashishDua and abhinav committed Mar 4, 2020
1 parent f717832 commit 6c8685c
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
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{}) {
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()
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

0 comments on commit 6c8685c

Please sign in to comment.