Files
core/test/logger.test.ts
T
chrnx e052d5ba8f feat(observability): request-level events, and request logging that reads them
Tasks 5 and 6, in that order rather than the plan's: request logging is a
subscriber, so the events it subscribes to had to exist first.

handle() now emits request:start, request:end, route:matched and
route:unmatched. request:end fires when the handler returns, not when a stream
it produced finishes — a streaming route is done here in milliseconds while its
connection may live for hours, and ending the span at close would put hour-long
SSE connections and 2ms buffered replies in one latency distribution. The
stream events already describe the connection and now share the requestId.

route:unmatched covers 404 and 405 both. Naming it after one outcome, as the
report's route.not_found does, would misreport the other.

logRequests(bus, logger) is the consumer: info per completed request, error per
failed one, and it returns an unsubscribe so it is removable rather than merely
optional. createApp({ logRequests: true }) turns it on and is off by default,
because a framework that writes to stdout uninvited is one you have to
configure before you can use it. withConsoleFallback wraps it, since Bus.emit
isolates listener failures by design and a user logger that throws would
otherwise stop writing with nothing to say so. A test proves both halves: the
request still succeeds, and the failure still surfaces.

The bus reaches handle() through HttpOptions so the Node and Fetch adapters
share one channel instead of growing separate ones.

Cost, measured: nothing. First attempt wrapped dispatch in a second async frame
and that alone cost 0.43us per request — a promise and two microtask ticks,
an order of magnitude more than the four Map lookups it was there to arrange.
handle() is no longer async and hands back dispatch's own promise when nothing
subscribes; 4.716-4.791us against 4.736-4.793 before, which is the same number.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 14:57:42 -05:00

254 lines
8.8 KiB
TypeScript

import { describe, it, expect, vi, afterEach } from 'vitest';
import { createApp, createDefaultLogger, logRequests, Route, Get, Step, Module, Provider, needs } from '../src/index';
import type { Logger, LogFields } from '../src/index';
/** Captures every call so a test can assert on what core wrote rather than on console output. */
function recordingLogger(): Logger & { records: Array<{ level: string; message: string; fields?: LogFields }> } {
const records: Array<{ level: string; message: string; fields?: LogFields }> = [];
const at =
(level: string) =>
(message: string, fields?: LogFields): void => {
records.push({ level, message, fields });
};
return { records, debug: at('debug'), info: at('info'), warn: at('warn'), error: at('error') };
}
afterEach(() => {
vi.restoreAllMocks();
});
describe('default logger', () => {
it('writes one JSON object per record when not on a TTY', () => {
const spy = vi.spyOn(console, 'warn').mockImplementation(() => {});
createDefaultLogger(false).warn('something happened', { route: '/x', count: 2 });
expect(spy).toHaveBeenCalledTimes(1);
const written = JSON.parse(spy.mock.calls[0][0] as string);
expect(written).toMatchObject({ level: 'warn', name: 'green-tea', msg: 'something happened', route: '/x', count: 2 });
// A log aggregator filters on a field; it cannot filter on a substring of prose.
expect(written.msg).not.toContain('[green-tea]');
expect(typeof written.time).toBe('string');
});
it('writes a readable line instead when interactive', () => {
const spy = vi.spyOn(console, 'warn').mockImplementation(() => {});
createDefaultLogger(true).warn('something happened', { route: '/x' });
const written = spy.mock.calls[0][0] as string;
expect(written).toBe('[green-tea] WARN something happened route=/x');
});
it('routes each level to the matching console method', () => {
const spies = {
debug: vi.spyOn(console, 'debug').mockImplementation(() => {}),
info: vi.spyOn(console, 'info').mockImplementation(() => {}),
warn: vi.spyOn(console, 'warn').mockImplementation(() => {}),
error: vi.spyOn(console, 'error').mockImplementation(() => {}),
};
const logger = createDefaultLogger(false);
logger.debug('d');
logger.info('i');
logger.warn('w');
logger.error('e');
for (const spy of Object.values(spies)) expect(spy).toHaveBeenCalledTimes(1);
});
});
describe('createApp({ logger })', () => {
@Route('/')
class Ctl {
@Get('/ok')
ok() {
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
it('sends framework diagnostics to the supplied logger, not to console', async () => {
const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const logger = recordingLogger();
const app = createApp({ modules: [M], logger });
// close({ timeoutMs }) on an app that never listen()ed is one of the diagnostics core emits.
await app.close({ timeoutMs: 100 });
expect(logger.records).toHaveLength(1);
expect(logger.records[0].level).toBe('warn');
expect(logger.records[0].message).toContain('has no listen()ed server');
// The point of the contract: nothing reached console behind the logger's back.
expect(consoleWarn).not.toHaveBeenCalled();
});
it('exposes the logger on the app so adapters and plugins share it', () => {
const logger = recordingLogger();
expect(createApp({ modules: [M], logger }).logger).toBe(logger);
});
it('warns about a deep dependency chain through the logger, with structured fields', () => {
const logger = recordingLogger();
@Step({ provides: 's0' })
class S0 {
run() {
return { s0: 0 };
}
}
@Step({ provides: 's1', needs: ['s0'] })
class S1 {
run() {
return { s1: 1 };
}
}
@Route('/deep')
class DeepCtl {
@Get('/go')
go(@needs('s1') s: unknown) {
return { s };
}
}
@Module({ mountpoint: '/', steps: [S0, S1], controllers: [DeepCtl] })
class DeepModule {}
createApp({ modules: [DeepModule], logger, warnGraphDepth: 1 });
const warned = logger.records.find((r) => r.message.includes('unusually deep'));
expect(warned).toBeDefined();
// Structured, so a dashboard can group by route instead of parsing the sentence.
expect(warned!.fields).toMatchObject({ route: '/deep/go', method: 'GET', depth: 2, threshold: 1 });
});
});
describe('request logging', () => {
@Route('/api')
class Ctl {
@Get('/ok')
ok() {
return { ok: true };
}
@Get('/boom')
boom(): never {
throw new Error('handler exploded');
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
it('is off unless asked for', async () => {
const logger = recordingLogger();
const app = createApp({ modules: [M], logger });
await app.fetch(new Request('http://x/api/ok'));
// A framework that writes to stdout uninvited is one you must configure before using.
expect(logger.records).toHaveLength(0);
});
it('logs one info per completed request, with the pattern and a duration', async () => {
const logger = recordingLogger();
const app = createApp({ modules: [M], logger, logRequests: true });
await app.fetch(new Request('http://x/api/ok'));
expect(logger.records).toHaveLength(1);
const [record] = logger.records;
expect(record.level).toBe('info');
expect(record.fields).toMatchObject({ route: '/api/ok', method: 'GET', status: 200 });
expect(typeof record.fields!.requestId).toBe('string');
expect(record.fields!.durationMs).toBeGreaterThanOrEqual(0);
});
it('logs an error for a failed request, correlated with it', async () => {
const logger = recordingLogger();
const app = createApp({ modules: [M], logger, logRequests: true });
await app.fetch(new Request('http://x/api/boom'));
const failed = logger.records.find((r) => r.level === 'error');
expect(failed).toBeDefined();
expect(failed!.fields).toMatchObject({ route: '/api/boom', error: 'handler exploded' });
// Same request, so the failure and the completion carry one identity between them.
const completed = logger.records.find((r) => r.level === 'info');
expect(completed!.fields!.requestId).toBe(failed!.fields!.requestId);
});
it('unsubscribes, so it is removable and not just optional', async () => {
const logger = recordingLogger();
const app = createApp({ modules: [M], logger });
const stop = logRequests(app.bus, logger);
await app.fetch(new Request('http://x/api/ok'));
expect(logger.records).toHaveLength(1);
stop();
await app.fetch(new Request('http://x/api/ok'));
expect(logger.records).toHaveLength(1);
});
it('keeps writing, and keeps serving, when the logger throws on every call', async () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
const exploding: Logger = {
debug: () => {
throw new Error('logger is broken');
},
info: () => {
throw new Error('logger is broken');
},
warn: () => {
throw new Error('logger is broken');
},
error: () => {
throw new Error('logger is broken');
},
};
const app = createApp({ modules: [M], logger: exploding, logRequests: true });
const res = await app.fetch(new Request('http://x/api/ok'));
// The request is unharmed: Bus.emit isolates listener failures by design.
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ ok: true });
// And the failure is not silent, which is what the wrapper buys on top of that guarantee.
expect(consoleError).toHaveBeenCalled();
const written = JSON.parse(consoleError.mock.calls[0][0] as string);
expect(written.msg).toContain('the configured logger threw');
expect(written.error).toBe('logger is broken');
});
});
describe('logger as a dependency', () => {
it('is injectable with @needs("logger") and is the same instance', async () => {
const logger = recordingLogger();
let seen: unknown;
@Provider({ provides: 'noop' })
class Noop {
provide() {
return { noop: 1 };
}
}
@Route('/')
class Ctl {
@Get('/log')
log(@needs('logger') injected: Logger) {
seen = injected;
injected.info('from a handler', { where: 'handler' });
return { ok: true };
}
}
@Module({ mountpoint: '/', providers: [Noop], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], logger });
await app.fetch(new Request('http://x/log'));
// One object, two access paths — not a second logger wired into the graph.
expect(seen).toBe(logger);
expect(logger.records).toContainEqual({ level: 'info', message: 'from a handler', fields: { where: 'handler' } });
});
});