APIs with Express · Chapter 20 of 29

Logging

By the end of this chapter you can write one structured log line per request, find any request by its id, and keep secrets out of your logs. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Production
  • 5 tasks
  • Express
  • In the all labs plan

The first 2 chapters of APIs with Express are free. This one comes with the all labs plan.

Why you need this

Kulhad Corner says an order failed at 4:17 pm yesterday. Ravi finds a wall of console.log lines: sentences, whole request objects, and one partner's API key in plain text. Kabir wants logs usable at 4 pm under pressure: one line per request, the same fields every time, and nothing in them you would not paste into a public chat.

Chapter 6's log line was a sentence. You cannot ask a sentence for "every 500 after 4 pm", you cannot tell which line was the café's request, and whatever you print, secrets included, stays for months.

What you build: 5 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    logger: one JSON line per request

    Export logger({ now, write, skip }), which returns a middleware; the options may be left out, with now defaulting to Date.now and write to console.log. Once per request, after the response has been sent, it calls write exactly once with one string: JSON.stringify of an object holding at least

    time: the time the request arrived (now() then), as an ISO string such as '2026-10-04T16:17:00.000Z';

    method, such as 'GET';

    path: the URL as the client sent it, query string and router prefix included ('/menu?page=2', and '/api/orders' for a route in a router mounted at /api);

    status: the status code, as a number;

    ms: now() when the response has been sent minus now() when the request arrived (42 when the route takes 42 ms on the check's clock).

    Express's own 404 answers are logged too ({ path: '/nope', status: 404 }). Later tasks add more fields to the same line.

  2. Task 2

    requestId: reuse a safe id, or make a new one

    Export requestId({ newId }), which returns a middleware (newId defaults to randomUUID). It puts an id on req.id, sends it back in the X-Request-Id response header, and passes the request on.

    When the request has an X-Request-Id of 1 to 64 characters, all of them letters, digits, _ or -, that id is reused ('lb-7f3a_09', or 64 b's) and newId is not called. Anything else, a missing header, 'abc"}{"status":200' or 65 characters, gets newId() instead.

    The logger's line gets an id field: req.id, or null when no requestId ran before the logger.

  3. Task 3

    redactHeaders: no keys, tokens or cookies in the logs

    Export redactHeaders(headers), which returns a copy of a headers object (lowercase names, as in req.headers) in which authorization, cookie and x-api-key say '[REDACTED]' when they are present. A header that was not sent stays absent ({ accept: 'text/html' } comes back equal), every other header keeps its value, and the object you were given does not change.

    The logger's line gets a headers field: redactHeaders(req.headers). None of the secret values appears anywhere in the line, and the route that runs after the logger still sees the real Authorization and X-Api-Key.

  4. Task 4

    logger: a level from the status, and the error message

    The logger's line gets a level field from the status: 'info' below 400 (200, and 301 too), 'warn' from 400 to 499, and 'error' from 500 up (503 included).

    An error handler may put the error's message in res.locals.error before it answers. When it is there, the line gets an error field with that message ('Milk supplier API timed out'); otherwise the line has no error field at all, not even null.

  5. Task 5

    createApp: log every request except /health

    In createApp({ now, write, newId }), register requestId with newId and then logger with now and write, both before the routes, so every request gets an id and the log line sees it. GET /health still gets an id, but is not logged: the logger takes a skip(req) option, and a request for which it returns true is not logged.

    The error handler puts err.message in res.locals.error and answers 500 with { error: 'Something went wrong' }.

    After GET /menu, three GET /health and GET /boom, exactly two lines are written. The /menu line has level 'info', status 200 and x-api-key '[REDACTED]' in its headers. The /boom line has level 'error', status 500, error 'Kitchen printer on fire' and id 'req-5' (the health checks took ids 2 to 4).

What you will learn

  • JSON log lines: one object per request, written when the answer has gone out.
  • Request ids: one id per request, in the response and in the log, and when to trust an id that arrives with the request.
  • Redaction: secrets replaced in a copy of the headers.
  • Levels and res.locals: info, warn and error, and the real error message from the error handler.

More in Production

Build "Logging" yourself

Partner cafés want Tapri’s menu online by Friday: you build its API. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of APIs with Express are free. This one comes with the all labs plan.