Logging

Record what a running server does in a structured, searchable way, so you can understand problems after the fact.

What is it?

During development, a stray console.log is often enough because you're watching the terminal. A production server runs unattended, often on several machines, for weeks, handling requests nobody watches. When something breaks at 3 AM, you need a record of what the server was doing then.

Logging means deliberately recording events as the server runs: a request came in, a database call took 400ms, a payment failed. Entries are usually structured and timestamped, with a severity level (like debug, info, warn, error). They're often sent somewhere searchable, not just printed to a terminal that disappears when the process restarts.

Explain like I'm 10

console.log is like shouting in an empty room: useful only if someone is listening right then. Structured logging is like a ship's logbook: every entry is timestamped, labeled by importance, and kept in a permanent, searchable record anyone can review later.

Examples

Ad-hoc console.log vs. structured logging

// Ad-hoc — fine for local debugging, poor for production
console.log("user logged in", userId);

// Structured — with a logging library like winston or pino
logger.info("user_login", { userId, ip: req.ip, timestamp: Date.now() });

The structured version adds a severity level, a machine-readable event name, and consistent fields, so you can filter and search logs later instead of parsing free-form text.

Logging at different severity levels

logger.debug("cache lookup", { key: cacheKey });      // routine, verbose detail
logger.info("order created", { orderId });             // normal operation
logger.warn("payment retry", { orderId, attempt: 2 });  // recoverable issue
logger.error("payment failed", { orderId, err });       // needs attention

Severity levels let you turn verbosity up or down per environment (full detail in development, only warnings and errors in production) without changing the logging calls.

How it works

A logging library gives you a method per severity level (debug, info, warn, error) instead of one flat console.log. Each call records a structured entry, usually with a timestamp, the level, a message, and any extra data you attach.

Entries go to one or more destinations: the terminal in development, and often a file or external logging service in production, where logs from many server instances can be searched together. A configured minimum level (like "info and above") decides which calls get recorded in each environment.

Why does it exist?

Production problems are almost never diagnosed live. Someone investigates later, often much later, without having watched it happen. Logging leaves a durable, searchable trail of what the system was doing, so it can answer questions nobody thought to ask at the time.

When to use it

Log meaningful events: requests, errors, retries, and decision points that help explain behavior later. This matters most around payments, authentication, and external services that can fail.

When not to use it

Don't log very frequent, low-value events at a verbose level in production (like every cache hit). It drowns out the signal you need and can become a performance or cost problem itself.

Common mistakes

  • Logging sensitive data (passwords, full card numbers, tokens) where it can be seen or leaked.

  • Using one level for everything (usually console.log), so you can't filter noise from real problems.

  • Keeping logs only in a terminal or on one server's disk, so they vanish when that process or machine goes away.

Practice exercises

  1. Easy:

    Replace three console.log calls in a small Express app with structured logger.info calls that include useful context.

  2. Medium:

    Add a logger.error call in a catch block that records the error and the request path, without leaking the raw error in the client's response.

  3. Hard:

    Explain why logging a user's raw password is a serious mistake even if the log file is 'internal only,' and describe a safer alternative.

Interview questions

Why is structured logging preferred over ad-hoc console.log statements in production?

Structured logs are timestamped, leveled, and machine-readable, so you can search and filter them later. They also outlive a single terminal session.

What are severity levels in logging, and why do they matter?

Levels like debug, info, warn, and error mark how important an entry is. They let you control verbosity per environment, e.g. full detail in development but only warnings and errors in production.

What kind of data should never be written to logs?

Sensitive data like passwords, full payment card numbers, or authentication tokens. Logs can be read by more people and systems than the original data was meant for.

Why can excessive logging itself become a performance problem in production?

Every log call costs something: serializing data and writing it to disk or the network. At high volume, logging every routine event verbosely can add real latency and storage cost, competing with the server's actual work.

What does it mean to set a minimum log level in production, e.g. only warn and above?

Calls below that threshold, like debug or info, are dropped and never written. The same code gives quiet output in production and full detail in development by changing one config value.

Why is including a request or correlation ID in every log line tied to a single incoming request useful?

With concurrent traffic, log lines from many requests interleave. A shared id on every line for one request lets you filter out that request's full story afterward, even among thousands of others.

Why do production systems typically send logs to a centralized aggregation service instead of just writing to a local file?

It collects logs from every instance into one searchable place. A log on one instance's local disk is lost if that instance is replaced or scaled down, and you can't search across instances without a central destination.

Why might a team choose JSON as the on-the-wire format for log entries rather than a human-readable sentence?

Log tools can parse JSON reliably and filter, aggregate, and query its fields directly. A free-form sentence needs pattern matching or regex, which is brittle and breaks when the wording changes slightly.

What's the risk of logging an entire request or response body indiscriminately?

Bodies often contain exactly the sensitive data that shouldn't be logged, and can be large. Logging them wholesale creates a security or privacy liability and bloats log storage.

Why should error logs typically include the full stack trace, not just the error's message string?

The message often says what went wrong but not where. The stack trace shows the call chain that led to the failure, which is usually what you need to find and fix the bug.

What's the difference between logging and monitoring or alerting?

Logging records events for later inspection. Monitoring and alerting watch metrics or log patterns continuously and notify someone when a threshold is crossed. Logs are often the raw material alerting watches, but the two serve different purposes.

Why is `console.log` particularly unsuitable for a production Node.js server handling concurrent requests?

It writes synchronously to standard output by default, which can block the event loop under heavy load. Its output is also unstructured, untimestamped, and unleveled, so it doesn't fit aggregation or filtering tools.

Why might you log at the `warn` level for a recoverable failure, like a successful retry after one failed attempt, instead of `error`?

Keeping error for events that need attention keeps that level meaningful. Logging every recovered hiccup as an error causes alert fatigue and buries the urgent ones.

How would you redact a sensitive field, like a password or token, from a log entry while still logging the rest of the object it's part of?

Explicitly remove or mask that field before logging, e.g. by destructuring it out, instead of logging the raw object and hoping nothing sensitive is in it.

Why might logging configuration differ between local development and production, beyond just the minimum level?

Development often wants colorized, readable console output for a person. Production usually wants machine-parseable JSON sent to an aggregation service, maybe to other destinations too. The logging calls stay the same; only the configured format and destinations change.