Log One JSON Line per Request

Your timer from Add a Request ID and a Timer prints a line such as POST /ask 200 1188 ms ac356251-... for every finished request. That’s readable for one request. For a season of hikers, though, you’ll want a program to answer questions about those lines: how many failed, which were slow, and what happened to the one a hiker complains about.

In this lesson, you’ll turn the timer’s line into JSON, log every server error under the same request ID, and count how many of the traffic simulator’s requests ended in a server error. Start with the line itself and what it should hold.

Write the Line as JSON

A person can read free text, but a program looking for every failed request would have to guess which word is the status. A structured log solves that by writing each line as one JSON object, with a name for every value. This format is called JSON Lines, which tools read one line at a time. Your traces, which record the steps within a request, will use it later in this course too.

Replace the "finish" callback in timer(), in middleware.js, so it builds an object and logs it with JSON.stringify():

Language: JavaScript Filename: middleware.js
export function timer(req, res, next) {
  const start = performance.now();
  res.on("finish", () => {
    const ms = Math.round(performance.now() - start);
    const line = {
      time: new Date().toISOString(),
      level: "info",
      method: req.method,
      route: req.route?.path ?? "(no route)",
      status: res.statusCode,
      durationMs: ms,
      requestId: res.locals.requestId,
    };
    console.log(JSON.stringify(line));
  });
  next();
}

Each field answers one question: when the request finished, what it asked for, how it went, how long it took, and which request it was. req.route?.path is the pattern of the route that answered, such as /ask, rather than the address the client typed.

Requests that no route answered, such as the page’s files and the 404 fallback, get the label "(no route)". The level field indicates the severity of the logged event: "info" here, "warn" and "error" in the next section.

The line still comes from the "finish" callback. When the request arrives, res.statusCode is 200, Node.js’s default, even for a request that ends in a 404, and there’s no duration yet.

Notice what the object leaves out. It’s an allow-list: only fields you named on purpose get logged. Logging req.headers and req.body “to have everything” would copy every Authorization and Cookie header into your logs, along with hikers’ questions and the names, phone numbers, and health details people type into them. Logs are kept for months and read by many people and tools, so any other field needs a reason before it goes in.

The address comes from the client too, so it can leak data as a body or a header can. Log req.path, and a request for /booking/RH-48213 copies a booking reference into your logs. A route’s pattern or a fixed label can’t copy one. The cost is that the log no longer shows which addresses scanners probe, so a team that needs them logs them with a reason.

Restart the server and request the health check from the last lesson with curl http://localhost:3000/health. The server’s terminal shows a line like this one, spread over several lines here:

Language: Text
{
  "time": "2026-12-02T01:45:10.379Z",
  "level": "info",
  "method": "GET",
  "route": "/health",
  "status": 200,
  "durationMs": 6,
  "requestId": "a04c136f-aade-4eae-be89-1233f0989b92"
}

The line goes to stdout, the standard output your terminal shows. On a real server, the platform running the app collects stdout, so the app never manages log files itself. Logging libraries such as Pino write lines like these with more options, but console.log() is enough here.

Which fields earn a place is a judgment call, so make one. Pick a field you’d add, such as the user agent, which identifies the client’s software, and write down the question it would answer. The button opens a chat with a question filled in. Replace the capitals with your field and its purpose:

Keep the field only if its values can’t carry personal data or secrets and you’ll actually ask the question it answers.

Log a Server Error Under the Same ID

When a route throws, its request line says 500 but not why, and Express 5’s built-in handler prints the stack as loose lines with no request ID.

So add an error handler of your own to middleware.js. This is a first look, only as much error handling as your logs need:

Language: JavaScript Filename: middleware.js
export function logErrors(err, req, res, next) {
  const requestId = res.locals.requestId;
  let status = err.status ?? err.statusCode;
  if (!(status >= 400 && status < 600)) status = 500;
  const line = {
    time: new Date().toISOString(),
    level: status >= 500 ? "error" : "warn",
    requestId,
    status,
    error: err.name,
  };
  if (status >= 500) line.stack = stackFrames(err);
  console.log(JSON.stringify(line));
  if (res.headersSent) return res.destroy();
  res.status(status).json({ error: "Request failed", requestId });
}

function stackFrames(err) {
  const lines = String(err.stack).split("\n");
  return lines.filter((l) => l.startsWith("    at "));
}

Express recognizes an error handler by its four parameters, with err first, and calls it only when a function registered above it throws, returns a rejected promise, or calls next() with an error. Its contract has two parts:

  • It records one line under the request ID with the status and the error’s name. The level is "error" for a server error or "warn" for a client error such as the 400 that express.json() sends for a malformed body.
  • It returns the status and the ID, never the stack, so a hiker can quote the ID. If the server has already sent a 200 status for a streamed answer, res.destroy() can only close the connection.

A server error’s line adds the at lines of the call stack, but not the message, which can quote the data that caused the error. In exchange, whoever investigates sees where a model call failed but can’t see why, such as a rate limit or a retired model. Traces record that later in the course, and that’s all you need about them for now.

Import logErrors in server.js and register it last, below the 404 fallback, so every route sits above it:

Language: JavaScript Filename: server.js
app.use((req, res) => res.status(404).json({ error: "Not found" }));
app.use(logErrors);

To see it work, add a route that fails on purpose, above the fallback:

Language: JavaScript Filename: server.js
app.get("/boom", () => {
  throw new Error("Test failure");
});

Restart the server with its output going through tee, or Tee-Object in PowerShell, which also writes each line to server.log:

Language: Windows PowerShell
PS> npm start | Tee-Object server.log
Language: Shell
$ npm start | tee server.log

Then request the new route in the second terminal:

Language: Shell
$ curl -i http://localhost:3000/boom
HTTP/1.1 500 Internal Server Error
X-Powered-By: Express
X-Request-Id: 2f565857-472e-4bbb-abf7-dc8f99178e58
...

{"error":"Request failed","requestId":"2f565857-472e-4bbb-abf7-dc8f99178e58"}

Say a hiker quotes that ID. Search for the ID from your own response with grep <your ID> server.log, or Select-String <your ID> server.log, and name the line that gives the route and status, and the frame that points to the failing code. Here’s the search above, with the stack shortened and each of its two lines spread over several:

Language: Shell
$ grep 2f565857 server.log
{
  "time": "2026-12-02T01:52:11.225Z",
  "level": "error",
  "requestId": "2f565857-472e-4bbb-abf7-dc8f99178e58",
  "status": 500,
  "error": "Error",
  "stack": ["    at file:///.../server.js:9:9", ...]
}
{
  "time": "2026-12-02T01:52:11.230Z",
  "level": "info",
  "method": "GET",
  "route": "/boom",
  "status": 500,
  "durationMs": 6,
  "requestId": "2f565857-472e-4bbb-abf7-dc8f99178e58"
}

Both lines describe one failed request: the request line gives the route, the 500, and the duration, and the error line’s first frame, server.js:9:9 here, points to the throw in /boom.

Delete the /boom route before you go on. Error handlers are new in this course, so if the path from a throwing route to these two lines isn’t clear yet, step through it with the mentor:

When you’re back, say why the error line comes before the request line. Question 3 at the end of this lesson asks it too, so you can confirm your answer there.

Count the Server Errors

With one JSON request line per completed request, a failure count is one short command away. Restart the server the same way, which starts a fresh server.log. In the second terminal, run npm run traffic -- --month=july for a few minutes, then press Ctrl+C in both terminals. Now count the request lines, then the error lines:

Language: Windows PowerShell
PS> (Select-String '"route":' server.log).Count
PS> (Select-String '"level":"error"' server.log).Count
Language: Shell
$ grep -c '"route":' server.log
$ grep -c '"level":"error"' server.log

The first number counts completed requests, since only request lines have a route field. The second counts every server error logErrors recorded. That includes answers that failed mid-stream, which leave no request line, so counting 5xx statuses in request lines would miss them.

Write the result as a rate by dividing error lines by request lines and expressing it as a percentage. The rate is approximate: mid-stream failures count among the error lines but have no request line. A short run may well show zero. That’s a real result, but a few hundred simulated requests can only show that failures are rare. Real traffic adds scanners, retries, and rate limits.

The count still misses some failures. As in Add a Request ID and a Timer, a hiker who closes the page mid-answer leaves no line, and a 200 answer can still be wrong. The traces later in this course account for those.

Check Your Understanding

Try these before you reveal the answers:

  1. Say you add console.log(res.statusCode); as the first line of timer(). What does it print for a request for a missing page?
  2. In a code review, you find console.log(JSON.stringify({ path: req.path, headers: req.headers, body: req.body })). What would it write for a hiker’s question, and what would you change?
  3. A hiker reports a 500 response with “Request failed” and quotes an ID. Which lines does searching server.log for it find, what does each one tell you, and why does the error line come first?
  1. It prints 200, Node.js’s default, because the 404 fallback hasn’t run yet, and there’s no duration to log. Logging in the "finish" callback gives the real status.
  2. It would write the hiker’s question, with any names or phone numbers in it, and every header, Authorization and Cookie included. Log an allow-list instead: method, route, status, duration, and request ID. Even req.path can carry a booking reference, so log the route’s pattern.
  3. The request line gives the method, route, 500 status, and duration. The error line under the same ID gives the status, the error’s name, and its stack frames, which point to the code that failed. The error line comes first because logErrors writes it before its response finishes, and the request line waits for "finish".

Every completed request now leaves one JSON line, and every server error its own line with its stack frames. In the next lesson, Exercise: Log Every Request, you’ll give a copy of the Ridgeline Huts server its own request log, then track down a hiker’s failed question in a day of recorded lines.

It’s the course’s first coding exercise. You edit the code in your browser, click Run Tests, and use the automated test feedback to fix it and rerun the tests. The exercise’s Contents tab explains the rest.

Become a Member to join the conversation.