-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathslog_test.go
More file actions
275 lines (221 loc) · 7.68 KB
/
Copy pathslog_test.go
File metadata and controls
275 lines (221 loc) · 7.68 KB
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
/*
Copyright The containerd 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 log
import (
"bytes"
"context"
"log/slog"
"strings"
"sync"
"testing"
"github.com/sirupsen/logrus"
)
// setupSlogTest sets up UseSlogHook with a captured slog buffer and a separate
// buffer for the original logrus output. It restores all global state on cleanup.
func setupSlogTest(t *testing.T) (slogBuf, logrusBuf *bytes.Buffer) {
t.Helper()
// Save global state to restore later.
oldLogger := L.Logger
oldDefault := slog.Default()
oldSlogOut := slogOut
// Create a fresh logrus logger so we don't mutate the real global.
logger := logrus.New()
logger.SetLevel(logrus.TraceLevel)
logrusBuf = &bytes.Buffer{}
logger.SetOutput(logrusBuf)
L = &Entry{
Logger: logger,
Data: make(Fields, 6),
}
// Reset slogOnce so UseSlog runs against this fresh logger.
slogOnce = sync.Once{}
// Activate the slog hook — this redirects logrus output to io.Discard
// and sets slogOut to the logger's original output.
UseSlog()
// Now install a slog handler that writes to our test buffer.
slogBuf = &bytes.Buffer{}
handler := slog.NewTextHandler(slogBuf, &slog.HandlerOptions{
Level: slog.LevelDebug - 4, // capture all levels including trace
})
slog.SetDefault(slog.New(handler))
t.Cleanup(func() {
L = &Entry{
Logger: oldLogger,
Data: make(Fields, 6),
}
slog.SetDefault(oldDefault)
slogOut = oldSlogOut
slogOnce = sync.Once{}
})
return slogBuf, logrusBuf
}
func TestUseSlogHook(t *testing.T) {
slogBuf, logrusBuf := setupSlogTest(t)
L.Info("hello from L")
slogOutput := slogBuf.String()
logrusOutput := logrusBuf.String()
if !strings.Contains(slogOutput, "hello from L") {
t.Errorf("expected slog output to contain message, got: %s", slogOutput)
}
if logrusOutput != "" {
t.Errorf("expected no logrus output, got: %s", logrusOutput)
}
}
func TestUseSlogHookWithFields(t *testing.T) {
slogBuf, logrusBuf := setupSlogTest(t)
L.WithFields(Fields{
"component": "test",
"count": 42,
}).Warn("something happened")
slogOutput := slogBuf.String()
if !strings.Contains(slogOutput, "something happened") {
t.Errorf("expected slog output to contain message, got: %s", slogOutput)
}
if !strings.Contains(slogOutput, "component=test") {
t.Errorf("expected slog output to contain component field, got: %s", slogOutput)
}
if !strings.Contains(slogOutput, "count=42") {
t.Errorf("expected slog output to contain count field, got: %s", slogOutput)
}
if logrusBuf.Len() != 0 {
t.Errorf("expected no logrus output, got: %s", logrusBuf.String())
}
}
func TestUseSlogHookWithContext(t *testing.T) {
slogBuf, logrusBuf := setupSlogTest(t)
ctx := context.Background()
logger := G(ctx).WithField("request_id", "abc123")
ctx = WithLogger(ctx, logger)
G(ctx).Info("context logger message")
slogOutput := slogBuf.String()
if !strings.Contains(slogOutput, "context logger message") {
t.Errorf("expected slog output to contain message, got: %s", slogOutput)
}
if !strings.Contains(slogOutput, "request_id=abc123") {
t.Errorf("expected slog output to contain request_id field, got: %s", slogOutput)
}
if logrusBuf.Len() != 0 {
t.Errorf("expected no logrus output, got: %s", logrusBuf.String())
}
}
func TestUseSlogHookLevels(t *testing.T) {
slogBuf, logrusBuf := setupSlogTest(t)
tests := []struct {
name string
logFunc func(string, ...any)
message string
wantLevel string
}{
{"trace", L.Tracef, "trace-msg", "DEBUG-4"},
{"debug", L.Debugf, "debug-msg", "DEBUG"},
{"info", L.Infof, "info-msg", "INFO"},
{"warn", L.Warnf, "warn-msg", "WARN"},
{"error", L.Errorf, "error-msg", "ERROR"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
slogBuf.Reset()
logrusBuf.Reset()
tc.logFunc(tc.message)
output := slogBuf.String()
if !strings.Contains(output, tc.message) {
t.Errorf("expected slog output to contain %q, got: %s", tc.message, output)
}
if !strings.Contains(output, "level="+tc.wantLevel) {
t.Errorf("expected slog output to contain level %q, got: %s", tc.wantLevel, output)
}
if logrusBuf.Len() != 0 {
t.Errorf("expected no logrus output, got: %s", logrusBuf.String())
}
})
}
}
func TestSetFormatWithSlog(t *testing.T) {
// SetFormat reconfigures the slog default handler to write to slogOut.
// After SetFormat, logging through L should still go to slog (via slogOut),
// and nothing should go to the logrus output (which is io.Discard).
_, _ = setupSlogTest(t)
// Replace slogOut with our own buffer so we can capture what SetFormat configures.
var slogBuf bytes.Buffer
slogOut = &slogBuf
t.Run("text format", func(t *testing.T) {
slogBuf.Reset()
if err := SetFormat(TextFormat); err != nil {
t.Fatalf("unexpected error: %v", err)
}
L.Info("text format message")
if !strings.Contains(slogBuf.String(), "text format message") {
t.Errorf("expected slog output to contain message, got: %s", slogBuf.String())
}
})
t.Run("json format", func(t *testing.T) {
slogBuf.Reset()
if err := SetFormat(JSONFormat); err != nil {
t.Fatalf("unexpected error: %v", err)
}
L.Info("json format message")
slogOutput := slogBuf.String()
if !strings.Contains(slogOutput, "json format message") {
t.Errorf("expected slog output to contain message, got: %s", slogOutput)
}
if !strings.Contains(slogOutput, "{") {
t.Errorf("expected JSON format output, got: %s", slogOutput)
}
})
}
// TestSetLevelWithSlog verifies that slog filtering follows the Logrus logger
// level, whether changed through SetLevel or directly on the logger.
func TestSetLevelWithSlog(t *testing.T) {
slogBuf, _ := setupSlogTest(t)
// Set level to warn — debug/info messages should be suppressed by slog.
if err := SetLevel("warn"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Also reconfigure slog handler to use slogLevel (as SetFormat does).
slogOut = slogBuf
if err := SetFormat(TextFormat); err != nil {
t.Fatalf("unexpected error: %v", err)
}
slogBuf.Reset()
L.Info("should be hidden")
if slogBuf.Len() != 0 {
t.Errorf("expected info message to be suppressed at warn level, got: %s", slogBuf.String())
}
slogBuf.Reset()
L.Warn("should be visible")
if !strings.Contains(slogBuf.String(), "should be visible") {
t.Errorf("expected warn message to appear, got: %s", slogBuf.String())
}
// Raise level back to debug — info should now appear.
if err := SetLevel("debug"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
slogBuf.Reset()
L.Info("now visible")
if !strings.Contains(slogBuf.String(), "now visible") {
t.Errorf("expected info message to appear at debug level, got: %s", slogBuf.String())
}
// Direct changes to the Logrus logger should also affect slog filtering.
L.Logger.SetLevel(logrus.WarnLevel)
slogBuf.Reset()
L.Info("hidden after direct change")
if slogBuf.Len() != 0 {
t.Errorf("expected info message to be suppressed after direct level change, got: %s", slogBuf.String())
}
L.Logger.SetLevel(logrus.DebugLevel)
slogBuf.Reset()
L.Info("visible after direct change")
if !strings.Contains(slogBuf.String(), "visible after direct change") {
t.Errorf("expected info message to appear after direct level change, got: %s", slogBuf.String())
}
}