feat(observability): an injectable logger, and a lint rule that keeps core off console
Task 4. createApp({ logger }) accepts any Logger; the default writes structured
JSON, or a readable line on a TTY, decided once at construction rather than per
record. It writes through console, which is what lets core have a logging
contract while reflect-metadata stays the only runtime dependency.
Four levels, because four have callers. Core's diagnostics were all warn — every
one of the eight console.warn calls — and request logging adds info and error.
No trace, no fatal: a level nothing emits is a decision handed to the user for
no reason.
Registered rather than declared as a provider. Provider boot failures are
reported while the graph is still resolving and shutdown warnings after it is
gone, so a logger that lives in the graph cannot cover either end. It is also
registered as a builtin provider, so @needs('logger') reaches the same object —
one instance, two access paths — and exposed on App so serveDeno/serveBun report
through the application's logger instead of past it.
The [green-tea] prefix moves out of the prose into a `name` field: an aggregator
filters on a field and cannot filter on a substring of a sentence. Context that
was interpolated into messages is now structured alongside them.
#10 asks that nothing in core call console directly. That is now a lint rule
scoped to src/ rather than a grep somebody has to remember, with src/logger.ts
exempted because being the console sink is its entire job. Verified it fails on
a planted console.log.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
8 files changed
+316
-26
No files matched your search
@@ -23,4 +23,12 @@ export default tseslint.config(
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
// Nothing in core writes to console directly — every diagnostic goes through the injectable
|
||||||
|
// `Logger`, or an application cannot redirect it. This is the rule form of a check that was
|
||||||
|
// otherwise a `grep` somebody has to remember to run.
|
||||||
|
files: ['src/**/*.ts'],
|
||||||
|
ignores: ['src/logger.ts'], // the default logger *is* the console sink; that is its whole job
|
||||||
|
rules: { 'no-console': 'error' },
|
||||||
|
},
|
||||||
);
|
);
|
||||||
+54
-21
@@ -1,5 +1,6 @@
|
|||||||
import type http from 'http';
|
import type http from 'http';
|
||||||
import { Bus } from '../bus';
|
import { Bus } from '../bus';
|
||||||
|
import { createDefaultLogger, type Logger } from '../logger';
|
||||||
import { Container } from '../container';
|
import { Container } from '../container';
|
||||||
import { topoSort, subgraphFor, GraphNode, nearest } from '../graph';
|
import { topoSort, subgraphFor, GraphNode, nearest } from '../graph';
|
||||||
import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
|
import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
|
||||||
@@ -110,6 +111,16 @@ export function createApp(opts: {
|
|||||||
* where passing it per call is not an option.
|
* where passing it per call is not an option.
|
||||||
*/
|
*/
|
||||||
shutdownTimeoutMs?: number;
|
shutdownTimeoutMs?: number;
|
||||||
|
/**
|
||||||
|
* Where every framework diagnostic is written (default: structured JSON, human-readable on a TTY).
|
||||||
|
*
|
||||||
|
* Registered here rather than declared as a provider, and the ordering is why: provider boot
|
||||||
|
* events and the failures they report happen *while* the graph resolves, so a provider cannot
|
||||||
|
* report its own boot failing, and shutdown warnings happen after the graph is gone. The logger
|
||||||
|
* has to outlive the graph on both ends. It is also reachable from a step or handler as
|
||||||
|
* `@needs('logger')` — one object, two access paths.
|
||||||
|
*/
|
||||||
|
logger?: Logger;
|
||||||
/** Opt in to alpha features whose API may still change. Currently gates `mesh`. */
|
/** Opt in to alpha features whose API may still change. Currently gates `mesh`. */
|
||||||
experimental?: boolean;
|
experimental?: boolean;
|
||||||
/**
|
/**
|
||||||
@@ -127,6 +138,7 @@ export function createApp(opts: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const bus = new Bus();
|
const bus = new Bus();
|
||||||
|
const logger = opts.logger ?? createDefaultLogger();
|
||||||
const container = new Container();
|
const container = new Container();
|
||||||
let server: http.Server | undefined;
|
let server: http.Server | undefined;
|
||||||
const streams = new Set<() => void>();
|
const streams = new Set<() => void>();
|
||||||
@@ -137,7 +149,7 @@ export function createApp(opts: {
|
|||||||
const registry = collectModules(opts.modules, viewsCtx);
|
const registry = collectModules(opts.modules, viewsCtx);
|
||||||
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
|
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
|
||||||
mountPlugins(opts.plugins, bus, registry);
|
mountPlugins(opts.plugins, bus, registry);
|
||||||
provideBuiltins(registry);
|
provideBuiltins(registry, logger);
|
||||||
|
|
||||||
// For each route, resolve which providers/steps feed it via topo order.
|
// For each route, resolve which providers/steps feed it via topo order.
|
||||||
// MVP: every route depends on every declared step + provider in the app graph.
|
// MVP: every route depends on every declared step + provider in the app graph.
|
||||||
@@ -150,7 +162,7 @@ export function createApp(opts: {
|
|||||||
const meshLinks: Link[] = [];
|
const meshLinks: Link[] = [];
|
||||||
|
|
||||||
const finalize = (): void => {
|
const finalize = (): void => {
|
||||||
({ orderedProviders, orderedSteps } = finalizeGraph(registry, opts.warnGraphDepth));
|
({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth));
|
||||||
booted = true;
|
booted = true;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -166,7 +178,7 @@ export function createApp(opts: {
|
|||||||
// can only be built here, after finalize(), and never at construction time.
|
// can only be built here, after finalize(), and never at construction time.
|
||||||
const prepareGraph = async (): Promise<void> => {
|
const prepareGraph = async (): Promise<void> => {
|
||||||
if (opts.mesh && !booted) {
|
if (opts.mesh && !booted) {
|
||||||
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry);
|
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger);
|
||||||
remoteRoutes = spliced.remoteRoutes;
|
remoteRoutes = spliced.remoteRoutes;
|
||||||
meshLinks.push(...spliced.meshLinks);
|
meshLinks.push(...spliced.meshLinks);
|
||||||
finalize();
|
finalize();
|
||||||
@@ -214,7 +226,7 @@ export function createApp(opts: {
|
|||||||
registry,
|
registry,
|
||||||
opts.overrides,
|
opts.overrides,
|
||||||
() => orderedProviders,
|
() => orderedProviders,
|
||||||
{ runners, container, providerMeta, bus },
|
{ runners, container, providerMeta, bus, logger },
|
||||||
degradedProviders,
|
degradedProviders,
|
||||||
ready,
|
ready,
|
||||||
);
|
);
|
||||||
@@ -268,7 +280,7 @@ export function createApp(opts: {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const close = (options: { timeoutMs?: number } = {}): Promise<void> =>
|
const close = (options: { timeoutMs?: number } = {}): Promise<void> =>
|
||||||
closeApp(server, meshLinks, streams, options, opts.shutdownTimeoutMs);
|
closeApp(server, meshLinks, streams, options, opts.shutdownTimeoutMs, logger);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
listen,
|
listen,
|
||||||
@@ -284,6 +296,7 @@ export function createApp(opts: {
|
|||||||
openapi,
|
openapi,
|
||||||
degraded: () => [...degradedProviders],
|
degraded: () => [...degradedProviders],
|
||||||
bus,
|
bus,
|
||||||
|
logger,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -450,7 +463,17 @@ function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registr
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Auto-provides a shared {@link Rooms} instance unless the user already declared a `rooms` provider. */
|
/** Auto-provides a shared {@link Rooms} instance unless the user already declared a `rooms` provider. */
|
||||||
function provideBuiltins(registry: Registry): void {
|
function provideBuiltins(registry: Registry, logger: Logger): void {
|
||||||
|
// `logger` is registered as an ordinary provider *in addition to* being framework infrastructure,
|
||||||
|
// so a step or handler reaches it with `@needs('logger')` like any other dependency. It is the
|
||||||
|
// same object createApp holds, not a second one — core cannot depend on the graph for something
|
||||||
|
// it must use while the graph is still resolving.
|
||||||
|
if (!registry.runners.has('logger')) {
|
||||||
|
registry.providerNodes.push({ name: 'logger', needs: [], provides: ['logger'], origin: 'builtin' });
|
||||||
|
registry.providerMeta.set('logger', { optional: false });
|
||||||
|
registry.setRunner('logger', () => ({ logger }));
|
||||||
|
}
|
||||||
|
|
||||||
if (registry.runners.has('rooms')) return;
|
if (registry.runners.has('rooms')) return;
|
||||||
const roomsInstance = new Rooms();
|
const roomsInstance = new Rooms();
|
||||||
registry.providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' });
|
registry.providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' });
|
||||||
@@ -469,6 +492,7 @@ const DEEP_GRAPH_WARN = 20;
|
|||||||
*/
|
*/
|
||||||
function finalizeGraph(
|
function finalizeGraph(
|
||||||
registry: Registry,
|
registry: Registry,
|
||||||
|
logger: Logger,
|
||||||
warnDepth: number | false = DEEP_GRAPH_WARN,
|
warnDepth: number | false = DEEP_GRAPH_WARN,
|
||||||
): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } {
|
): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } {
|
||||||
const { providerNodes, stepNodes, routePlans } = registry;
|
const { providerNodes, stepNodes, routePlans } = registry;
|
||||||
@@ -488,10 +512,11 @@ function finalizeGraph(
|
|||||||
const depth = closure.filter((node) => stepNodes.includes(node)).length;
|
const depth = closure.filter((node) => stepNodes.includes(node)).length;
|
||||||
|
|
||||||
if (warnDepth !== false && depth > warnDepth) {
|
if (warnDepth !== false && depth > warnDepth) {
|
||||||
console.warn(
|
logger.warn(
|
||||||
`[green-tea] ${plan.method} ${plan.pattern} resolves to ${depth} steps — an unusually deep dependency chain. ` +
|
`${plan.method} ${plan.pattern} resolves to ${depth} steps — an unusually deep dependency chain. ` +
|
||||||
`It runs fine (per-request cost is linear), but ${warnDepth}+ steps on one route usually means a step ` +
|
`It runs fine (per-request cost is linear), but ${warnDepth}+ steps on one route usually means a step ` +
|
||||||
`is doing too much or the graph wants splitting. If it's intentional, ignore this.`,
|
`is doing too much or the graph wants splitting. If it's intentional, ignore this.`,
|
||||||
|
{ route: plan.pattern, method: plan.method, depth, threshold: warnDepth },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -524,6 +549,7 @@ async function spliceRemoteScopes(
|
|||||||
mesh: MeshConfig,
|
mesh: MeshConfig,
|
||||||
bus: Bus,
|
bus: Bus,
|
||||||
registry: Registry,
|
registry: Registry,
|
||||||
|
logger: Logger,
|
||||||
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> {
|
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> {
|
||||||
const remoteRoutes: RouteDef[] = [];
|
const remoteRoutes: RouteDef[] = [];
|
||||||
const meshLinks: Link[] = [];
|
const meshLinks: Link[] = [];
|
||||||
@@ -584,8 +610,8 @@ async function spliceRemoteScopes(
|
|||||||
compilePattern(plan.pattern).shape === compilePattern(route.pattern).shape,
|
compilePattern(plan.pattern).shape === compilePattern(route.pattern).shape,
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
console.warn(
|
logger.warn(
|
||||||
`[green-tea] mesh: route '${display}' is exported by teapot ${teapot.url} but also declared locally — ` +
|
`mesh: route '${display}' is exported by teapot ${teapot.url} but also declared locally — ` +
|
||||||
'the local route takes precedence and the remote one will not be reached. ' +
|
'the local route takes precedence and the remote one will not be reached. ' +
|
||||||
'Remove one if that is not what you meant.',
|
'Remove one if that is not what you meant.',
|
||||||
);
|
);
|
||||||
@@ -630,9 +656,10 @@ async function bootProviders(
|
|||||||
container: Container;
|
container: Container;
|
||||||
providerMeta: Map<string, { optional: boolean }>;
|
providerMeta: Map<string, { optional: boolean }>;
|
||||||
bus: Bus;
|
bus: Bus;
|
||||||
|
logger: Logger;
|
||||||
},
|
},
|
||||||
): Promise<string[]> {
|
): Promise<string[]> {
|
||||||
const { runners, container, providerMeta, bus } = deps;
|
const { runners, container, providerMeta, bus, logger } = deps;
|
||||||
const degraded: string[] = [];
|
const degraded: string[] = [];
|
||||||
|
|
||||||
for (const node of orderedProviders) {
|
for (const node of orderedProviders) {
|
||||||
@@ -653,7 +680,10 @@ async function bootProviders(
|
|||||||
// optional: warn, leave it unregistered; routes needing it fail at request time
|
// optional: warn, leave it unregistered; routes needing it fail at request time
|
||||||
// ponytail: full partial-degradation is out of scope (spec §10); warn is enough here
|
// ponytail: full partial-degradation is out of scope (spec §10); warn is enough here
|
||||||
degraded.push(node.name);
|
degraded.push(node.name);
|
||||||
console.warn(`[green-tea] optional provider '${node.name}' failed: ${(error as Error).message}`);
|
logger.warn(`optional provider '${node.name}' failed: ${(error as Error).message}`, {
|
||||||
|
provider: node.name,
|
||||||
|
error,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -676,6 +706,7 @@ function makeAppBooter(
|
|||||||
container: Container;
|
container: Container;
|
||||||
providerMeta: Map<string, { optional: boolean }>;
|
providerMeta: Map<string, { optional: boolean }>;
|
||||||
bus: Bus;
|
bus: Bus;
|
||||||
|
logger: Logger;
|
||||||
},
|
},
|
||||||
degradedProviders: string[],
|
degradedProviders: string[],
|
||||||
/** Resolves the graph (splices remote mesh scopes, finalizes). Must precede providers: remote nodes join the topo sort. */
|
/** Resolves the graph (splices remote mesh scopes, finalizes). Must precede providers: remote nodes join the topo sort. */
|
||||||
@@ -688,8 +719,9 @@ function makeAppBooter(
|
|||||||
degradedProviders.push(...(await bootProviders(getOrderedProviders(), deps)));
|
degradedProviders.push(...(await bootProviders(getOrderedProviders(), deps)));
|
||||||
|
|
||||||
if (degradedProviders.length) {
|
if (degradedProviders.length) {
|
||||||
console.warn(
|
deps.logger.warn(
|
||||||
`[green-tea] started with ${degradedProviders.length} degraded optional provider(s): ${degradedProviders.join(', ')} — routes that need them will fail at request time.`,
|
`started with ${degradedProviders.length} degraded optional provider(s): ${degradedProviders.join(', ')} — routes that need them will fail at request time.`,
|
||||||
|
{ degraded: degradedProviders },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -968,6 +1000,7 @@ function closeApp(
|
|||||||
streams: Set<() => void>,
|
streams: Set<() => void>,
|
||||||
options: { timeoutMs?: number },
|
options: { timeoutMs?: number },
|
||||||
defaultTimeoutMs: number | undefined,
|
defaultTimeoutMs: number | undefined,
|
||||||
|
logger: Logger,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
// A mesh app booted through `app.fetch` has links but no server, and would leak every
|
// A mesh app booted through `app.fetch` has links but no server, and would leak every
|
||||||
@@ -980,10 +1013,10 @@ function closeApp(
|
|||||||
// `serveDeno`/`serveBun` return a server with the same bounded `close({ timeoutMs })`.
|
// `serveDeno`/`serveBun` return a server with the same bounded `close({ timeoutMs })`.
|
||||||
if (!server) {
|
if (!server) {
|
||||||
if (options.timeoutMs !== undefined) {
|
if (options.timeoutMs !== undefined) {
|
||||||
console.warn(
|
logger.warn(
|
||||||
'[green-tea] close({ timeoutMs }) has no effect here — this app has no listen()ed ' +
|
'close({ timeoutMs }) has no effect here — this app has no listen()ed server. On Deno ' +
|
||||||
'server. On Deno and Bun, call close() on the server serveDeno()/serveBun() returned; ' +
|
'and Bun, call close() on the server serveDeno()/serveBun() returned; it takes the ' +
|
||||||
'it takes the same option. On the edge the platform owns the lifecycle.',
|
'same option. On the edge the platform owns the lifecycle.',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1003,9 +1036,9 @@ function closeApp(
|
|||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
if (settled) return;
|
if (settled) return;
|
||||||
|
|
||||||
console.warn(
|
logger.warn(`graceful shutdown timed out after ${timeoutMs}ms — forcing remaining HTTP connections closed`, {
|
||||||
`[green-tea] graceful shutdown timed out after ${timeoutMs}ms — ` + 'forcing remaining HTTP connections closed',
|
timeoutMs,
|
||||||
);
|
});
|
||||||
|
|
||||||
// closeAllConnections() requires Node >=18.2, same floor as closeIdleConnections()
|
// closeAllConnections() requires Node >=18.2, same floor as closeIdleConnections()
|
||||||
// below — `engines` in package.json only guarantees >=18, so this matters.
|
// below — `engines` in package.json only guarantees >=18, so this matters.
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import type http from 'http';
|
import type http from 'http';
|
||||||
import type { Bus } from '../bus';
|
import type { Bus } from '../bus';
|
||||||
|
import type { Logger } from '../logger';
|
||||||
import type { GraphNode } from '../graph';
|
import type { GraphNode } from '../graph';
|
||||||
import type { GraphView } from '../graph-viz';
|
import type { GraphView } from '../graph-viz';
|
||||||
import type { HttpMethod, Transport } from '../metadata';
|
import type { HttpMethod, Transport } from '../metadata';
|
||||||
@@ -62,6 +63,12 @@ export interface App {
|
|||||||
/** Names of optional providers that failed to boot and are running degraded (empty until {@link App.listen}). */
|
/** Names of optional providers that failed to boot and are running degraded (empty until {@link App.listen}). */
|
||||||
degraded(): string[];
|
degraded(): string[];
|
||||||
bus: Bus;
|
bus: Bus;
|
||||||
|
/**
|
||||||
|
* Where framework diagnostics are written — the one passed to `createApp({ logger })`, or the
|
||||||
|
* default. Exposed so the Deno and Bun adapters report through the application's logger rather
|
||||||
|
* than reaching past it to `console`, and so a plugin or a test can read what core would write.
|
||||||
|
*/
|
||||||
|
logger: Logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Internal per-route plan: match criteria, its resolved provider/step closure, and the compiled handler. */
|
/** Internal per-route plan: match criteria, its resolved provider/step closure, and the compiled handler. */
|
||||||
|
|||||||
+4
-1
@@ -123,7 +123,10 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServeResu
|
|||||||
() => void server.stop(true),
|
() => void server.stop(true),
|
||||||
closeOptions.timeoutMs ?? 10_000,
|
closeOptions.timeoutMs ?? 10_000,
|
||||||
(ms) =>
|
(ms) =>
|
||||||
console.warn(`[green-tea] graceful shutdown timed out after ${ms}ms — forcing remaining connections closed`),
|
app.logger.warn(`graceful shutdown timed out after ${ms}ms — forcing remaining connections closed`, {
|
||||||
|
timeoutMs: ms,
|
||||||
|
runtime: 'bun',
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
+4
-4
@@ -90,10 +90,10 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoServer {
|
|||||||
() => {},
|
() => {},
|
||||||
closeOptions.timeoutMs ?? 10_000,
|
closeOptions.timeoutMs ?? 10_000,
|
||||||
(ms) =>
|
(ms) =>
|
||||||
console.warn(
|
app.logger.warn(
|
||||||
`[green-tea] graceful shutdown timed out after ${ms}ms — returning anyway. Deno cannot ` +
|
`graceful shutdown timed out after ${ms}ms — returning anyway. Deno cannot force-close ` +
|
||||||
'force-close a server that is already draining, so remaining connections end when the ' +
|
'a server that is already draining, so remaining connections end when the process does.',
|
||||||
'process does.',
|
{ timeoutMs: ms, runtime: 'deno' },
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ export {
|
|||||||
|
|
||||||
// Bus & flow
|
// Bus & flow
|
||||||
export { Bus } from './bus';
|
export { Bus } from './bus';
|
||||||
|
export type { LifecycleEvent, EventPayload, Correlation } from './bus';
|
||||||
export { flow, Flow } from './flow';
|
export { flow, Flow } from './flow';
|
||||||
export type { StepFn, CompiledFlow } from './flow';
|
export type { StepFn, CompiledFlow } from './flow';
|
||||||
|
|
||||||
@@ -65,6 +66,10 @@ export type { StepFn, CompiledFlow } from './flow';
|
|||||||
export { needs, ctx, param, query, body, headers, header, inbound, abort } from './params';
|
export { needs, ctx, param, query, body, headers, header, inbound, abort } from './params';
|
||||||
export type { Query, Headers, Context, ArgSpec, ArgDecorator } from './params';
|
export type { Query, Headers, Context, ArgSpec, ArgDecorator } from './params';
|
||||||
|
|
||||||
|
// Observability
|
||||||
|
export { createDefaultLogger } from './logger';
|
||||||
|
export type { Logger, LogLevel, LogFields } from './logger';
|
||||||
|
|
||||||
// Streaming
|
// Streaming
|
||||||
export { channel, isAsyncIterable } from './channel';
|
export { channel, isAsyncIterable } from './channel';
|
||||||
export type { Channel } from './channel';
|
export type { Channel } from './channel';
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
/**
|
||||||
|
* 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
|
||||||
|
* `trace`, no `fatal`, no `silent` — a level nothing emits is a decision handed to the user for
|
||||||
|
* no reason.
|
||||||
|
*/
|
||||||
|
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
|
||||||
|
|
||||||
|
/** Structured context attached to a log record. Flattened into the JSON output alongside the message. */
|
||||||
|
export type LogFields = Record<string, unknown>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What `createApp({ logger })` accepts, and what core writes every diagnostic through.
|
||||||
|
*
|
||||||
|
* Message first, fields second, so a call reads as a sentence and the structured part stays
|
||||||
|
* optional. Bridging a `pino`- or `winston`-style logger is a four-line adapter in either
|
||||||
|
* direction; core defines the shape it needs rather than adopting anyone's.
|
||||||
|
*/
|
||||||
|
export interface Logger {
|
||||||
|
debug(message: string, fields?: LogFields): void;
|
||||||
|
info(message: string, fields?: LogFields): void;
|
||||||
|
warn(message: string, fields?: LogFields): void;
|
||||||
|
error(message: string, fields?: LogFields): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether output should be human-readable rather than JSON.
|
||||||
|
*
|
||||||
|
* Decided once, when the logger is built, and never per call — the answer cannot change while the
|
||||||
|
* process runs, and asking on every record would put a syscall-shaped question on a path that is
|
||||||
|
* supposed to be cheap. `process` is absent on the edge, so the guard is not defensive padding:
|
||||||
|
* unattended is the correct default there, and JSON is the unattended format.
|
||||||
|
*/
|
||||||
|
function isInteractive(): boolean {
|
||||||
|
const proc = (globalThis as { process?: { stdout?: { isTTY?: boolean } } }).process;
|
||||||
|
return Boolean(proc?.stdout?.isTTY);
|
||||||
|
}
|
||||||
|
|
||||||
|
const CONSOLE_METHOD: Record<LogLevel, 'debug' | 'info' | 'warn' | 'error'> = {
|
||||||
|
debug: 'debug',
|
||||||
|
info: 'info',
|
||||||
|
warn: 'warn',
|
||||||
|
error: 'error',
|
||||||
|
};
|
||||||
|
|
||||||
|
function renderPretty(level: LogLevel, message: string, fields?: LogFields): string {
|
||||||
|
const pairs = fields
|
||||||
|
? Object.entries(fields)
|
||||||
|
.filter(([, value]) => value !== undefined)
|
||||||
|
.map(([key, value]) => `${key}=${typeof value === 'string' ? value : JSON.stringify(value)}`)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
return `[green-tea] ${level.toUpperCase()} ${message}${pairs.length ? ' ' + pairs.join(' ') : ''}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderJson(level: LogLevel, message: string, fields?: LogFields): string {
|
||||||
|
// `name` rather than the `[green-tea]` prefix the messages used to carry inline: a log
|
||||||
|
// aggregator filters on a field, and cannot filter on a substring of prose.
|
||||||
|
return JSON.stringify({ level, time: new Date().toISOString(), name: 'green-tea', msg: message, ...fields });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The logger used when `createApp` is given none: structured JSON, or human-readable on a TTY.
|
||||||
|
*
|
||||||
|
* Writes through `console`, which is the whole reason core can have a logging contract without a
|
||||||
|
* logging dependency — `reflect-metadata` stays the only runtime dependency, and anything richer
|
||||||
|
* (transports, sampling, rotation) is a `Logger` a user passes in.
|
||||||
|
*/
|
||||||
|
export function createDefaultLogger(pretty: boolean = isInteractive()): Logger {
|
||||||
|
const write = (level: LogLevel, message: string, fields?: LogFields): void => {
|
||||||
|
console[CONSOLE_METHOD[level]](pretty ? renderPretty(level, message, fields) : renderJson(level, message, fields));
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
debug: (message, fields) => write('debug', message, fields),
|
||||||
|
info: (message, fields) => write('info', message, fields),
|
||||||
|
warn: (message, fields) => write('warn', message, fields),
|
||||||
|
error: (message, fields) => write('error', message, fields),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||||
|
import { createApp, createDefaultLogger, 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('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' } });
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user