-
Notifications
You must be signed in to change notification settings - Fork 66.7k
Expand file tree
/
Copy pathlogger.ts
More file actions
527 lines (423 loc) · 18.9 KB
/
logger.ts
File metadata and controls
527 lines (423 loc) · 18.9 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
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { createLogger } from '@/observability/logger'
// Mock only the logger-context for most tests, but we'll test integration without mocks
vi.mock('@/observability/logger/lib/logger-context')
describe('createLogger', () => {
let originalEnv: typeof process.env
let originalConsoleLog: typeof console.log
let originalConsoleError: typeof console.error
const consoleLogs: string[] = []
const consoleErrors: unknown[] = []
beforeEach(() => {
// Store original environment and console methods
originalEnv = { ...process.env }
originalConsoleLog = console.log
originalConsoleError = console.error
// Mock console methods to capture output
console.log = vi.fn((message: string) => {
consoleLogs.push(message)
})
console.error = vi.fn((error: unknown) => {
consoleErrors.push(error)
})
// Clear captured output
consoleLogs.length = 0
consoleErrors.length = 0
// Set default environment
vi.stubEnv('NODE_ENV', 'development')
vi.stubEnv('LOG_LEVEL', 'debug')
})
afterEach(() => {
// Restore original environment and console methods
process.env = originalEnv
console.log = originalConsoleLog
console.error = originalConsoleError
vi.clearAllMocks()
})
describe('constructor validation', () => {
it('should throw error when filePath is not provided', () => {
expect(() => createLogger('')).toThrow(
'createLogger must be called with the import.meta.url argument',
)
})
it('should throw error when filePath is null or undefined', () => {
expect(() => createLogger(null as unknown as string)).toThrow(
'createLogger must be called with the import.meta.url argument',
)
expect(() => createLogger(undefined as unknown as string)).toThrow(
'createLogger must be called with the import.meta.url argument',
)
})
it('should create logger successfully with valid filePath', () => {
const logger = createLogger('file:///path/to/test.js')
expect(logger).toHaveProperty('error')
expect(logger).toHaveProperty('warn')
expect(logger).toHaveProperty('info')
expect(logger).toHaveProperty('debug')
})
})
describe('logging patterns in development mode', () => {
let logger: ReturnType<typeof createLogger>
beforeEach(() => {
vi.stubEnv('NODE_ENV', 'development')
logger = createLogger('file:///path/to/test.js')
})
it('should log simple messages (Pattern 1)', () => {
logger.info('Hello world')
expect(consoleLogs).toContain('[INFO] Hello world')
})
it('should log messages with extra data (Pattern 2)', () => {
logger.info('User logged in', { userId: 123, email: 'test@example.com' })
expect(consoleLogs).toContain('[INFO] User logged in')
})
it('should log multiple message parts (Pattern 3)', () => {
logger.info('User', 'action', 123, true)
expect(consoleLogs).toContain('[INFO] User action 123 true')
})
it('should log multiple message parts with extra data (Pattern 4)', () => {
logger.info('User', 'login', 'success', { userId: 123 })
expect(consoleLogs).toContain('[INFO] User login success')
})
it('should log messages with Error objects (Pattern 5)', () => {
const error = new Error('Database connection failed')
logger.error('Database error', error)
expect(consoleLogs).toContain('[ERROR] Database error: Database connection failed')
expect(consoleErrors).toContain(error)
})
it('should log messages with multiple errors and parts (Pattern 6)', () => {
const error1 = new Error('First error')
const error2 = new Error('Second error')
logger.error('Multiple failures', error1, error2)
expect(consoleLogs).toContain('[ERROR] Multiple failures: First error, Second error')
expect(consoleErrors).toContain(error1)
expect(consoleErrors).toContain(error2)
})
it('should handle mixed arguments with errors and extra data', () => {
const error = new Error('Test error')
logger.error('Operation failed', 'with code', 500, error, { operation: 'delete' })
expect(consoleLogs).toContain('[ERROR] Operation failed with code 500: Test error')
expect(consoleErrors).toContain(error)
})
it('should log all levels in development', () => {
logger.debug('Debug message')
logger.info('Info message')
logger.warn('Warning message')
logger.error('Error message')
expect(consoleLogs).toContain('[DEBUG] Debug message')
expect(consoleLogs).toContain('[INFO] Info message')
expect(consoleLogs).toContain('[WARN] Warning message')
expect(consoleLogs).toContain('[ERROR] Error message')
})
})
describe('logging with mocked context', () => {
let logger: ReturnType<typeof createLogger>
beforeEach(() => {
logger = createLogger('file:///path/to/test.js')
})
it('should use development format when context is mocked', () => {
logger.info('Test message')
// Check that a log was output in development format
expect(consoleLogs).toHaveLength(1)
const logOutput = consoleLogs[0]
expect(logOutput).toBe('[INFO] Test message')
})
it('should include extra data in development logs', () => {
logger.info('User action', { userId: 123, action: 'login' })
expect(consoleLogs).toHaveLength(1)
const logOutput = consoleLogs[0]
expect(logOutput).toBe('[INFO] User action')
})
it('should format errors properly in development logs', () => {
const error = new Error('Test error')
error.stack = 'Error: Test error\n at test.js:1:1'
logger.error('Something failed', error)
expect(consoleLogs).toHaveLength(1)
expect(consoleErrors).toHaveLength(1)
const logOutput = consoleLogs[0]
expect(logOutput).toBe('[ERROR] Something failed: Test error')
expect(consoleErrors[0]).toBe(error)
})
it('should handle multiple errors in development logs', () => {
const error1 = new Error('First error')
const error2 = new Error('Second error')
error1.stack = 'Error: First error\n at test.js:1:1'
error2.stack = 'Error: Second error\n at test.js:2:1'
logger.error('Multiple errors', error1, error2)
// In development mode, each error triggers a separate console.log + console.error
expect(consoleLogs).toHaveLength(2)
expect(consoleErrors).toHaveLength(2)
// Both log entries should have the same message
expect(consoleLogs[0]).toBe('[ERROR] Multiple errors: First error, Second error')
expect(consoleLogs[1]).toBe('[ERROR] Multiple errors: First error, Second error')
expect(consoleErrors[0]).toBe(error1)
expect(consoleErrors[1]).toBe(error2)
})
})
describe('log level filtering', () => {
let logger: ReturnType<typeof createLogger>
beforeEach(() => {
// Clear console logs before each test
consoleLogs.length = 0
consoleErrors.length = 0
})
it('should respect LOG_LEVEL=error setting', () => {
// Mock the function to return error level (0) and dynamically import logger
vi.stubEnv('LOG_LEVEL', 'error')
logger = createLogger('file:///path/to/test.js')
logger.debug('Debug message')
logger.info('Info message')
logger.warn('Warn message')
logger.error('Error message')
expect(consoleLogs).not.toContain('[DEBUG] Debug message')
expect(consoleLogs).not.toContain('[INFO] Info message')
expect(consoleLogs).not.toContain('[WARN] Warn message')
expect(consoleLogs).toContain('[ERROR] Error message')
})
it('should respect LOG_LEVEL=warn setting', () => {
vi.stubEnv('LOG_LEVEL', 'warn')
logger = createLogger('file:///path/to/test.js')
logger.debug('Debug message')
logger.info('Info message')
logger.warn('Warn message')
logger.error('Error message')
expect(consoleLogs).not.toContain('[DEBUG] Debug message')
expect(consoleLogs).not.toContain('[INFO] Info message')
expect(consoleLogs).toContain('[WARN] Warn message')
expect(consoleLogs).toContain('[ERROR] Error message')
})
it('should respect LOG_LEVEL=info setting', () => {
vi.stubEnv('LOG_LEVEL', 'info')
logger = createLogger('file:///path/to/test.js')
logger.debug('Debug message')
logger.info('Info message')
logger.warn('Warn message')
logger.error('Error message')
expect(consoleLogs).not.toContain('[DEBUG] Debug message')
expect(consoleLogs).toContain('[INFO] Info message')
expect(consoleLogs).toContain('[WARN] Warn message')
expect(consoleLogs).toContain('[ERROR] Error message')
})
})
describe('edge cases and error handling', () => {
let logger: ReturnType<typeof createLogger>
beforeEach(() => {
// Clear console logs before each test
consoleLogs.length = 0
consoleErrors.length = 0
logger = createLogger('file:///path/to/test.js')
})
it('should handle null and undefined values in extra data', () => {
logger.info('Test message', { nullValue: null, undefinedValue: undefined })
expect(consoleLogs).toContain('[INFO] Test message')
})
it('should handle arrays in extra data', () => {
logger.info('Test message', { items: [1, 2, 3] })
expect(consoleLogs).toContain('[INFO] Test message')
})
it('should handle Date objects in extra data', () => {
const date = new Date('2023-01-01T00:00:00.000Z')
logger.info('Test message', { timestamp: date })
expect(consoleLogs).toContain('[INFO] Test message')
})
it('should handle nested objects properly', () => {
logger.info('Test message', {
user: {
id: 123,
profile: { name: 'John', age: 30 },
},
})
expect(consoleLogs).toContain('[INFO] Test message')
})
it('should distinguish between plain objects and class instances', () => {
class CustomClass {
constructor(public value: string) {}
}
const instance = new CustomClass('test')
logger.info('Custom object', instance)
expect(consoleLogs).toContain('[INFO] Custom object [object Object]')
})
it('should handle empty arguments gracefully', () => {
logger.info('Just a message')
expect(consoleLogs).toContain('[INFO] Just a message')
})
it('should handle boolean and number arguments', () => {
logger.info('Values:', true, false, 42, 0, -1)
expect(consoleLogs).toContain('[INFO] Values: true false 42 0 -1')
})
})
describe('file path handling in development', () => {
it('should log file paths in development format', () => {
const logger = createLogger('file:///Users/test/project/src/test.js')
logger.info('Test message')
expect(consoleLogs).toHaveLength(1)
const logOutput = consoleLogs[0]
expect(logOutput).toBe('[INFO] Test message')
})
it('should handle relative paths in development logs', () => {
const logger = createLogger('file:///absolute/path/to/src/component/test.ts')
logger.info('Test message')
expect(consoleLogs).toHaveLength(1)
const logOutput = consoleLogs[0]
expect(logOutput).toBe('[INFO] Test message')
})
})
describe('logger context integration with mocks', () => {
let logger: ReturnType<typeof createLogger>
beforeEach(() => {
logger = createLogger('file:///path/to/test.js')
})
it('should handle missing logger context gracefully in development', () => {
logger.info('No context test')
expect(consoleLogs).toHaveLength(1)
const logOutput = consoleLogs[0]
expect(logOutput).toBe('[INFO] No context test')
})
})
describe('complex argument combinations', () => {
let logger: ReturnType<typeof createLogger>
beforeEach(() => {
// Clear console logs before each test
consoleLogs.length = 0
consoleErrors.length = 0
logger = createLogger('file:///path/to/test.js')
})
it('should handle error at the beginning of arguments', () => {
const error = new Error('First error')
logger.error('Error occurred', error, 'additional', 'info', { extra: 'data' })
expect(consoleLogs).toContain('[ERROR] Error occurred additional info: First error')
expect(consoleErrors).toContain(error)
})
it('should handle error in the middle of arguments', () => {
const error = new Error('Middle error')
logger.error('Error', 'in', error, 'middle', { context: 'test' })
expect(consoleLogs).toContain('[ERROR] Error in middle: Middle error')
expect(consoleErrors).toContain(error)
})
it('should handle multiple data types in arguments', () => {
logger.info('Mixed', 123, true, 'string', { data: 'object' })
expect(consoleLogs).toContain('[INFO] Mixed 123 true string')
})
it('should prioritize plain objects as extra data over other objects', () => {
vi.stubEnv('LOG_LIKE_PRODUCTION', 'true')
// Create new logger instance
logger = createLogger('file:///path/to/test.js')
const date = new Date()
const plainObject = { key: 'value' }
logger.info('Test', date, 'string', plainObject)
expect(consoleLogs).toHaveLength(1)
const logOutput = consoleLogs[0]
// The message should contain the full string with date converted to string
expect(logOutput).toContain('message="Test')
expect(logOutput).toContain('string"')
// The plain object should be in the included context
expect(logOutput).toContain('included.key=value')
})
})
describe('pod identity fields in production logs', () => {
it('should include podName, podNamespace, nodeHostname in logfmt output when env vars are set', async () => {
vi.stubEnv('POD_NAME', 'webapp-abc123')
vi.stubEnv('POD_NAMESPACE', 'docs-internal-staging-cedar')
vi.stubEnv('KUBE_NODE_HOSTNAME', 'ghe-k8s-node-42')
vi.stubEnv('LOG_LIKE_PRODUCTION', 'true')
// Reset modules so pod-identity is re-evaluated with the new env vars
vi.resetModules()
const { createLogger: freshCreateLogger } = await import('@/observability/logger')
const logger = freshCreateLogger('file:///path/to/test.js')
logger.info('Pod identity test')
expect(consoleLogs).toHaveLength(1)
const logOutput = consoleLogs[0]
expect(logOutput).toContain('podName=webapp-abc123')
expect(logOutput).toContain('podNamespace=docs-internal-staging-cedar')
expect(logOutput).toContain('nodeHostname=ghe-k8s-node-42')
})
it('should not include pod identity fields in logfmt output when env vars are absent', async () => {
vi.stubEnv('LOG_LIKE_PRODUCTION', 'true')
// Ensure pod env vars are absent
delete process.env.POD_NAME
delete process.env.POD_NAMESPACE
delete process.env.KUBE_NODE_HOSTNAME
vi.resetModules()
const { createLogger: freshCreateLogger } = await import('@/observability/logger')
const logger = freshCreateLogger('file:///path/to/test.js')
logger.info('No pod identity test')
expect(consoleLogs).toHaveLength(1)
const logOutput = consoleLogs[0]
expect(logOutput).not.toContain('podName=')
expect(logOutput).not.toContain('podNamespace=')
expect(logOutput).not.toContain('nodeHostname=')
})
})
describe('BUILD_SHA in production logs', () => {
it('should include build_sha in logfmt output when BUILD_SHA env var is set', async () => {
vi.stubEnv('BUILD_SHA', 'abc123def456')
vi.stubEnv('LOG_LIKE_PRODUCTION', 'true')
vi.resetModules()
const { createLogger: freshCreateLogger } = await import('@/observability/logger')
const logger = freshCreateLogger('file:///path/to/test.js')
logger.info('Build SHA test')
expect(consoleLogs).toHaveLength(1)
const logOutput = consoleLogs[0]
expect(logOutput).toContain('build_sha=abc123def456')
})
it('should not include build_sha in logfmt output when BUILD_SHA env var is absent', async () => {
vi.stubEnv('LOG_LIKE_PRODUCTION', 'true')
delete process.env.BUILD_SHA
vi.resetModules()
const { createLogger: freshCreateLogger } = await import('@/observability/logger')
const logger = freshCreateLogger('file:///path/to/test.js')
logger.info('No build SHA test')
expect(consoleLogs).toHaveLength(1)
const logOutput = consoleLogs[0]
expect(logOutput).not.toContain('build_sha=')
})
})
describe('error serialization in production logs', () => {
it('should include error_code and error_name when Error has a .code property', async () => {
vi.stubEnv('LOG_LIKE_PRODUCTION', 'true')
vi.resetModules()
const { createLogger: freshCreateLogger } = await import('@/observability/logger')
const logger = freshCreateLogger('file:///path/to/test.js')
const error = new Error('Connection reset') as NodeJS.ErrnoException
error.code = 'ECONNRESET'
logger.error('Network failure', error)
expect(consoleLogs).toHaveLength(1)
const logOutput = consoleLogs[0]
expect(logOutput).toContain('included.error="Connection reset"')
expect(logOutput).toContain('included.error_code=ECONNRESET')
expect(logOutput).toContain('included.error_name=Error')
expect(logOutput).toContain('included.error_stack=')
})
it('should include error_name even when .code is undefined', async () => {
vi.stubEnv('LOG_LIKE_PRODUCTION', 'true')
vi.resetModules()
const { createLogger: freshCreateLogger } = await import('@/observability/logger')
const logger = freshCreateLogger('file:///path/to/test.js')
const error = new TypeError('Cannot read property')
logger.error('Type error occurred', error)
expect(consoleLogs).toHaveLength(1)
const logOutput = consoleLogs[0]
expect(logOutput).toContain('included.error="Cannot read property"')
expect(logOutput).toContain('included.error_name=TypeError')
// When .code is undefined, error_code is present but empty
expect(logOutput).toMatch(/included\.error_code= /)
expect(logOutput).toContain('included.error_stack=')
})
it('should serialize multiple errors with indexed keys', async () => {
vi.stubEnv('LOG_LIKE_PRODUCTION', 'true')
vi.resetModules()
const { createLogger: freshCreateLogger } = await import('@/observability/logger')
const logger = freshCreateLogger('file:///path/to/test.js')
const error1 = new Error('First') as NodeJS.ErrnoException
error1.code = 'ERR_FIRST'
const error2 = new Error('Second')
logger.error('Multiple errors', error1, error2)
expect(consoleLogs).toHaveLength(1)
const logOutput = consoleLogs[0]
expect(logOutput).toContain('included.error_1=First')
expect(logOutput).toContain('included.error_1_code=ERR_FIRST')
expect(logOutput).toContain('included.error_1_name=Error')
expect(logOutput).toContain('included.error_2=Second')
expect(logOutput).toContain('included.error_2_name=Error')
})
})
})