Monitoring & Logging: Knowing Before Your Users Do

Monitoring & Logging: Knowing Before Your Users Do in JavaScript: Once your code leaves your laptop you lose the debugger.

Concept Explanation

Once your code leaves your laptop you lose the debugger. You cannot set a breakpoint on a customer's checkout at 3am in another timezone. What you have instead is whatever you decided, in advance, to record.

That is why observability is a design decision rather than an afterthought. The classic framing is the three pillars:

  • Logs are discrete events. "User 88 failed login from this IP." Good for the specifics of one incident.
  • Metrics are numbers aggregated over time. Requests per second, p95 latency, error rate. Good for noticing that something changed.
  • Traces follow one request across every service it touched, with timings. Good for answering where the 900ms went.

And the practical distinction that matters most day to day: monitoring tells you a known thing broke; observability is having enough recorded to investigate a failure nobody predicted.


Syntax or Core Structure

Structured logs, not sentences

// BAD: unparseable, ungreppable at scale
console.log('User ' + id + ' failed to pay: ' + err.message);

// GOOD: machine-queryable JSON
import pino from 'pino';
const log = pino({ level: process.env.LOG_LEVEL || 'info' });

log.error({
  event: 'payment_failed',
  userId: id,
  orderId: order.id,
  provider: 'stripe',
  code: err.code,
  requestId: req.id
}, 'payment failed');

Now "show me every payment failure with code card_declined in the last hour, grouped by provider" is one query instead of a regex archaeology project.

Correlating a request end to end

import { randomUUID } from 'node:crypto';

app.use((req, res, next) => {
  req.id = req.headers['x-request-id'] || randomUUID();
  res.setHeader('x-request-id', req.id);
  req.log = log.child({ requestId: req.id });   // every line carries the id
  next();
});

Catching what you did not expect

process.on('unhandledRejection', (reason) => {
  log.fatal({ err: reason }, 'unhandled rejection');
  process.exit(1);         // let the supervisor restart a poisoned process
});

Key Features

LevelUse it for
fatalThe process cannot continue
errorThis request failed and somebody should look
warnDegraded but handled: a retry, a fallback, a deprecation
infoNotable business events: order placed, user registered
debugDeveloper detail, off in production

The four signals worth alerting on (the "golden signals"): latency, traffic, error rate, and saturation. Almost every real incident shows up in at least one.

SLOs beat thresholds. "99.5% of checkout requests succeed within 500ms over 30 days" is a target you can reason about and budget against. "Alert when CPU is over 80%" mostly generates noise.


Real World Example

The outage nobody was paged for. A payment provider started returning 500s for one card type. The service caught the error, logged it, showed the user a generic "try again" message, and returned HTTP 200. Every dashboard was green: no 5xx, normal latency, healthy CPU. Support tickets were the alerting system, and they arrived nine hours later.

The gap was that the team monitored infrastructure rather than outcomes. Adding one business metric, successful checkouts per minute, with an alert on a sharp drop, would have caught it in about two minutes. The most valuable thing to watch is usually not a server statistic; it is the number that means the product is working.


Common Mistakes

  • Logging secrets or personal data. Tokens, passwords, card numbers and full request bodies end up in a searchable store with wide access, and often a compliance obligation attached. Redact at the logger.
  • console.log everywhere in production. Unstructured, unleveled, and expensive: synchronous writes to stdout under load are a real bottleneck.
  • Alerting on everything. An on-call rotation that receives forty pages a night stops reading them. Every alert must be actionable.
  • Swallowing errors. catch (e) {} deletes the evidence. If you truly can ignore it, log at debug and say why in a comment.
  • No request ID. Without correlation you have thousands of unrelated lines instead of one story.
  • Monitoring only servers. Add real-user monitoring for the frontend; a JS exception that blanks the page produces no server error at all.
  • Unbounded retention. Logs are cheap per line and startling per terabyte. Sample the noisy paths.

Best Practices

  • Emit structured JSON with a consistent set of fields, and attach a request ID to every line.
  • Redact sensitive keys in the logger's configuration, so no individual call site can leak them by accident.
  • Track a handful of business metrics (signups, orders, successful payments) alongside the technical ones, and alert on those.
  • Send exceptions to an error tracker (Sentry or similar) with release and user context so you get grouping and regression detection for free.
  • Add a /health endpoint that actually checks its dependencies, and make your platform's restart policy depend on it.
  • Write a one-page runbook per alert: what it means, what to check first, how to mitigate.
  • Set log level by environment: debug locally, info in production, and make it changeable without a redeploy.

Practice Exercises

  1. The Structured Switch: Replace every console.log in a small Express app with a pino logger, add a request-ID middleware, and confirm one request's lines can be filtered by that ID.
  2. The Redactor: Configure your logger to redact password and authorization fields, then deliberately log an object containing both and verify the output.
  3. The Business Metric: Pick one number that means your app is working, expose it as a counter, and describe the alert you would set on it (threshold, window, and who gets paged).