forked from uber-go/zap
-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger_test.go
432 lines (396 loc) · 13.5 KB
/
logger_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
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package zap
import (
"errors"
"sync"
"testing"
"go.uber.org/zap/internal/exit"
"go.uber.org/zap/internal/ztest"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/atomic"
)
func makeCountingHook() (func(zapcore.Entry) error, *atomic.Int64) {
count := &atomic.Int64{}
h := func(zapcore.Entry) error {
count.Inc()
return nil
}
return h, count
}
func TestLoggerAtomicLevel(t *testing.T) {
// Test that the dynamic level applies to all ancestors and descendants.
dl := NewAtomicLevel()
withLogger(t, dl, nil, func(grandparent *Logger, _ *observer.ObservedLogs) {
parent := grandparent.With(Int("generation", 1))
child := parent.With(Int("generation", 2))
tests := []struct {
setLevel zapcore.Level
testLevel zapcore.Level
enabled bool
}{
{DebugLevel, DebugLevel, true},
{InfoLevel, DebugLevel, false},
{WarnLevel, PanicLevel, true},
}
for _, tt := range tests {
dl.SetLevel(tt.setLevel)
for _, logger := range []*Logger{grandparent, parent, child} {
if tt.enabled {
assert.NotNil(
t,
logger.Check(tt.testLevel, ""),
"Expected level %s to be enabled after setting level %s.", tt.testLevel, tt.setLevel,
)
} else {
assert.Nil(
t,
logger.Check(tt.testLevel, ""),
"Expected level %s to be enabled after setting level %s.", tt.testLevel, tt.setLevel,
)
}
}
}
})
}
func TestLoggerInitialFields(t *testing.T) {
fieldOpts := opts(Fields(Int("foo", 42), String("bar", "baz")))
withLogger(t, DebugLevel, fieldOpts, func(logger *Logger, logs *observer.ObservedLogs) {
logger.Info("")
assert.Equal(
t,
observer.LoggedEntry{Context: []Field{Int("foo", 42), String("bar", "baz")}},
logs.AllUntimed()[0],
"Unexpected output with initial fields set.",
)
})
}
func TestLoggerWith(t *testing.T) {
fieldOpts := opts(Fields(Int("foo", 42)))
withLogger(t, DebugLevel, fieldOpts, func(logger *Logger, logs *observer.ObservedLogs) {
// Child loggers should have copy-on-write semantics, so two children
// shouldn't stomp on each other's fields or affect the parent's fields.
logger.With(String("one", "two")).Info("")
logger.With(String("three", "four")).Info("")
logger.Info("")
assert.Equal(t, []observer.LoggedEntry{
{Context: []Field{Int("foo", 42), String("one", "two")}},
{Context: []Field{Int("foo", 42), String("three", "four")}},
{Context: []Field{Int("foo", 42)}},
}, logs.AllUntimed(), "Unexpected cross-talk between child loggers.")
})
}
func TestLoggerLogPanic(t *testing.T) {
for _, tt := range []struct {
do func(*Logger)
should bool
expected string
}{
{func(logger *Logger) { logger.Check(PanicLevel, "bar").Write() }, true, "bar"},
{func(logger *Logger) { logger.Panic("baz") }, true, "baz"},
} {
withLogger(t, DebugLevel, nil, func(logger *Logger, logs *observer.ObservedLogs) {
if tt.should {
assert.Panics(t, func() { tt.do(logger) }, "Expected panic")
} else {
assert.NotPanics(t, func() { tt.do(logger) }, "Expected no panic")
}
output := logs.AllUntimed()
assert.Equal(t, 1, len(output), "Unexpected number of logs.")
assert.Equal(t, 0, len(output[0].Context), "Unexpected context on first log.")
assert.Equal(
t,
zapcore.Entry{Message: tt.expected, Level: PanicLevel},
output[0].Entry,
"Unexpected output from panic-level Log.",
)
})
}
}
func TestLoggerLogFatal(t *testing.T) {
for _, tt := range []struct {
do func(*Logger)
expected string
}{
{func(logger *Logger) { logger.Check(FatalLevel, "bar").Write() }, "bar"},
{func(logger *Logger) { logger.Fatal("baz") }, "baz"},
} {
withLogger(t, DebugLevel, nil, func(logger *Logger, logs *observer.ObservedLogs) {
stub := exit.WithStub(func() {
tt.do(logger)
})
assert.True(t, stub.Exited, "Expected Fatal logger call to terminate process.")
output := logs.AllUntimed()
assert.Equal(t, 1, len(output), "Unexpected number of logs.")
assert.Equal(t, 0, len(output[0].Context), "Unexpected context on first log.")
assert.Equal(
t,
zapcore.Entry{Message: tt.expected, Level: FatalLevel},
output[0].Entry,
"Unexpected output from fatal-level Log.",
)
})
}
}
func TestLoggerLeveledMethods(t *testing.T) {
withLogger(t, DebugLevel, nil, func(logger *Logger, logs *observer.ObservedLogs) {
tests := []struct {
method func(string, ...Field)
expectedLevel zapcore.Level
}{
{logger.Debug, DebugLevel},
{logger.Info, InfoLevel},
{logger.Warn, WarnLevel},
{logger.Error, ErrorLevel},
{logger.DPanic, DPanicLevel},
}
for i, tt := range tests {
tt.method("")
output := logs.AllUntimed()
assert.Equal(t, i+1, len(output), "Unexpected number of logs.")
assert.Equal(t, 0, len(output[i].Context), "Unexpected context on first log.")
assert.Equal(
t,
zapcore.Entry{Level: tt.expectedLevel},
output[i].Entry,
"Unexpected output from %s-level logger method.", tt.expectedLevel)
}
})
}
func TestLoggerAlwaysPanics(t *testing.T) {
// Users can disable writing out panic-level logs, but calls to logger.Panic()
// should still call panic().
withLogger(t, FatalLevel, nil, func(logger *Logger, logs *observer.ObservedLogs) {
msg := "Even if output is disabled, logger.Panic should always panic."
assert.Panics(t, func() { logger.Panic("foo") }, msg)
assert.Panics(t, func() {
if ce := logger.Check(PanicLevel, "foo"); ce != nil {
ce.Write()
}
}, msg)
assert.Equal(t, 0, logs.Len(), "Panics shouldn't be written out if PanicLevel is disabled.")
})
}
func TestLoggerAlwaysFatals(t *testing.T) {
// Users can disable writing out fatal-level logs, but calls to logger.Fatal()
// should still terminate the process.
withLogger(t, FatalLevel+1, nil, func(logger *Logger, logs *observer.ObservedLogs) {
stub := exit.WithStub(func() { logger.Fatal("") })
assert.True(t, stub.Exited, "Expected calls to logger.Fatal to terminate process.")
stub = exit.WithStub(func() {
if ce := logger.Check(FatalLevel, ""); ce != nil {
ce.Write()
}
})
assert.True(t, stub.Exited, "Expected calls to logger.Check(FatalLevel, ...) to terminate process.")
assert.Equal(t, 0, logs.Len(), "Shouldn't write out logs when fatal-level logging is disabled.")
})
}
func TestLoggerDPanic(t *testing.T) {
withLogger(t, DebugLevel, nil, func(logger *Logger, logs *observer.ObservedLogs) {
assert.NotPanics(t, func() { logger.DPanic("") })
assert.Equal(
t,
[]observer.LoggedEntry{{Entry: zapcore.Entry{Level: DPanicLevel}, Context: []Field{}}},
logs.AllUntimed(),
"Unexpected log output from DPanic in production mode.",
)
})
withLogger(t, DebugLevel, opts(Development()), func(logger *Logger, logs *observer.ObservedLogs) {
assert.Panics(t, func() { logger.DPanic("") })
assert.Equal(
t,
[]observer.LoggedEntry{{Entry: zapcore.Entry{Level: DPanicLevel}, Context: []Field{}}},
logs.AllUntimed(),
"Unexpected log output from DPanic in development mode.",
)
})
}
func TestLoggerNoOpsDisabledLevels(t *testing.T) {
withLogger(t, WarnLevel, nil, func(logger *Logger, logs *observer.ObservedLogs) {
logger.Info("silence!")
assert.Equal(
t,
[]observer.LoggedEntry{},
logs.AllUntimed(),
"Expected logging at a disabled level to produce no output.",
)
})
}
func TestLoggerNames(t *testing.T) {
tests := []struct {
names []string
expected string
}{
{nil, ""},
{[]string{""}, ""},
{[]string{"foo"}, "foo"},
{[]string{"foo", ""}, "foo"},
{[]string{"foo", "bar"}, "foo.bar"},
{[]string{"foo.bar", "baz"}, "foo.bar.baz"},
// Garbage in, garbage out.
{[]string{"foo.", "bar"}, "foo..bar"},
{[]string{"foo", ".bar"}, "foo..bar"},
{[]string{"foo.", ".bar"}, "foo...bar"},
}
for _, tt := range tests {
withLogger(t, DebugLevel, nil, func(log *Logger, logs *observer.ObservedLogs) {
for _, n := range tt.names {
log = log.Named(n)
}
log.Info("")
require.Equal(t, 1, logs.Len(), "Expected only one log entry to be written.")
assert.Equal(t, tt.expected, logs.AllUntimed()[0].Entry.LoggerName, "Unexpected logger name.")
})
withSugar(t, DebugLevel, nil, func(log *SugaredLogger, logs *observer.ObservedLogs) {
for _, n := range tt.names {
log = log.Named(n)
}
log.Infow("")
require.Equal(t, 1, logs.Len(), "Expected only one log entry to be written.")
assert.Equal(t, tt.expected, logs.AllUntimed()[0].Entry.LoggerName, "Unexpected logger name.")
})
}
}
func TestLoggerWriteFailure(t *testing.T) {
errSink := &ztest.Buffer{}
logger := New(
zapcore.NewCore(
zapcore.NewJSONEncoder(NewProductionConfig().EncoderConfig),
zapcore.Lock(zapcore.AddSync(ztest.FailWriter{})),
DebugLevel,
),
ErrorOutput(errSink),
)
logger.Info("foo")
// Should log the error.
assert.Regexp(t, `write error: failed`, errSink.Stripped(), "Expected to log the error to the error output.")
assert.True(t, errSink.Called(), "Expected logging an internal error to call Sync the error sink.")
}
func TestLoggerSync(t *testing.T) {
withLogger(t, DebugLevel, nil, func(logger *Logger, _ *observer.ObservedLogs) {
assert.NoError(t, logger.Sync(), "Expected syncing a test logger to succeed.")
assert.NoError(t, logger.Sugar().Sync(), "Expected syncing a sugared logger to succeed.")
})
}
func TestLoggerSyncFail(t *testing.T) {
noSync := &ztest.Buffer{}
err := errors.New("fail")
noSync.SetError(err)
logger := New(zapcore.NewCore(
zapcore.NewJSONEncoder(zapcore.EncoderConfig{}),
noSync,
DebugLevel,
))
assert.Equal(t, err, logger.Sync(), "Expected Logger.Sync to propagate errors.")
assert.Equal(t, err, logger.Sugar().Sync(), "Expected SugaredLogger.Sync to propagate errors.")
}
func TestLoggerAddCaller(t *testing.T) {
tests := []struct {
options []Option
pat string
}{
{opts(AddCaller()), `.+/logger_test.go:[\d]+$`},
{opts(AddCaller(), AddCallerSkip(1), AddCallerSkip(-1)), `.+/zap/logger_test.go:[\d]+$`},
{opts(AddCaller(), AddCallerSkip(1)), `.+/zap/common_test.go:[\d]+$`},
{opts(AddCaller(), AddCallerSkip(1), AddCallerSkip(3)), `.+/src/runtime/.*:[\d]+$`},
}
for _, tt := range tests {
withLogger(t, DebugLevel, tt.options, func(logger *Logger, logs *observer.ObservedLogs) {
// Make sure that sugaring and desugaring resets caller skip properly.
logger = logger.Sugar().Desugar()
logger.Info("")
output := logs.AllUntimed()
assert.Equal(t, 1, len(output), "Unexpected number of logs written out.")
assert.Regexp(
t,
tt.pat,
output[0].Entry.Caller,
"Expected to find package name and file name in output.",
)
})
}
}
func TestLoggerAddCallerFail(t *testing.T) {
errBuf := &ztest.Buffer{}
withLogger(t, DebugLevel, opts(AddCaller(), ErrorOutput(errBuf)), func(log *Logger, logs *observer.ObservedLogs) {
log.callerSkip = 1e3
log.Info("Failure.")
assert.Regexp(
t,
`Logger.check error: failed to get caller`,
errBuf.String(),
"Didn't find expected failure message.",
)
assert.Equal(
t,
logs.AllUntimed()[0].Entry.Message,
"Failure.",
"Expected original message to survive failures in runtime.Caller.")
})
}
func TestLoggerReplaceCore(t *testing.T) {
replace := WrapCore(func(zapcore.Core) zapcore.Core {
return zapcore.NewNopCore()
})
withLogger(t, DebugLevel, opts(replace), func(logger *Logger, logs *observer.ObservedLogs) {
logger.Debug("")
logger.Info("")
logger.Warn("")
assert.Equal(t, 0, logs.Len(), "Expected no-op core to write no logs.")
})
}
func TestLoggerHooks(t *testing.T) {
hook, seen := makeCountingHook()
withLogger(t, DebugLevel, opts(Hooks(hook)), func(logger *Logger, logs *observer.ObservedLogs) {
logger.Debug("")
logger.Info("")
})
assert.Equal(t, int64(2), seen.Load(), "Hook saw an unexpected number of logs.")
}
func TestLoggerConcurrent(t *testing.T) {
withLogger(t, DebugLevel, nil, func(logger *Logger, logs *observer.ObservedLogs) {
child := logger.With(String("foo", "bar"))
wg := &sync.WaitGroup{}
runConcurrently(5, 10, wg, func() {
logger.Info("", String("foo", "bar"))
})
runConcurrently(5, 10, wg, func() {
child.Info("")
})
wg.Wait()
// Make sure the output doesn't contain interspersed entries.
assert.Equal(t, 100, logs.Len(), "Unexpected number of logs written out.")
for _, obs := range logs.AllUntimed() {
assert.Equal(
t,
observer.LoggedEntry{
Entry: zapcore.Entry{Level: InfoLevel},
Context: []Field{String("foo", "bar")},
},
obs,
"Unexpected log output.",
)
}
})
}