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>
This commit is contained in:
7 files changed
+303
-6
No files matched your search
@@ -1,3 +1,5 @@
|
||||
import type { EventPayload } from './bus';
|
||||
|
||||
/**
|
||||
* The logging contract. Four levels, because four have callers: core diagnostics are all `warn`
|
||||
* today, request logging adds `info` and `error`, and the graph diagnostics add `debug`. No
|
||||
@@ -59,6 +61,78 @@ function renderJson(level: LogLevel, message: string, fields?: LogFields): strin
|
||||
return JSON.stringify({ level, time: new Date().toISOString(), name: 'green-tea', msg: message, ...fields });
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a logger so a throwing one cannot go silent.
|
||||
*
|
||||
* `Bus.emit` isolates listener failures on purpose — an observer must never be able to break a
|
||||
* request — but that guarantee has a cost when the observer is the logger itself: a user logger
|
||||
* that throws would simply stop writing, with nothing to say so. Falling back to `console` keeps
|
||||
* the Bus's promise without paying for it in silence.
|
||||
*
|
||||
* Exported because request logging is not the only thing that should survive a broken logger.
|
||||
*/
|
||||
export function withConsoleFallback(logger: Logger): Logger {
|
||||
const guard =
|
||||
(level: LogLevel) =>
|
||||
(message: string, fields?: LogFields): void => {
|
||||
try {
|
||||
logger[level](message, fields);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
renderJson('error', 'the configured logger threw; falling back to console', {
|
||||
level,
|
||||
originalMessage: message,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
...fields,
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return { debug: guard('debug'), info: guard('info'), warn: guard('warn'), error: guard('error') };
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribes request logging to the lifecycle stream: `info` per completed request, `error` per
|
||||
* failed one. Returns an unsubscribe function, so it is as removable as it is composable — which
|
||||
* is what "a composable step, not a global middleware" has to mean in practice.
|
||||
*
|
||||
* Reads the stream rather than being called from the request path, so there is exactly one account
|
||||
* of what happened to a request. A second path would eventually disagree with the first.
|
||||
*/
|
||||
export function logRequests(bus: BusLike, logger: Logger): () => void {
|
||||
const safe = withConsoleFallback(logger);
|
||||
const offEnd = bus.on('request:end', (event) => {
|
||||
safe.info(`${event.method ?? ''} ${event.route ?? event.name} ${event.status ?? ''}`.trim(), {
|
||||
requestId: event.requestId,
|
||||
traceId: event.traceId,
|
||||
route: event.route,
|
||||
method: event.method,
|
||||
status: event.status,
|
||||
durationMs: event.durationMs,
|
||||
});
|
||||
});
|
||||
const offFailed = bus.on('request:failed', (event) => {
|
||||
safe.error(`${event.method ?? ''} ${event.route ?? event.name} failed`.trim(), {
|
||||
requestId: event.requestId,
|
||||
traceId: event.traceId,
|
||||
route: event.route,
|
||||
method: event.method,
|
||||
error: event.error instanceof Error ? event.error.message : event.error,
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
offEnd();
|
||||
offFailed();
|
||||
};
|
||||
}
|
||||
|
||||
/** The slice of {@link Bus} request logging needs — `on` only, matching what a plugin is handed. */
|
||||
interface BusLike {
|
||||
on(event: 'request:end' | 'request:failed', listener: (payload: EventPayload) => void): () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The logger used when `createApp` is given none: structured JSON, or human-readable on a TTY.
|
||||
*
|
||||
|
||||
Reference in new issue
Block a user