/
zap_test.go
508 lines (415 loc) · 14.4 KB
/
zap_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package zap
import (
"bytes"
"encoding/json"
"flag"
"os"
"github.com/go-logr/logr"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"go.uber.org/zap/zapcore"
kapi "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/types"
)
// testStringer is a fmt.Stringer
type testStringer struct{}
func (testStringer) String() string {
return "value"
}
// fakeSyncWriter is a fake zap.SyncerWriter that lets us test if sync was called
type fakeSyncWriter bool
func (w *fakeSyncWriter) Write(p []byte) (int, error) {
return len(p), nil
}
func (w *fakeSyncWriter) Sync() error {
*w = true
return nil
}
// logInfo is the information for a particular fakeLogger message
type logInfo struct {
name []string
tags []interface{}
msg string
}
// fakeLoggerRoot is the root object to which all fakeLoggers record their messages.
type fakeLoggerRoot struct {
messages []logInfo
}
var _ logr.Logger = &fakeLogger{}
// fakeLogger is a fake implementation of logr.Logger that records
// messages, tags, and names,
// just records the name.
type fakeLogger struct {
name []string
tags []interface{}
root *fakeLoggerRoot
}
func (f *fakeLogger) WithName(name string) logr.Logger {
names := append([]string(nil), f.name...)
names = append(names, name)
return &fakeLogger{
name: names,
tags: f.tags,
root: f.root,
}
}
func (f *fakeLogger) WithValues(vals ...interface{}) logr.Logger {
tags := append([]interface{}(nil), f.tags...)
tags = append(tags, vals...)
return &fakeLogger{
name: f.name,
tags: tags,
root: f.root,
}
}
func (f *fakeLogger) Error(err error, msg string, vals ...interface{}) {
tags := append([]interface{}(nil), f.tags...)
tags = append(tags, "error", err)
tags = append(tags, vals...)
f.root.messages = append(f.root.messages, logInfo{
name: append([]string(nil), f.name...),
tags: tags,
msg: msg,
})
}
func (f *fakeLogger) Info(msg string, vals ...interface{}) {
tags := append([]interface{}(nil), f.tags...)
tags = append(tags, vals...)
f.root.messages = append(f.root.messages, logInfo{
name: append([]string(nil), f.name...),
tags: tags,
msg: msg,
})
}
func (f *fakeLogger) Enabled() bool { return true }
func (f *fakeLogger) V(lvl int) logr.InfoLogger { return f }
var _ = Describe("Zap options setup", func() {
var opts *Options
BeforeEach(func() {
opts = &Options{}
})
It("should enable development mode", func() {
UseDevMode(true)(opts)
Expect(opts.Development).To(BeTrue())
})
It("should disable development mode", func() {
UseDevMode(false)(opts)
Expect(opts.Development).To(BeFalse())
})
It("should set a custom writer", func() {
var w fakeSyncWriter
WriteTo(&w)(opts)
Expect(opts.DestWriter).To(Equal(&w))
})
})
var _ = Describe("Zap logger setup", func() {
Context("when logging kubernetes objects", func() {
var logOut *bytes.Buffer
var logger logr.Logger
defineTests := func() {
It("should log a standard namespaced Kubernetes object name and namespace", func() {
pod := &kapi.Pod{}
pod.Name = "some-pod"
pod.Namespace = "some-ns"
logger.Info("here's a kubernetes object", "thing", pod)
outRaw := logOut.Bytes()
res := map[string]interface{}{}
Expect(json.Unmarshal(outRaw, &res)).To(Succeed())
Expect(res).To(HaveKeyWithValue("thing", map[string]interface{}{
"name": pod.Name,
"namespace": pod.Namespace,
}))
})
It("should work fine with normal stringers", func() {
logger.Info("here's a non-kubernetes stringer", "thing", testStringer{})
outRaw := logOut.Bytes()
res := map[string]interface{}{}
Expect(json.Unmarshal(outRaw, &res)).To(Succeed())
Expect(res).To(HaveKeyWithValue("thing", "value"))
})
It("should log a standard non-namespaced Kubernetes object name", func() {
node := &kapi.Node{}
node.Name = "some-node"
logger.Info("here's a kubernetes object", "thing", node)
outRaw := logOut.Bytes()
res := map[string]interface{}{}
Expect(json.Unmarshal(outRaw, &res)).To(Succeed())
Expect(res).To(HaveKeyWithValue("thing", map[string]interface{}{
"name": node.Name,
}))
})
It("should log a standard Kubernetes object's kind, if set", func() {
node := &kapi.Node{}
node.Name = "some-node"
node.APIVersion = "v1"
node.Kind = "Node"
logger.Info("here's a kubernetes object", "thing", node)
outRaw := logOut.Bytes()
res := map[string]interface{}{}
Expect(json.Unmarshal(outRaw, &res)).To(Succeed())
Expect(res).To(HaveKeyWithValue("thing", map[string]interface{}{
"name": node.Name,
"apiVersion": "v1",
"kind": "Node",
}))
})
It("should log a standard non-namespaced NamespacedName name", func() {
name := types.NamespacedName{Name: "some-node"}
logger.Info("here's a kubernetes object", "thing", name)
outRaw := logOut.Bytes()
res := map[string]interface{}{}
Expect(json.Unmarshal(outRaw, &res)).To(Succeed())
Expect(res).To(HaveKeyWithValue("thing", map[string]interface{}{
"name": name.Name,
}))
})
It("should log an unstructured Kubernetes object", func() {
pod := &unstructured.Unstructured{
Object: map[string]interface{}{
"metadata": map[string]interface{}{
"name": "some-pod",
"namespace": "some-ns",
},
},
}
logger.Info("here's a kubernetes object", "thing", pod)
outRaw := logOut.Bytes()
res := map[string]interface{}{}
Expect(json.Unmarshal(outRaw, &res)).To(Succeed())
Expect(res).To(HaveKeyWithValue("thing", map[string]interface{}{
"name": "some-pod",
"namespace": "some-ns",
}))
})
It("should log a standard namespaced NamespacedName name and namespace", func() {
name := types.NamespacedName{Name: "some-pod", Namespace: "some-ns"}
logger.Info("here's a kubernetes object", "thing", name)
outRaw := logOut.Bytes()
res := map[string]interface{}{}
Expect(json.Unmarshal(outRaw, &res)).To(Succeed())
Expect(res).To(HaveKeyWithValue("thing", map[string]interface{}{
"name": name.Name,
"namespace": name.Namespace,
}))
})
}
Context("with logger created using New", func() {
BeforeEach(func() {
logOut = new(bytes.Buffer)
By("setting up the logger")
// use production settings (false) to get just json output
logger = New(WriteTo(logOut), UseDevMode(false))
})
defineTests()
})
})
})
var _ = Describe("Zap log level flag options setup", func() {
var (
fromFlags Options
fs flag.FlagSet
logInfoLevel0 = "info text"
logDebugLevel1 = "debug 1 text"
logDebugLevel2 = "debug 2 text"
logDebugLevel3 = "debug 3 text"
)
BeforeEach(func() {
fromFlags = Options{}
fs = *flag.NewFlagSet(os.Args[0], flag.ExitOnError)
})
Context("with zap-log-level options provided", func() {
It("Should output logs for info and debug zap-log-level.", func() {
args := []string{"--zap-log-level=debug"}
fromFlags.BindFlags(&fs)
err := fs.Parse(args)
Expect(err).ToNot(HaveOccurred())
logOut := new(bytes.Buffer)
logger := New(UseFlagOptions(&fromFlags), WriteTo(logOut))
logger.V(0).Info(logInfoLevel0)
logger.V(1).Info(logDebugLevel1)
outRaw := logOut.Bytes()
Expect(string(outRaw)).Should(ContainSubstring(logInfoLevel0))
Expect(string(outRaw)).Should(ContainSubstring(logDebugLevel1))
})
It("Should output only error logs, otherwise empty logs", func() {
args := []string{"--zap-log-level=error"}
fromFlags.BindFlags(&fs)
err := fs.Parse(args)
Expect(err).ToNot(HaveOccurred())
logOut := new(bytes.Buffer)
logger := New(UseFlagOptions(&fromFlags), WriteTo(logOut))
logger.V(0).Info(logInfoLevel0)
logger.V(1).Info(logDebugLevel1)
outRaw := logOut.Bytes()
Expect(outRaw).To(BeEmpty())
})
})
Context("with zap-log-level with increased verbosity.", func() {
It("Should output debug and info log, with default production mode.", func() {
args := []string{"--zap-log-level=1"}
fromFlags.BindFlags(&fs)
err := fs.Parse(args)
Expect(err).ToNot(HaveOccurred())
logOut := new(bytes.Buffer)
logger := New(UseFlagOptions(&fromFlags), WriteTo(logOut))
logger.V(0).Info(logInfoLevel0)
logger.V(1).Info(logDebugLevel1)
outRaw := logOut.Bytes()
Expect(string(outRaw)).Should(ContainSubstring(logInfoLevel0))
Expect(string(outRaw)).Should(ContainSubstring(logDebugLevel1))
})
It("Should output info and debug logs, with development mode.", func() {
args := []string{"--zap-log-level=1", "--zap-devel=true"}
fromFlags.BindFlags(&fs)
err := fs.Parse(args)
Expect(err).ToNot(HaveOccurred())
logOut := new(bytes.Buffer)
logger := New(UseFlagOptions(&fromFlags), WriteTo(logOut))
logger.V(0).Info(logInfoLevel0)
logger.V(1).Info(logDebugLevel1)
outRaw := logOut.Bytes()
Expect(string(outRaw)).Should(ContainSubstring(logInfoLevel0))
Expect(string(outRaw)).Should(ContainSubstring(logDebugLevel1))
})
It("Should output info, and debug logs with increased verbosity, and with development mode set to true.", func() {
args := []string{"--zap-log-level=3", "--zap-devel=false"}
fromFlags.BindFlags(&fs)
err := fs.Parse(args)
Expect(err).ToNot(HaveOccurred())
logOut := new(bytes.Buffer)
logger := New(UseFlagOptions(&fromFlags), WriteTo(logOut))
logger.V(0).Info(logInfoLevel0)
logger.V(1).Info(logDebugLevel1)
logger.V(2).Info(logDebugLevel2)
logger.V(3).Info(logDebugLevel3)
outRaw := logOut.Bytes()
Expect(string(outRaw)).Should(ContainSubstring(logInfoLevel0))
Expect(string(outRaw)).Should(ContainSubstring(logDebugLevel1))
Expect(string(outRaw)).Should(ContainSubstring(logDebugLevel2))
Expect(string(outRaw)).Should(ContainSubstring(logDebugLevel3))
})
It("Should output info, and debug logs with increased verbosity, and with production mode set to true.", func() {
args := []string{"--zap-log-level=3", "--zap-devel=true"}
fromFlags.BindFlags(&fs)
err := fs.Parse(args)
Expect(err).ToNot(HaveOccurred())
logOut := new(bytes.Buffer)
logger := New(UseFlagOptions(&fromFlags), WriteTo(logOut))
logger.V(0).Info(logInfoLevel0)
logger.V(1).Info(logDebugLevel1)
logger.V(2).Info(logDebugLevel2)
logger.V(3).Info(logDebugLevel3)
outRaw := logOut.Bytes()
Expect(string(outRaw)).Should(ContainSubstring(logInfoLevel0))
Expect(string(outRaw)).Should(ContainSubstring(logDebugLevel1))
Expect(string(outRaw)).Should(ContainSubstring(logDebugLevel2))
Expect(string(outRaw)).Should(ContainSubstring(logDebugLevel3))
})
})
Context("with zap-stacktrace-level options provided", func() {
It("Should output stacktrace at info level, with development mode set to true.", func() {
args := []string{"--zap-stacktrace-level=info", "--zap-devel=true"}
fromFlags.BindFlags(&fs)
err := fs.Parse(args)
Expect(err).ToNot(HaveOccurred())
out := Options{}
UseFlagOptions(&fromFlags)(&out)
Expect(out.StacktraceLevel.Enabled(zapcore.InfoLevel)).To(BeTrue())
})
It("Should output stacktrace at error level, with development mode set to true.", func() {
args := []string{"--zap-stacktrace-level=error", "--zap-devel=true"}
fromFlags.BindFlags(&fs)
err := fs.Parse(args)
Expect(err).ToNot(HaveOccurred())
out := Options{}
UseFlagOptions(&fromFlags)(&out)
Expect(out.StacktraceLevel.Enabled(zapcore.ErrorLevel)).To(BeTrue())
})
})
Context("with only -zap-devel flag provided", func() {
It("Should set dev=true.", func() {
args := []string{"--zap-devel=true"}
fromFlags.BindFlags(&fs)
if err := fs.Parse(args); err != nil {
Expect(err).ToNot(HaveOccurred())
}
out := Options{}
UseFlagOptions(&fromFlags)(&out)
Expect(out.Development).To(BeTrue())
Expect(out.Encoder).To(BeNil())
Expect(out.Level).To(BeNil())
Expect(out.StacktraceLevel).To(BeNil())
Expect(out.EncoderConfigOptions).To(BeNil())
})
It("Should set dev=false", func() {
args := []string{"--zap-devel=false"}
fromFlags.BindFlags(&fs)
if err := fs.Parse(args); err != nil {
Expect(err).ToNot(HaveOccurred())
}
out := Options{}
UseFlagOptions(&fromFlags)(&out)
Expect(out.Development).To(BeFalse())
Expect(out.Encoder).To(BeNil())
Expect(out.Level).To(BeNil())
Expect(out.StacktraceLevel).To(BeNil())
Expect(out.EncoderConfigOptions).To(BeNil())
})
})
Context("with encoder options provided programmatically.", func() {
It("Should set Console Encoder, with given Nanos TimeEncoder option.", func() {
logOut := new(bytes.Buffer)
f := func(ec *zapcore.EncoderConfig) {
if err := ec.EncodeTime.UnmarshalText([]byte("nanos")); err != nil {
Expect(err).ToNot(HaveOccurred())
}
}
opts := func(o *Options) {
o.EncoderConfigOptions = append(o.EncoderConfigOptions, f)
}
log := New(UseDevMode(true), WriteTo(logOut), opts)
log.Info("This is a test message")
outRaw := logOut.Bytes()
// Assert for Console Encoder
res := map[string]interface{}{}
Expect(json.Unmarshal(outRaw, &res)).ToNot(Succeed())
// Assert for Epoch Nanos TimeEncoder
Expect(string(outRaw)).ShouldNot(ContainSubstring("."))
})
It("Should set JSON Encoder, with given Millis TimeEncoder option, and MessageKey", func() {
logOut := new(bytes.Buffer)
f := func(ec *zapcore.EncoderConfig) {
ec.MessageKey = "MillisTimeFormat"
if err := ec.EncodeTime.UnmarshalText([]byte("millis")); err != nil {
Expect(err).ToNot(HaveOccurred())
}
}
opts := func(o *Options) {
o.EncoderConfigOptions = append(o.EncoderConfigOptions, f)
}
log := New(UseDevMode(false), WriteTo(logOut), opts)
log.Info("This is a test message")
outRaw := logOut.Bytes()
// Assert for JSON Encoder
res := map[string]interface{}{}
Expect(json.Unmarshal(outRaw, &res)).To(Succeed())
// Assert for Epoch Nanos TimeEncoder
Expect(string(outRaw)).Should(ContainSubstring("."))
// Assert for MessageKey
Expect(string(outRaw)).Should(ContainSubstring("MillisTimeFormat"))
})
})
})