Application Logging — DevOps

A good log (the record of events an app writes) is one JSON line per event. Each line has time (in the international date format ISO 8601, in UTC, the world's…

That morning, around 11:42 London time, a few users report that their notes won't load. By the time you check, everything is normal again. You can't make it happen again, so all you have is whatever notes-api managed to write about those minutes.

That writing is the log: the record an application writes as it runs, one line per event. Each line holds when it happened, how important it is, what happened, and its context. Picture the shift report book in a convenience store. Every event is written down with the time, an importance mark (routine, attention, urgent) and the details. A busy manager only reads the urgent ones. When money is missing from the cash register at three in the afternoon, they read everything around that hour. Here the report book is the log, each entry is one log line, and the importance mark is the level (covered below). Reading logs on a server works the same way as that manager: filter by importance, then by time.

notes-api now runs as a container on web-1 (the Docker Compose and What is CI/CD lessons). Back when it ran directly under systemd, its log went to storage/logs/app.log, and you read it with tail and grep (the Command Line Essentials lesson). In this lesson we make the log tidy: every line is JSON, has a level, and goes to stdout (a program's standard output, where console.log prints).

One log line, four parts

This is the line notes-api writes after a request finishes:

{"time":"2026-10-09T10:41:02.114Z","level":"info","msg":"request completed","reqId":"r-101","method":"GET","path":"/notes","status":200,"ms":38,"userId":42}

Logs like this are called structured logging: every line has a structured format (JSON) you can query field by field, for example "every line with status 500 and path /notes". Compare it with plain text User 42 GET /notes 200 38ms: to get the 38, you have to guess where it sits. At minimum, every line has a timestamp (the time, here time), a level, a message (here msg) and context (request ID, user ID).

Levels: how important

Level Used for Example in notes-api
debug detail for developers looking for a bug the SQL query, a cache hit
info normal events you want to count request finished, user logged in
warn nothing failed yet, but a warning sign an 870 ms query, the connection pool at 9 of 10
error one operation failed, the app still runs database connection timeout, a 500 request
fatal the app cannot go on, the process stops DATABASE_URL empty at startup

Guess first. The Lab holds 16 notes-api log lines: 3 debug, 7 info, 3 warn, 3 error. If you set the level filter to warn, how many lines show, 3 or 6?

The order is debug < info < warn < error < fatal. A logger (the part of the app that writes the log) gets a minimum level, usually from the LOG_LEVEL environment variable. Lines below the minimum are dropped right away; the rest are printed. A warn filter means warn and everything more important, so 3 warn + 3 error = 6 lines. Production usually runs at info, a laptop at debug.

Some systems have eight levels, for example syslog (the log standard on Linux) and Monolog (a PHP log library, which Laravel uses): debug, info, notice, warning, error, critical, alert, emergency. The last three mark serious failures that need handling right away, such as the main database going down or the whole app being down.

A small logger with a minimum level

This is a small logger that applies that minimum level:

const LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };

function createLogger(minLevel) {
  function log(level, message, data) {
    if (LEVELS[level] < LEVELS[minLevel]) return null; // below the minimum: dropped
    const entry = { level, message, data, timestamp: new Date().toISOString() };
    console.log(JSON.stringify(entry)); // one JSON line to stdout
    return entry;
  }

  return {
    debug: (message, data) => log("debug", message, data),
    info: (message, data) => log("info", message, data),
    warn: (message, data) => log("warn", message, data),
    error: (message, data) => log("error", message, data),
  };
}

This table shows four calls and their results:

Call Comparison Result
createLogger("info").info("test", { a: 1 }) 1 < 1? no the object { level: "info", message: "test", data: { a: 1 }, timestamp }
createLogger("info").debug("query", {}) 0 < 1? yes null
createLogger("warn").info("test", {}) 1 < 2? yes null
createLogger("error").warn("warning", {}) 2 < 3? yes null

In the exercise, timestamp is the fixed "2024-01-01" so the result can be checked, and you only return the object.

notes-api's request log and how to filter it

At 10:42 UTC (11:42 in London), some users report that their notes fail to load. The Lab holds 16 log lines from 10:41 to 10:44. To find the cause, take the warn and higher lines in the 10:42 minute. This filterLogs function does that:

function filterLogs(lines, minLevel, from, to) {
  return lines
    .map((line) => JSON.parse(line))
    .filter((log) => LEVELS[log.level] >= LEVELS[minLevel])
    .filter((log) => {
      const t = Date.parse(log.time);
      return t >= Date.parse(from) && t < Date.parse(to);
    });
}

filterLogs(lines, "warn", "2026-10-09T10:42:00.000Z", "2026-10-09T10:43:00.000Z");

The result is four lines:

time level msg context
10:42:03.215 warn db pool almost full used 9, max 10
10:42:07.402 error db connection timeout reqId r-105, timeoutMs 5000
10:42:07.405 error request failed reqId r-105, GET /notes, 500, 5,003 ms
10:42:19.044 error request failed reqId r-107, POST /notes, 500, 5,001 ms

4 of the 16 lines are left, and their order tells the story: the connection pool is almost full, one connection times out after 5 seconds, then two requests fail with status 500. reqId r-105 ties the database error to the request that failed. In the 10:41 minute there is a warn for an 870 ms query: that slow query is what started holding connections.

What never goes in a log

Logs are read by many people and copied to many places: the server's disk, the log service, backups. Never write:

Personal data such as email addresses and phone numbers goes in only as far as needed, or masked. The classic mistake is logging the whole request body. The Lab's failed-login line carries Sari's password as plain text. Remove the password at the source, before the line is printed. In pino, you do that with the redact option:

const logger = pino({ level: process.env.LOG_LEVEL || "info", redact: ["body.password", "req.headers.authorization"] });

The fields named in redact are written as "[Redacted]". The Security Logging & Monitoring lesson in the Security track covers the other side: which events you must record for security, such as failed logins and permission changes.

In a container: write to stdout

An app in a container should not write log files of its own. Write to stdout, and let the platform store and send it. Docker keeps every container's stdout, and you read it with this command:

deploy@web-1:/srv/notes-api$ docker compose logs --since 10m app
app-1  | {"time":"2026-10-09T10:41:02.114Z","level":"info","msg":"request completed","reqId":"r-101", ...}

--since 10m shows the last 10 minutes of log, -f keeps showing new lines live, and --no-log-prefix drops the app-1 | prefix. To keep the disk from filling up, limit the log's size in docker-compose.yml:

services:
  app:
    image: ghcr.io/budi/notes-api:e4b2d90
    environment:
      LOG_LEVEL: info
    logging:
      driver: json-file
      options:
        max-size: "10m"
        max-file: "3"

Here one log file is at most 10 MB (max-size; in this config m means MB, not minutes), and Docker keeps at most 3 files (max-file). When a fourth file is made, the oldest is deleted.

The log Docker keeps disappears when the container is removed, and every server has its own. Once the app runs in many containers or servers, a shipper (a program that sends logs: Vector, Fluent Bit, Grafana Alloy) sends the logs to one central place such as Loki, Elasticsearch or CloudWatch Logs. What that gives you: a request that passes through several services can be tied together by its request ID, the logs stay after the container is gone, and everything is queried in one place. The Structured Logging Patterns and OpenTelemetry Fundamentals lessons cover these patterns in more depth.

⚠️ What makes logs noisy, expensive or leaky

TL;DR: A good log (the record of events an app writes) is one JSON line per event. Each line has time (in the international date format ISO 8601, in UTC, the world's standard time), level (how important), a msg (message) with fixed wording, and context such as reqId (the request ID) and userId. Levels go debug < info < warn < error < fatal. The minimum level from the LOG_LEVEL environment variable drops everything below it, so a warn filter means warn and above. Syslog (the log standard on Linux) and Monolog (a PHP log library) have three levels above error: critical, alert and emergency, for serious failures that need handling right away. To find the cause of a problem, filter by level, then by a time window, and tie lines together by request ID. Never log passwords, tokens, the Authorization header or cookies: redact (mask) them in the logger before the line is printed. In a container, write to stdout (what console.log prints), read it with docker compose logs, limit its size, and send it to a central log (Loki, Elasticsearch, CloudWatch) once there is more than one server.

⚡ One log line, four parts

Write:

{"time":"2026-10-09T10:41:02.114Z","level":"info","msg":"request completed","reqId":"r-101","method":"GET","path":"/notes","status":200,"ms":38,"userId":42}

Meaning: This is one log line (a record of an event the app writes), in JSON. time is when, in UTC (the world's standard time), level is how important, and msg is a fixed sentence so it can be counted. The rest is context, such as reqId (the request ID) and userId, each in its own field (a name and value pair). Logs whose lines are built like this are called structured logging.

⚡ Levels and the minimum

Write:

debug < info < warn < error < fatal
Guess first: a level is how important a log line is, from debug (the least) to fatal (the most serious). There are 3 debug, 7 info, 3 warn and 3 error lines. How many does a warn filter show, 3 or 6?

Six lines. A warn filter means warn and everything more important, so 3 warn + 3 error.

Meaning: A logger (the part of the app that writes the log) gets a minimum level, usually from the LOG_LEVEL environment variable. Lines below the minimum are dropped right away. Monolog (a PHP log library, which Laravel uses) and syslog (the log standard on Linux) have three levels above error: critical, alert and emergency. They are for serious failures that need handling right away, such as the main database going down.

⚡ Find the cause: level, then a time window

Write:

filterLogs(lines, "warn", "2026-10-09T10:42:00.000Z", "2026-10-09T10:43:00.000Z");

Meaning: filterLogs takes, from lines (the log lines), every warn and higher line in the 10:42 minute, from 10:42:00 up to just before 10:43:00. 4 of the Lab's 16 log lines are left, and their order tells the story: the database connection pool is almost full, one connection times out, then two requests fail with status 500. reqId (the request ID) ties the database error to the request that failed.

⚡ What never goes in a log

Write:

const logger = pino({ level: process.env.LOG_LEVEL || "info", redact: ["body.password", "req.headers.authorization"] });

Meaning: pino is a log library for Node. The redact option masks the fields you name, here the password in the request body and the Authorization header: their values are written as "[Redacted]". Passwords, tokens, the Authorization header and cookies are masked in the logger before the line is printed. In a container, write logs to stdout (what console.log prints) and read them with docker compose logs.

What you will learn