Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Log Each Request as One JSON Line

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 with JSON.stringify() and console.log() on standard output. The startup message goes through log() 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, warn and error. A finish line’s level comes from its status: 500 and above is error, 400 and above is warn, and everything else is info.
  • LOG_LEVEL is a setting in the config schema, a Zod enum (z.enum()) of the four levels with a default of info, listed in .env and .env.example as LOG_LEVEL=info. A typo such as verbose stops the server at startup. In log(), 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 an info line. A value set in front of the command wins over .env for that run only. At error, only a status of 500 or above prints. Nothing logs at debug yet: 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 --silent flag turns off npm’s own lines, which aren’t JSON.

Here’s log.ts:

Language: TypeScript Filename: 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));
}

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

00:00 Your walks API already prints one line for every request. The timing middleware writes it: the request’s id, the method, the path, the status, and how long it took.

00:13 Say Priya asks how often her page asked for a missing walk. You need every 404. A program reading these lines has to count words, and the status is the fourth until the day you add a field.

00:28 So write each line as one JSON object instead, with a name on every value. Now a tool can ask for the status by name. One JSON object per line is a structured log.

00:42 Every line goes through one small function, log(), in a new file. It takes a level and an object of fields. A level, such as info or warn, says how much the line matters.

00:56 The function puts the time and the level first, then spreads in the fields. JSON.stringify() turns that object into one line, and console.log() prints it on standard output.

01:09 The server file imports log() for its startup message too, so everything on standard output is JSON.

01:17 Now follow the request for walk 9. addRequestId gives it an id on arrival. The timing middleware notes the start time and passes the request on. The handler finds no walk 9, and the error handler answers with 404.

01:35 Then the response finishes. Only now are the status and the duration final. Read on arrival, this status would still say 200. The level comes from the status: 500 and above is error, 400 and above is warn, and everything else is info.

01:53 So this 404 is a warn line. The finish callback hands the level and the fields to log(), which prints one JSON line.

02:03 How many lines you want depends on the machine. On your laptop, every request helps. On the co-op’s server, you want only the problems. So the minimum level is a setting.

02:16 Add LOG_LEVEL to the config schema as a Zod enum of the four levels. From low to high, they’re debug, info, warn, and error. Info is the default, and .env and .env.example list it.

02:31 A typo such as verbose stops the server at startup. log.ts imports the config, and each level gets a rank, from 0 for debug to 3 for error. A line ranked below the configured level returns early and never prints.

02:50 Here are the morning’s four requests. Your turn: picture the server started with LOG_LEVEL set to warn on the command line, which wins over .env.

03:00 Pause the video and predict which lines still print.

03:09 Only the 404 and the 422.

03:12 They’re warn lines. The two 200s are info, which ranks below warn. The startup message is info too, so the server starts without a word. At error, none of these print.

03:25 Only a 500 would. Nothing logs at debug yet. It’s for chasing a problem.

03:32 Without that setting, the server reads info from .env again. Now Priya’s question has a quick answer. jq, linked below the video, is a command-line program that reads JSON and filters it.

03:45 Pipe the server’s output into it, and its select filter keeps only the 404 lines. The silent flag turns off npm’s own lines, which aren’t JSON. Two missing walks give two lines, nothing else.

04:02 Write each request’s line when the response finishes, as one JSON object, with a level that comes from its status. A request the client abandons, say the tab closes mid-request, never finishes, so it gets no line.

04:17 One thing is still free text. When a booking fails with a 500, its finish line says error. Above it, the error handler prints the error as plain text on standard error, where jq never sees it.

04:30 In the next lesson, Log Errors Without Leaking Secrets, you’ll turn that into a JSON line too, and decide what must never reach the log.

Become a Member to join the conversation.