-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdebugLogger.test.ts
More file actions
436 lines (339 loc) · 12.8 KB
/
Copy pathdebugLogger.test.ts
File metadata and controls
436 lines (339 loc) · 12.8 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
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
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import {
createDebugLogger,
isDebugLoggingDegraded,
resetDebugLoggingState,
runWithoutDebugLogSession,
setDebugLogSession,
type DebugLogSession,
} from './debugLogger.js';
import { promises as fs } from 'node:fs';
import path from 'node:path';
import { Storage } from '../config/storage.js';
import { getTraceContext } from '../telemetry/trace-context.js';
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs')>();
return {
...actual,
promises: {
...actual.promises,
mkdir: vi.fn().mockResolvedValue(undefined),
appendFile: vi.fn().mockResolvedValue(undefined),
unlink: vi.fn().mockResolvedValue(undefined),
symlink: vi.fn().mockResolvedValue(undefined),
copyFile: vi.fn().mockResolvedValue(undefined),
},
};
});
vi.mock('../telemetry/trace-context.js', () => ({
getTraceContext: vi.fn().mockReturnValue(null),
}));
describe('debugLogger', () => {
const mockSession: DebugLogSession = {
getSessionId: () => 'test-session-123',
};
const previousDebugLogFileEnv = process.env['QWEN_DEBUG_LOG_FILE'];
beforeEach(async () => {
process.env['QWEN_DEBUG_LOG_FILE'] = '1';
Storage.setRuntimeBaseDir(null);
vi.clearAllMocks();
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-01-24T10:30:00.000Z'));
resetDebugLoggingState();
setDebugLogSession(mockSession);
await vi.runAllTimersAsync();
resetDebugLoggingState();
vi.clearAllMocks();
vi.mocked(getTraceContext).mockReturnValue(null);
});
afterEach(() => {
vi.useRealTimers();
setDebugLogSession(null);
Storage.setRuntimeBaseDir(null);
if (previousDebugLogFileEnv === undefined) {
delete process.env['QWEN_DEBUG_LOG_FILE'];
} else {
process.env['QWEN_DEBUG_LOG_FILE'] = previousDebugLogFileEnv;
}
});
describe('createDebugLogger', () => {
it('returns no-op logger when session is unset', () => {
setDebugLogSession(null);
const logger = createDebugLogger();
logger.debug('test');
logger.info('test');
logger.warn('test');
logger.error('test');
expect(fs.appendFile).not.toHaveBeenCalled();
});
it('suppresses the global debug session within an async context', async () => {
const logger = createDebugLogger('READ_ONLY');
await runWithoutDebugLogSession(async () => {
logger.warn('hidden before await');
await Promise.resolve();
logger.error('hidden after await');
});
await vi.runAllTimersAsync();
expect(fs.mkdir).not.toHaveBeenCalled();
expect(fs.appendFile).not.toHaveBeenCalled();
logger.info('visible outside context');
await vi.runAllTimersAsync();
expect(fs.appendFile).toHaveBeenCalledOnce();
});
it('writes debug log without trace context when telemetry context is unset', async () => {
const logger = createDebugLogger();
logger.debug('Hello world');
await vi.runAllTimersAsync();
expect(fs.mkdir).toHaveBeenCalledWith(Storage.getGlobalDebugDir(), {
recursive: true,
});
expect(fs.appendFile).toHaveBeenCalledWith(
Storage.getDebugLogPath('test-session-123'),
'2026-01-24T10:30:00.000Z [DEBUG] Hello world\n',
'utf8',
);
});
it('does not write debug log by default when QWEN_DEBUG_LOG_FILE is unset', async () => {
delete process.env['QWEN_DEBUG_LOG_FILE'];
const logger = createDebugLogger();
logger.info('default log');
await vi.runAllTimersAsync();
expect(fs.appendFile).not.toHaveBeenCalled();
});
it.each(['', ' ', '0', 'false', 'off', 'no'])(
'does not write debug log when QWEN_DEBUG_LOG_FILE is %j',
async (value) => {
process.env['QWEN_DEBUG_LOG_FILE'] = value;
const logger = createDebugLogger();
logger.info('disabled log');
await vi.runAllTimersAsync();
expect(fs.appendFile).not.toHaveBeenCalled();
},
);
it('writes log with tag when provided', async () => {
const logger = createDebugLogger('STARTUP');
logger.info('Server started');
await vi.runAllTimersAsync();
expect(fs.appendFile).toHaveBeenCalledWith(
Storage.getDebugLogPath('test-session-123'),
'2026-01-24T10:30:00.000Z [INFO] [STARTUP] Server started\n',
'utf8',
);
});
it('writes different log levels correctly', async () => {
const logger = createDebugLogger();
logger.debug('debug message');
logger.info('info message');
logger.warn('warn message');
logger.error('error message');
await vi.runAllTimersAsync();
const calls = vi.mocked(fs.appendFile).mock.calls;
expect(calls[0]?.[1]).toContain('[DEBUG]');
expect(calls[1]?.[1]).toContain('[INFO]');
expect(calls[2]?.[1]).toContain('[WARN]');
expect(calls[3]?.[1]).toContain('[ERROR]');
});
it('uses trace context when getTraceContext returns a context', async () => {
vi.mocked(getTraceContext).mockReturnValue({
traceId: 'realtraceidddddddddddddddddddddd',
spanId: 'realspanid111111',
traceFlags: 1,
});
const logger = createDebugLogger();
logger.debug('with real span');
await vi.runAllTimersAsync();
expect(fs.appendFile).toHaveBeenCalledWith(
expect.any(String),
expect.stringContaining(
'[trace_id=realtraceidddddddddddddddddddddd span_id=realspanid111111]',
),
'utf8',
);
});
it('omits trace context when getTraceContext returns null', async () => {
vi.mocked(getTraceContext).mockReturnValue(null);
const logger = createDebugLogger();
logger.debug('no trace context');
await vi.runAllTimersAsync();
expect(fs.appendFile).toHaveBeenCalledWith(
expect.any(String),
expect.not.stringContaining('trace_id='),
'utf8',
);
});
it('does not synthesize span ids when telemetry context is unset', async () => {
const logger = createDebugLogger();
logger.debug('first line');
logger.debug('second line');
await vi.runAllTimersAsync();
const calls = vi.mocked(fs.appendFile).mock.calls;
expect(calls).toHaveLength(2);
expect(calls[0]?.[1]).not.toContain('span_id=');
expect(calls[1]?.[1]).not.toContain('span_id=');
});
it('uses the session root span context for fallback trace context', async () => {
vi.mocked(getTraceContext).mockReturnValue({
traceId: 'cccccccccccccccccccccccccccccccc',
spanId: 'dddddddddddddddd',
traceFlags: 1,
});
const logger = createDebugLogger();
logger.debug('session root fallback');
await vi.runAllTimersAsync();
expect(fs.appendFile).toHaveBeenCalledWith(
expect.any(String),
expect.stringContaining(
'[trace_id=cccccccccccccccccccccccccccccccc span_id=dddddddddddddddd]',
),
'utf8',
);
});
it('creates a new debug directory after the runtime base dir changes', async () => {
Storage.setRuntimeBaseDir(path.resolve('runtime-a'));
const logger = createDebugLogger();
logger.debug('first');
await vi.runAllTimersAsync();
Storage.setRuntimeBaseDir(path.resolve('runtime-b'));
logger.debug('second');
await vi.runAllTimersAsync();
const mkdirCalls = vi.mocked(fs.mkdir).mock.calls;
expect(mkdirCalls).toContainEqual([
path.join(path.resolve('runtime-a'), 'debug'),
{ recursive: true },
]);
expect(mkdirCalls).toContainEqual([
path.join(path.resolve('runtime-b'), 'debug'),
{ recursive: true },
]);
});
it('formats multiple arguments', async () => {
const logger = createDebugLogger();
logger.debug('Count:', 42, 'items');
await vi.runAllTimersAsync();
expect(fs.appendFile).toHaveBeenCalledWith(
expect.any(String),
expect.stringContaining('Count: 42 items'),
'utf8',
);
});
it('formats Error objects with stack trace', async () => {
const logger = createDebugLogger();
const error = new Error('Something went wrong');
logger.error('Failed:', error);
await vi.runAllTimersAsync();
const call = vi.mocked(fs.appendFile).mock.calls[0];
expect(call?.[1]).toContain('Failed:');
expect(call?.[1]).toContain('Error: Something went wrong');
});
it('formats objects using util.inspect', async () => {
const logger = createDebugLogger();
logger.debug('Data:', { foo: 'bar', count: 123 });
await vi.runAllTimersAsync();
const call = vi.mocked(fs.appendFile).mock.calls[0];
expect(call?.[1]).toContain('foo');
expect(call?.[1]).toContain('bar');
});
});
describe('isDebugLoggingDegraded', () => {
it('returns false when no failures have occurred', () => {
expect(isDebugLoggingDegraded()).toBe(false);
});
it('returns true when mkdir fails', async () => {
resetDebugLoggingState();
vi.mocked(fs.mkdir).mockRejectedValueOnce(new Error('Permission denied'));
const logger = createDebugLogger();
logger.debug('test');
await vi.runAllTimersAsync();
expect(isDebugLoggingDegraded()).toBe(true);
});
it('returns true when appendFile fails', async () => {
vi.mocked(fs.appendFile).mockRejectedValueOnce(new Error('Disk full'));
const logger = createDebugLogger();
logger.debug('test');
await vi.runAllTimersAsync();
expect(isDebugLoggingDegraded()).toBe(true);
});
it('stays true after failure even if subsequent writes succeed', async () => {
vi.mocked(fs.appendFile).mockRejectedValueOnce(
new Error('Temporary error'),
);
const logger = createDebugLogger();
logger.debug('first write fails');
await vi.runAllTimersAsync();
expect(isDebugLoggingDegraded()).toBe(true);
vi.mocked(fs.appendFile).mockResolvedValue(undefined);
logger.debug('second write succeeds');
await vi.runAllTimersAsync();
expect(isDebugLoggingDegraded()).toBe(true);
});
});
describe('latest debug log symlink', () => {
const expectedLatestPath = path.join(Storage.getGlobalDebugDir(), 'latest');
const uuidSession: DebugLogSession = {
getSessionId: () => '92ec0176-d354-4147-848b-5cd2d80609c4',
};
it('creates a symlink to the current session log file', async () => {
resetDebugLoggingState();
setDebugLogSession(uuidSession);
await vi.runAllTimersAsync();
expect(fs.unlink).toHaveBeenCalledWith(expectedLatestPath);
expect(fs.symlink).toHaveBeenCalledWith(
'92ec0176-d354-4147-848b-5cd2d80609c4.txt',
expectedLatestPath,
);
});
it('does not create latest symlink when QWEN_DEBUG_LOG_FILE is unset', async () => {
delete process.env['QWEN_DEBUG_LOG_FILE'];
vi.clearAllMocks();
resetDebugLoggingState();
setDebugLogSession(uuidSession);
await vi.runAllTimersAsync();
expect(fs.symlink).not.toHaveBeenCalled();
});
it('does not point latest at non-session debug logs', async () => {
resetDebugLoggingState();
setDebugLogSession({ getSessionId: () => 'log-to-span-sink-test' });
await vi.runAllTimersAsync();
expect(fs.symlink).not.toHaveBeenCalled();
expect(fs.appendFile).not.toHaveBeenCalled();
});
it('does not create symlink when session is cleared', async () => {
vi.clearAllMocks();
resetDebugLoggingState();
setDebugLogSession(null);
await vi.runAllTimersAsync();
expect(fs.symlink).not.toHaveBeenCalled();
});
it('does not fall back to copy when symlink fails', async () => {
resetDebugLoggingState();
vi.mocked(fs.symlink).mockRejectedValueOnce(new Error('EPERM'));
setDebugLogSession(uuidSession);
await vi.runAllTimersAsync();
expect(fs.copyFile).not.toHaveBeenCalled();
});
it('does not create symlink when debug logging is disabled', async () => {
process.env['QWEN_DEBUG_LOG_FILE'] = '0';
vi.clearAllMocks();
resetDebugLoggingState();
setDebugLogSession(uuidSession);
await vi.runAllTimersAsync();
expect(fs.symlink).not.toHaveBeenCalled();
});
});
describe('resetDebugLoggingState', () => {
it('resets the degraded state', async () => {
vi.mocked(fs.appendFile).mockRejectedValueOnce(new Error('Disk full'));
const logger = createDebugLogger();
logger.debug('test');
await vi.runAllTimersAsync();
expect(isDebugLoggingDegraded()).toBe(true);
resetDebugLoggingState();
expect(isDebugLoggingDegraded()).toBe(false);
});
});
});