aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/go.uber.org/zap/global_test.go
blob: 17fa225e629fd6e19f1a878a94f606b5772ac2b2 (plain) (blame)
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
// 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 (
	"log"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"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"
)

func TestReplaceGlobals(t *testing.T) {
	initialL := *L()
	initialS := *S()

	withLogger(t, DebugLevel, nil, func(l *Logger, logs *observer.ObservedLogs) {
		L().Info("no-op")
		S().Info("no-op")
		assert.Equal(t, 0, logs.Len(), "Expected initial logs to go to default no-op global.")

		defer ReplaceGlobals(l)()

		L().Info("captured")
		S().Info("captured")
		expected := observer.LoggedEntry{
			Entry:   zapcore.Entry{Message: "captured"},
			Context: []Field{},
		}
		assert.Equal(
			t,
			[]observer.LoggedEntry{expected, expected},
			logs.AllUntimed(),
			"Unexpected global log output.",
		)
	})

	assert.Equal(t, initialL, *L(), "Expected func returned from ReplaceGlobals to restore initial L.")
	assert.Equal(t, initialS, *S(), "Expected func returned from ReplaceGlobals to restore initial S.")
}

func TestGlobalsConcurrentUse(t *testing.T) {
	var (
		stop atomic.Bool
		wg   sync.WaitGroup
	)

	for i := 0; i < 100; i++ {
		wg.Add(2)
		go func() {
			for !stop.Load() {
				ReplaceGlobals(NewNop())
			}
			wg.Done()
		}()
		go func() {
			for !stop.Load() {
				L().With(Int("foo", 42)).Named("main").WithOptions(Development()).Info("")
				S().Info("")
			}
			wg.Done()
		}()
	}

	ztest.Sleep(100 * time.Millisecond)
	// CAS loop to toggle the current value.
	for old := stop.Load(); !stop.CompareAndSwap(old, !old); {
		old = stop.Load()
	}
	wg.Wait()
}

func TestNewStdLog(t *testing.T) {
	withLogger(t, DebugLevel, []Option{AddCaller()}, func(l *Logger, logs *observer.ObservedLogs) {
		std := NewStdLog(l)
		std.Print("redirected")
		checkStdLogMessage(t, "redirected", logs)
	})
}

func TestNewStdLogAt(t *testing.T) {
	// include DPanicLevel here, but do not include Development in options
	levels := []zapcore.Level{DebugLevel, InfoLevel, WarnLevel, ErrorLevel, DPanicLevel}
	for _, level := range levels {
		withLogger(t, DebugLevel, []Option{AddCaller()}, func(l *Logger, logs *observer.ObservedLogs) {
			std, err := NewStdLogAt(l, level)
			require.NoError(t, err, "Unexpected error.")
			std.Print("redirected")
			checkStdLogMessage(t, "redirected", logs)
		})
	}
}

func TestNewStdLogAtPanics(t *testing.T) {
	// include DPanicLevel here and enable Development in options
	levels := []zapcore.Level{DPanicLevel, PanicLevel}
	for _, level := range levels {
		withLogger(t, DebugLevel, []Option{AddCaller(), Development()}, func(l *Logger, logs *observer.ObservedLogs) {
			std, err := NewStdLogAt(l, level)
			require.NoError(t, err, "Unexpected error")
			assert.Panics(t, func() { std.Print("redirected") }, "Expected log to panic.")
			checkStdLogMessage(t, "redirected", logs)
		})
	}
}

func TestNewStdLogAtFatal(t *testing.T) {
	withLogger(t, DebugLevel, []Option{AddCaller()}, func(l *Logger, logs *observer.ObservedLogs) {
		stub := exit.WithStub(func() {
			std, err := NewStdLogAt(l, FatalLevel)
			require.NoError(t, err, "Unexpected error.")
			std.Print("redirected")
			checkStdLogMessage(t, "redirected", logs)
		})
		assert.True(t, true, stub.Exited, "Expected Fatal logger call to terminate process.")
		stub.Unstub()
	})
}

func TestNewStdLogAtInvalid(t *testing.T) {
	_, err := NewStdLogAt(NewNop(), zapcore.Level(99))
	assert.ErrorContains(t, err, "99", "Expected level code in error message")
}

func TestRedirectStdLog(t *testing.T) {
	initialFlags := log.Flags()
	initialPrefix := log.Prefix()

	withLogger(t, DebugLevel, nil, func(l *Logger, logs *observer.ObservedLogs) {
		defer RedirectStdLog(l)()
		log.Print("redirected")

		assert.Equal(t, []observer.LoggedEntry{{
			Entry:   zapcore.Entry{Message: "redirected"},
			Context: []Field{},
		}}, logs.AllUntimed(), "Unexpected global log output.")
	})

	assert.Equal(t, initialFlags, log.Flags(), "Expected to reset initial flags.")
	assert.Equal(t, initialPrefix, log.Prefix(), "Expected to reset initial prefix.")
}

func TestRedirectStdLogCaller(t *testing.T) {
	withLogger(t, DebugLevel, []Option{AddCaller()}, func(l *Logger, logs *observer.ObservedLogs) {
		defer RedirectStdLog(l)()
		log.Print("redirected")
		entries := logs.All()
		require.Len(t, entries, 1, "Unexpected number of logs.")
		assert.Contains(t, entries[0].Caller.File, "global_test.go", "Unexpected caller annotation.")
	})
}

func TestRedirectStdLogAt(t *testing.T) {
	initialFlags := log.Flags()
	initialPrefix := log.Prefix()

	// include DPanicLevel here, but do not include Development in options
	levels := []zapcore.Level{DebugLevel, InfoLevel, WarnLevel, ErrorLevel, DPanicLevel}
	for _, level := range levels {
		withLogger(t, DebugLevel, nil, func(l *Logger, logs *observer.ObservedLogs) {
			restore, err := RedirectStdLogAt(l, level)
			require.NoError(t, err, "Unexpected error.")
			defer restore()
			log.Print("redirected")

			assert.Equal(t, []observer.LoggedEntry{{
				Entry:   zapcore.Entry{Level: level, Message: "redirected"},
				Context: []Field{},
			}}, logs.AllUntimed(), "Unexpected global log output.")
		})
	}

	assert.Equal(t, initialFlags, log.Flags(), "Expected to reset initial flags.")
	assert.Equal(t, initialPrefix, log.Prefix(), "Expected to reset initial prefix.")
}

func TestRedirectStdLogAtCaller(t *testing.T) {
	// include DPanicLevel here, but do not include Development in options
	levels := []zapcore.Level{DebugLevel, InfoLevel, WarnLevel, ErrorLevel, DPanicLevel}
	for _, level := range levels {
		withLogger(t, DebugLevel, []Option{AddCaller()}, func(l *Logger, logs *observer.ObservedLogs) {
			restore, err := RedirectStdLogAt(l, level)
			require.NoError(t, err, "Unexpected error.")
			defer restore()
			log.Print("redirected")
			entries := logs.All()
			require.Len(t, entries, 1, "Unexpected number of logs.")
			assert.Contains(t, entries[0].Caller.File, "global_test.go", "Unexpected caller annotation.")
		})
	}
}

func TestRedirectStdLogAtPanics(t *testing.T) {
	initialFlags := log.Flags()
	initialPrefix := log.Prefix()

	// include DPanicLevel here and enable Development in options
	levels := []zapcore.Level{DPanicLevel, PanicLevel}
	for _, level := range levels {
		withLogger(t, DebugLevel, []Option{AddCaller(), Development()}, func(l *Logger, logs *observer.ObservedLogs) {
			restore, err := RedirectStdLogAt(l, level)
			require.NoError(t, err, "Unexpected error.")
			defer restore()
			assert.Panics(t, func() { log.Print("redirected") }, "Expected log to panic.")
			checkStdLogMessage(t, "redirected", logs)
		})
	}

	assert.Equal(t, initialFlags, log.Flags(), "Expected to reset initial flags.")
	assert.Equal(t, initialPrefix, log.Prefix(), "Expected to reset initial prefix.")
}

func TestRedirectStdLogAtFatal(t *testing.T) {
	initialFlags := log.Flags()
	initialPrefix := log.Prefix()

	withLogger(t, DebugLevel, []Option{AddCaller()}, func(l *Logger, logs *observer.ObservedLogs) {
		stub := exit.WithStub(func() {
			restore, err := RedirectStdLogAt(l, FatalLevel)
			require.NoError(t, err, "Unexpected error.")
			defer restore()
			log.Print("redirected")
			checkStdLogMessage(t, "redirected", logs)
		})
		assert.True(t, true, stub.Exited, "Expected Fatal logger call to terminate process.")
		stub.Unstub()
	})

	assert.Equal(t, initialFlags, log.Flags(), "Expected to reset initial flags.")
	assert.Equal(t, initialPrefix, log.Prefix(), "Expected to reset initial prefix.")
}

func TestRedirectStdLogAtInvalid(t *testing.T) {
	restore, err := RedirectStdLogAt(NewNop(), zapcore.Level(99))
	defer func() {
		if restore != nil {
			restore()
		}
	}()
	assert.ErrorContains(t, err, "99", "Expected level code in error message")
}

func checkStdLogMessage(t *testing.T, msg string, logs *observer.ObservedLogs) {
	require.Equal(t, 1, logs.Len(), "Expected exactly one entry to be logged")
	entry := logs.AllUntimed()[0]
	assert.Equal(t, []Field{}, entry.Context, "Unexpected entry context.")
	assert.Equal(t, "redirected", entry.Message, "Unexpected entry message.")
	assert.Regexp(
		t,
		`/global_test.go:\d+$`,
		entry.Caller.String(),
		"Unexpected caller annotation.",
	)
}