Skip to content

Commit 2c14fe6

Browse files
YashishDuaabhinav
andauthored
Config: Validate Level and EncoderConfig (#791)
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>
1 parent c89bd3c commit 2c14fe6

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-0
lines changed

config.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
package zap
2222

2323
import (
24+
"fmt"
2425
"sort"
2526
"time"
2627

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

178+
if cfg.Level == (AtomicLevel{}) {
179+
return nil, fmt.Errorf("missing Level")
180+
}
181+
177182
log := New(
178183
zapcore.NewCore(enc, sink, cfg.Level),
179184
cfg.buildOptions(errSink)...,

config_test.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import (
2727

2828
"github.com/stretchr/testify/assert"
2929
"github.com/stretchr/testify/require"
30+
"go.uber.org/zap/zapcore"
3031
)
3132

3233
func TestConfig(t *testing.T) {
@@ -106,3 +107,40 @@ func TestConfigWithInvalidPaths(t *testing.T) {
106107
})
107108
}
108109
}
110+
111+
func TestConfigWithMissingAttributes(t *testing.T) {
112+
tests := []struct {
113+
desc string
114+
cfg Config
115+
expectErr string
116+
}{
117+
{
118+
desc: "missing level",
119+
cfg: Config{
120+
Encoding: "json",
121+
},
122+
expectErr: "missing Level",
123+
},
124+
{
125+
desc: "missing encoder time in encoder config",
126+
cfg: Config{
127+
Level: NewAtomicLevelAt(zapcore.InfoLevel),
128+
Encoding: "json",
129+
EncoderConfig: zapcore.EncoderConfig{
130+
MessageKey: "msg",
131+
TimeKey: "ts",
132+
},
133+
},
134+
expectErr: "missing EncodeTime in EncoderConfig",
135+
},
136+
}
137+
138+
for _, tt := range tests {
139+
t.Run(tt.desc, func(t *testing.T) {
140+
cfg := tt.cfg
141+
_, err := cfg.Build()
142+
require.Error(t, err)
143+
assert.Equal(t, tt.expectErr, err.Error())
144+
})
145+
}
146+
}

encoder.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,10 @@ func RegisterEncoder(name string, constructor func(zapcore.EncoderConfig) (zapco
6262
}
6363

6464
func newEncoder(name string, encoderConfig zapcore.EncoderConfig) (zapcore.Encoder, error) {
65+
if encoderConfig.TimeKey != "" && encoderConfig.EncodeTime == nil {
66+
return nil, fmt.Errorf("missing EncodeTime in EncoderConfig")
67+
}
68+
6569
_encoderMutex.RLock()
6670
defer _encoderMutex.RUnlock()
6771
if name == "" {

0 commit comments

Comments
 (0)