logger.test.js 2.39 KB
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)
  })
})