Structured Logging — Debugging

Structured logging writes every log (a record of an event in the app) as one line of JSON with fixed fields (columns of data): level (how important it is)…

It's two in the morning, and payments are failing for some users. The logs (the records of events that the app writes) are there, thousands of lines of free sentences: "Login failed for user 42", "payment error again", "got here". Finding every log about a single user takes half an hour.

Structured logging prevents that problem. Every log is written as an object with fixed columns, usually one line of JSON, not a free sentence. Picture an office guest book. If every guest writes a free sentence ("I'm Budi, came at 10 to see HR"), finding every guest who saw HR today means reading them all one by one. If the book is a form with columns for name, time and purpose, you just filter the purpose column. A structured log is like that form: every log has the same columns, and those columns are called fields.

From a sentence to JSON

This is the same log, written in two ways:

// A free sentence: hard to search, hard to count
console.log("Login failed for user 42, attempt 3");

// Structured: one line of JSON with fixed fields
// {"level":"warn","timestamp":"2024-01-01T10:30:00.000Z","context":"auth","message":"Login failed","userId":42,"attempt":3}

In production, logs from many servers are collected in a log management tool, a service that stores logs and searches them. Examples are the ELK Stack (Elasticsearch, Logstash, Kibana), Grafana Loki and Datadog. Since every log is JSON, you can search by field, for example level:error AND context:payment (every error from the payment part). You can also count how many times "Login failed" happened for userId 42 this week. With free sentences, all you can do is search for bits of text.

Building a logger

A logger is an object that puts logs together in the same format every time. This is the version in the exercise. Its timestamp is fixed ("2024-01-01") so the output is always the same and can be checked. In a real app, use new Date().toISOString().

function createLogger(context) {
  function write(level, message, meta) {
    const entry = {
      level,
      timestamp: "2024-01-01",
      context,
      message,
      ...meta, // extra fields from the caller
    };
    console.log(JSON.stringify(entry)); // one line of JSON
  }

  return {
    info: (message, meta) => write("info", message, meta),
    warn: (message, meta) => write("warn", message, meta),
    error: (message, meta) => write("error", message, meta),
  };
}

const logger = createLogger("auth");
logger.info("User login", { userId: 42 });
// {"level":"info","timestamp":"2024-01-01","context":"auth","message":"User login","userId":42}

Log levels and how to filter them

A level is how important a log is. These are the five common levels:

Level When to use it Example
trace the most detailed trail, hardly ever turned on entering and leaving every function
debug details for finding a bug, usually only in development "checking password"
info normal events that matter "User login", "server start"
warn not normal, but the app still runs "high memory", "Retry attempt"
error something failed and needs handling "db connection failed"

The order from most critical to most verbose (writing the most logs) is: error, warn, info, debug, trace. Some libraries add fatal above error for failures that stop the app.

Filtering with a minimum level means letting that level and everything more critical through. To do that, give each level a number. The more critical the level, the bigger its number. The exercise uses only three levels:

const LOG_LEVELS = { info: 1, warn: 2, error: 3 };

function filterLogs(logs, level) {
  const minimum = LOG_LEVELS[level];
  return logs.filter((log) => LOG_LEVELS[log.level] >= minimum);
}
Log LOG_LEVELS[log.level] >= 2 (warn)?
info "server start" 1 filtered out
warn "high memory" 2 gets through
error "db connection failed" 3 gets through

With a minimum of warn, 2 logs get through, and the first log that gets through is warn. In the exercise, that 2 and that warn are the last two lines of the output. In production, the minimum is usually info or warn. During development (while the code is still being written and tried), it's usually debug.

Correlation ID: one request, many services

One click on "Pay" can pass through several services: the API gateway, auth, then payment. A service is a separate program that handles one part of the app, and the API gateway is the entrance that forwards requests to the other services. Each service writes its own logs. So that one request can be followed from start to finish:

  1. The first service creates a unique ID for that request. This ID is called a correlation ID, and it is often named requestId or trace ID.
  2. The ID is passed to the next service in an HTTP header.
  3. Every log includes the ID:
{"level":"info","context":"gateway","message":"request received","requestId":"req-103","path":"/pay"}
{"level":"warn","context":"payment","message":"Retry attempt","requestId":"req-103","attempt":2}
{"level":"error","context":"payment","message":"Payment failed","requestId":"req-103","reason":"gateway_timeout"}

Search for requestId:"req-103", and the whole journey of that request appears in order, even though its logs came from different services.

💡 Use a library in a real app

In Node.js, libraries such as pino and winston already write JSON, handle the minimum level and add the timestamp. pino, for example, writes a line like {"level":30,"time":...,"msg":"User login"} (shortened): the level is a number (30 for info), and the message is in the msg field. The idea is the same as your own logger.

⚠️ Writing and filtering logs wrong

TL;DR: Structured logging writes every log (a record of an event in the app) as one line of JSON with fixed fields (columns of data): level (how important it is), timestamp, context, message, plus extra fields such as userId. That way, logs can be filtered and counted per field in tools like ELK, Loki or Datadog. Build a logger (an object that puts logs together in the same format) with createLogger(context), which returns the methods info, warn and error. Each method prints JSON.stringify({ level, timestamp, context, message, ...meta }). Levels from most critical: error, warn, info, debug, trace. To filter with a minimum level, give each level a number in LOG_LEVELS (the more critical, the bigger), then let a log through when LOG_LEVELS[log.level] >= LOG_LEVELS[level]. So a minimum of warn lets warn and error through. Put the same correlation ID (a unique ID for one request) in every log of that request, so its journey can be followed across services (separate programs). Never log passwords or tokens.

⚡ From a sentence to JSON

Write:

const logger = createLogger("auth");
logger.info("User login", { userId: 42 });
// {"level":"info","timestamp":"2024-01-01","context":"auth","message":"User login","userId":42}

Meaning: createLogger("auth") makes a logger (an object that writes logs) for the auth part, and logger.info writes one log at the info level. Structured logging writes every log as one line of JSON with fields (columns of data) that are the same in every log: level (how important it is), timestamp (when), context (which part of the app), message, plus extra fields such as userId. Logs can then be filtered and counted per field, for example level:error AND context:payment.

⚡ Levels, most critical first

Meaning: A level is how important a log is. From most critical to most verbose (writing the most logs): error, warn, info, debug, trace. Don't log everything as error: when every log is an error, the errors that really matter get lost.

⚡ Filter with a minimum level

Write:

const LOG_LEVELS = { info: 1, warn: 2, error: 3 };

function filterLogs(logs, level) {
  const minimum = LOG_LEVELS[level];
  return logs.filter((log) => LOG_LEVELS[log.level] >= minimum);
}
Guess first: filterLogs(logs, "warn"). Does an error log get through?

Yes. A minimum of warn lets warn and everything more critical through. That's why the code uses >=, not ===.

Meaning: Each level gets a number (info 1, warn 2, error 3). Logs whose number is the same as the minimum's number or higher get through.

⚡ One request, one correlation ID

Meaning: One click sends one request, and that request can pass through several services (separate programs that each handle one part of the app). Put the same ID for that request, such as requestId, in every one of its logs. This ID is called a correlation ID. Then search for that ID, for example requestId:"req-103", to see its whole journey. And never log passwords or tokens.

What you will learn