You come across these two log lines. nginx writes "timestamp":"2026-10-12T04:16:07+01:00", notes-api writes "timestamp":"2026-10-12T03:16:07.402Z". Are these two events an hour apart, or one and the same request? Guess first. After the request_id section you can check it yourself.
Structured logging means every log line is one JSON object whose field names every service agrees on. Then logs from nginx, notes-api and any other service can be searched, joined and counted like a table. Picture a passport office. Applicants pass several desks: the document check, the photo, then the interview. If every officer writes free sentences in their own notebook, the question "how many applicants waited more than an hour at the photo desk today?" takes all day to answer. It is different if every officer fills in the same form (name, arrival time, desk, waiting time). All the forms of one applicant also carry the same queue number, from the entrance to the last desk. Then that question takes a minute, and one applicant's path can be followed from desk to desk. Here one applicant is one request, and each desk is one service (nginx, notes-api). The form is your log schema (the list of agreed fields), and the queue number is request_id.
In the Application Logging lesson, notes-api already wrote JSON to stdout. Now nginx in front of it writes JSON too, and we start asking the logs questions the way we ask a database.
One schema for every service
Compare two ways of recording a failed login:
console.log("User 123 failed login from 192.168.1.1");
logger.warn("login failed", { user_id: 123, ip: "192.168.1.1" });
The first line is only a sentence. To get 123 out of it, you have to guess its position in the text. The second keeps every piece of information in a separate field, so it can be queried and filtered, for example "every login failed from this ip". These three things are not its advantages: the warn level does not send a notification by itself, the line is even a little bigger, and nothing in it is encrypted. Its one advantage is the one that matters: the data can be asked questions.
As soon as there is more than one service, the fields must have the same name and the same meaning. In the Application Logging lesson, notes-api wrote reqId and time. If nginx writes request_id and another service writes requestId, no single query will ever find all three. So the notes-api team agrees on five core fields on every line:
| Field | Holds | Example |
|---|---|---|
timestamp |
ISO 8601 time with a time zone | 2026-10-12T03:15:02.114Z |
level |
info, warn, error |
info |
service |
who wrote it | notes-api, nginx |
request_id |
the request's number (next section) | 5cba9e2c945971c5e3fb8c7b70a6c075 |
msg |
a fixed sentence, never pieced together | request completed |
notes-api adds user_id (null before login), then per-event fields: method, route, status, duration_ms. nginx writes path (the raw URL path, exactly as it was requested, such as /notes/91) and request_time (in seconds). Extra fields may differ between services, as long as each name matches what the field holds. route in notes-api holds the pattern /notes/:id, so its name is kept different from nginx's raw path.
Levels carry the same meaning too. Take request 2cfc8f60 in the Lab (the Lab shows the first 8 characters of request_id). Its first database query was slow (2,000 ms), so it was retried (tried again) once, and then it succeeded. That is warn, not error: nothing failed yet, but the pattern deserves watching before it becomes a real error. error is for an operation that failed (a 500), info for normal events.
request_id: one number from nginx to notes-api
One request passes through several places, and each writes its own log. To collect all those logs, the same number travels in a header to every service. It is called a correlation ID or request ID. nginx makes it, because nginx receives the request first. This is the nginx config:
map $status $log_level {
~^5 error;
~^4 warn;
default info;
}
log_format json_log escape=json '{"timestamp":"$time_iso8601","level":"$log_level",'
'"service":"nginx","request_id":"$request_id","msg":"access",'
'"method":"$request_method","path":"$uri","status":$status,"request_time":$request_time}';
server {
server_name notes.example.com;
access_log /var/log/nginx/notes.access.log json_log;
location / {
proxy_set_header X-Request-Id $request_id;
proxy_pass http://127.0.0.1:3000;
}
}
log_format json_logbuilds one JSON line from nginx variables, such as$time_iso8601(the time) and$status.$request_idis 32 random hex characters (the digits 0 to 9 and the letters a to f) that nginx makes for every request.proxy_set_header X-Request-Idpasses that number on to notes-api as a header.mapturns the status into a level: 5xxerror, 4xxwarn, the restinfo.escape=jsonkeeps a value that contains quotes valid JSON.
In notes-api, the first middleware (a function that runs before the routes) reads that header. When a request arrives without passing through nginx, the middleware makes a new number. Then it creates a child logger: a logger that adds request_id to every line by itself.
const crypto = require("node:crypto");
const logger = require("./logger");
app.use((req, res, next) => {
req.requestId = req.get("x-request-id") || crypto.randomUUID().replaceAll("-", "");
req.log = logger.child({ request_id: req.requestId, user_id: null });
res.set("X-Request-Id", req.requestId); // a user can quote this number in a report
next();
});
// once the token is checked: req.log = req.log.child({ user_id: user.id });
// calling another service: fetch(url, { headers: { "X-Request-Id": req.requestId } });
Now the two lines from the start of the lesson can be checked. Both carry request_id e6ccb0bf4c98f527e3af585fbce90221, so they are one and the same request. 04:16:07+01:00 (London time, the time zone of the web-1 server) and 03:16:07.402Z (UTC, the container's time zone) are the same second. nginx only records whole seconds, notes-api records milliseconds. So remember two things: match lines by request_id, and sort times with Date.parse (a JavaScript function that turns a time written as text into a number), never as text.
Querying logs for real
The Lab holds 21 lines from Monday, 12 October 2026, 04:15 to 04:16 London time: 8 requests, 10 info lines, 5 warn and 6 error. Sari reports that her note failed to save. Since every line is JSON, the logs can be processed with plain JavaScript:
const logs = lines.map((line) => JSON.parse(line));
// 1. Every line of Sari's request, in time order
const requestSari = logs
.filter((log) => log.request_id === "e6ccb0bf4c98f527e3af585fbce90221")
.sort((a, b) => Date.parse(a.timestamp) - Date.parse(b.timestamp));
// 2. Requests and 5xx errors per route, from notes-api's summary lines
const perRoute = {};
for (const log of logs) {
if (log.service !== "notes-api" || log.status === undefined) continue;
const key = log.method + " " + log.route;
if (!perRoute[key]) perRoute[key] = { requests: 0, errors5xx: 0, slowest: 0 };
perRoute[key].requests++;
if (log.status >= 500) perRoute[key].errors5xx++;
perRoute[key].slowest = Math.max(perRoute[key].slowest, log.duration_ms);
}
The first query returns 4 lines that tell a story, in this order:
db pool exhausted: 10 of 10 connections in use.- nginx's
accessline with status 500. db query failedwith the errortimeout exceeded when trying to connect.request completedwith status 500 after 5,004 ms.
The second query gives this table (sorted by most errors):
| Route | Requests | 5xx errors | Slowest |
|---|---|---|---|
POST /notes |
3 | 2 | 5,004 ms |
GET /notes |
2 | 0 | 2,140 ms |
POST /auth/login |
1 | 0 | 9 ms |
GET /notes/popular |
1 | 0 | 4 ms |
GET /notes/:id |
1 | 0 | 12 ms |
linesholds the 21 text lines from the Lab, andJSON.parseturns every line into an object you can read field by field.continueskips nginx's lines and lines without astatus. Only notes-api's request summary lines are counted.- The group key uses
route(the pattern), not the raw path. With the path,/notes/91and/notes/92would become two different rows. if (!perRoute[key])creates a group's starting values only once, when that route first appears.
In Loki (the central place for logs), a similar query is written in LogQL, Loki's own query language. For example, every notes-api line with status 500 or above: {service="notes-api"} | json | status >= 500. The idea is the same: turn the JSON text into fields, then filter by field.
Sampling: keep a share, never drop errors
1,000 requests a minute means 1.44 million requests a day, about 3.7 million log lines, roughly 940 MB a day. Most of it is info lines from successful requests that look alike. Sampling means storing only part of the lines. Two rules:
function bucket(id) {
let hash = 0;
for (const char of id) hash = (hash * 31 + char.charCodeAt(0)) % 100;
return hash;
}
function keep(log, infoPercent) {
if (log.level === "warn" || log.level === "error") return true; // never dropped
return bucket(log.request_id) < infoPercent;
}
warnanderrorare always kept. They are exactly the lines you look for when something breaks.- The decision for
infocomes fromrequest_id, not from a draw per line.bucketis the same hash as the bucket in the Feature Flags & Gradual Rollouts lesson: the same id always gets the same number (0 to 99). Aninfoline is kept when that number is underinfoPercent. So a request that is picked is stored whole, from nginx to notes-api.
In the Lab, sampling info at 10% keeps 13 of 21 lines: all 11 warn and error lines, plus the 2 lines of request ff715f1a (bucket 8, under 10). On real traffic, 97% of the lines are info, so about 13% remains, roughly 120 MB a day. The rule can run in the logger, or in the shipper (the program that sends logs) before logs are sent. Vector, for example, has a sample transform (a processing step) with a key_field to pick per request_id.
Redact PII before the line is written
PII (personally identifiable information) is data that points to a specific person: name, email, phone number, address, national ID number, IP address. Its handling is governed by a data protection law such as the GDPR. Logs are copied to many places: disk, Loki, backups. So PII must be cleaned in the logger, before the line is written. This cleaning is called redaction (to redact): removing or masking the data. Masking it in a dashboard is already too late.
The login failed line in the Lab comes from req.log.warn("login failed", req.body): Dewi's email and password were printed with it. notes-api's logger cleans it with this function:
function redact(fields) {
const out = { ...fields };
if ("password" in out) out.password = "[Redacted]";
if (typeof out.email === "string") {
const [name, domain] = out.email.split("@");
out.email = name[0] + "***@" + domain; // [email protected] becomes d***@example.com
}
return out;
}
There are three ways, safest first:
- drop it: passwords, tokens, the
Authorizationheader. They are never needed in a log. - mask it: an email written as
d***@example.comis enough to debug. - replace it with an id:
user_id: 7instead of the email. Someone with access can match the id in the database.
Safer still: never log req.body whole. Name the fields that may go in.
⚠️ Four ways tidy logs stop being trustworthy
- Field names that differ between services.
reqIdin one service,request_idin another: your query quietly misses half the logs. Agree on a schema, and write it in the team's README. - Sorting times as text.
04:16:07+01:00and03:16:07.402Zare the same second. Sort withDate.parse, or make everything UTC. - Sampling drawn per line. Requests end up with holes: nginx's line kept, notes-api's lines gone. Decide per
request_id, and never dropwarnanderror. - Redacting in the dashboard. The password already sits on disk and in backups. Redact in the logger, before the line is written.
TL;DR: Structured logging = one JSON object per log line, with a schema every service agrees on. The schema is a list of fields (name and value pairs). The core fields are timestamp (ISO 8601 with a time zone), level, service, request_id and a fixed msg. Then come event fields like user_id, route, status, duration_ms. Separate fields make logs queryable and filterable. A retry (a second try) that finally succeeded is warn, a 500 is error. nginx makes $request_id (a random number for every request) and passes it on in the X-Request-Id header. notes-api adds it to every line through a child logger (a logger that adds that field by itself). So one filter collects every line of one request from every service. The query can be plain JavaScript (filter, grouping by route) or LogQL (the query language of Loki, the central place for logs). Sampling (storing only part of the lines): info lines are kept or dropped per request_id, and every warn and error is kept. Redact PII (data that points to a specific person) in the logger: drop passwords and tokens, mask emails, use user_id.
⚡ Separate fields, not sentences
Write:
console.log("User 123 failed login from 192.168.1.1");
logger.warn("login failed", { user_id: 123, ip: "192.168.1.1" });
Guess first: both lines record a failed login. What makes the second line more useful?
Its data sits in separate fields, so it can be queried and filtered: "every login failed from this ip". The warn level doesn't send a notification by itself, and nothing in it is encrypted.
Meaning: Structured logging means every log line is one JSON object with separate fields (name and value pairs). The core fields carry the same name and meaning in every service: timestamp, level, service, request_id, msg.
⚡ One request_id from nginx to the API
Write:
req.requestId = req.get("x-request-id") || crypto.randomUUID().replaceAll("-", "");
req.log = logger.child({ request_id: req.requestId, user_id: null });
Guess first: 04:16:07+01:00 from nginx and 03:16:07.402Z from the API, with the same request_id (request number). An hour apart?
No. That is the same second in two time zones: London time (BST) and UTC. Match lines by request_id, and sort times with Date.parse (it turns a time written as text into a number), not as text.
Meaning: nginx makes a request_id for every request, then sends it to notes-api in the X-Request-Id header. This code reads that header, or makes a new number when the header is missing. logger.child(...) creates a child logger: a logger that adds request_id to every line by itself. So one request_id filter collects every line of one request.
⚡ Sampling without dropping errors
Meaning: Sampling means storing only part of the log lines. Keep every warn and error. For info, decide per request_id, not per line, so a request that is picked is stored whole. Sampled per line, a request ends up with holes: the nginx line is kept while its API line is gone.