logger.test.js
2.39 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
import { describe, it, expect } from 'vitest'
import { createLogger } from '../src/logger.js'
import { createRequestContext } from '../src/context.js'
/** 简易 buffer sink。 */
function bufferSink() {
const lines = []
return { sink: (l) => lines.push(l), lines }
}
describe('createLogger', () => {
it('emits one valid JSON line per call with required fields', () => {
const buf = bufferSink()
const log = createLogger({ service: 'svc', sink: buf.sink })
const ctx = createRequestContext({ traceId: 'tid' })
log.child(ctx).info('hello', { k: 1 })
expect(buf.lines).toHaveLength(1)
const rec = JSON.parse(buf.lines[0])
expect(rec.service).toBe('svc')
expect(rec.trace_id).toBe('tid')
expect(rec.level).toBe('info')
expect(rec.msg).toBe('hello')
expect(typeof rec.time).toBe('string')
expect(rec.k).toBe(1)
})
it('filters levels below the configured threshold', () => {
const buf = bufferSink()
const log = createLogger({ service: 'svc', level: 'info', sink: buf.sink })
log.debug('dropped')
log.info('kept')
expect(buf.lines).toHaveLength(1)
expect(JSON.parse(buf.lines[0]).msg).toBe('kept')
})
it('child(ctx) binds the correct trace_id and ctx.fields on every line', () => {
const buf = bufferSink()
const log = createLogger({ service: 'svc', sink: buf.sink })
const ctx = createRequestContext({ traceId: 'T', fields: { userId: 'u1' } })
const clog = log.child(ctx)
clog.warn('a')
clog.error('b', { err: new Error('x') })
expect(buf.lines).toHaveLength(2)
for (const line of buf.lines) {
const rec = JSON.parse(line)
expect(rec.trace_id).toBe('T')
expect(rec.userId).toBe('u1')
}
expect(JSON.parse(buf.lines[1]).err.message).toBe('x')
})
it('per-call fields override bound ctx.fields', () => {
const buf = bufferSink()
const log = createLogger({ service: 'svc', sink: buf.sink })
const ctx = createRequestContext({ traceId: 'T', fields: { a: 1 } })
log.child(ctx).info('m', { a: 2 })
expect(JSON.parse(buf.lines[0]).a).toBe(2)
})
it('child does not mutate the parent logger', () => {
const buf = bufferSink()
const root = createLogger({ service: 'svc', sink: buf.sink })
const ctx = createRequestContext({ traceId: 'T' })
root.child(ctx)
root.info('no-trace')
const rec = JSON.parse(buf.lines[0])
expect('trace_id' in rec).toBe(false)
})
})