The walks API’s timing middleware used to print one free-text line per request. A person can read that line, but a program has to count words to find the status, and that breaks the day you add a field. Now each request’s line is one JSON object, so a tool can ask for a field by name.
Key points:
- The line is still written on
res.on("finish"), because only then is the status final and the duration measurable. Read on arrival, a request that ends in a 404 still shows the default status, 200. A request the client abandons before the response finishes (say the tab closes mid-request) never fires"finish", so it gets no line. - One JSON object per line is a structured log. Every line goes through one small
log()function. It puts the time and the level first, spreads in the fields, and prints the object withJSON.stringify()andconsole.log()on standard output. The startup message goes throughlog()too, so everything on standard output is JSON. - A level says how much a line matters. From low to high, the four levels are
debug,info,warnanderror. A finish line’s level comes from its status: 500 and above iserror, 400 and above iswarn, and everything else isinfo. LOG_LEVELis a setting in the config schema, a Zod enum (z.enum()) of the four levels with a default ofinfo, listed in.envand.env.exampleasLOG_LEVEL=info. A typo such asverbosestops the server at startup. Inlog(), a line ranked below the configured level returns early and never prints.- Started with
LOG_LEVEL=warn npm start, the server drops the 200s and keeps the 404 and 422 lines, and the startup message goes too, because it’s aninfoline. A value set in front of the command wins over.envfor that run only. Aterror, only a status of 500 or above prints. Nothing logs atdebugyet: that level is for extra detail while you chase a problem. - jq is a command-line program that reads JSON and filters it. Its
select()filter keeps only the lines whose status is 404. The--silentflag turns off npm’s own lines, which aren’t JSON.
Here’s log.ts:
log.ts
import { config } from "./config.ts";
type Level = "debug" | "info" | "warn" | "error";
const rank = { debug: 0, info: 1, warn: 2, error: 3 };
export function log(level: Level, fields: Record<string, unknown>) {
if (rank[level] < rank[config.logLevel]) {
return;
}
const line = { time: new Date().toISOString(), level, ...fields };
console.log(JSON.stringify(line));
}