LESSON 75 · ADVANCED4 min read

Debugging, Profiling & Observability

Find defects with breakpoints, read production signals, and measure performance before changing code.

ES2024 / Node.js 20+Free to readModule 17 of 19
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Debug running browser and Node.js code with breakpoints and the inspector.
  • Emit structured logs with levels and request identifiers.
  • Use profiles and observability signals to locate real bottlenecks and failures.

01Breakpoints beat scattered logs

console.log is a fine first probe, but it becomes noise when a bug spans several calls or a value changes inside a loop. A breakpoint pauses execution exactly where you choose, then lets you inspect every variable in scope, move one line at a time, and resume. In browser DevTools, open the Sources panel, click a line number, and reload.

Use a conditional breakpoint when the interesting case is rare, such as an order total above a threshold. A debugger statement does the same from code, but remove it before committing; a paused production tab is not a feature. Step over skips a called function, step into enters it, and step out finishes it. Source maps let you debug original files after a build.

02Node's inspector and honest stack traces

Start a Node process with node --inspect-brk app.js to pause before the first line, then open chrome://inspect and connect. Use --inspect when you want the process to keep running until you attach. The same panel shows call frames, scope variables, and the async call stack, which is often where a dropped promise hides.

Read a stack trace from the top down: the first frame is where the error was thrown, and lower frames show how execution arrived there. An error message names the symptom, not always the cause. When you wrap an error, pass the original as the cause option so the chain survives logging and error trackers.

config.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03Logs that scale past one request

console.log prints a value, but production logs need shape and context. Emit one JSON object per line with a timestamp, level, service name, message, and relevant fields. Machines can filter and aggregate that shape; humans can still read it. Keep field names stable so dashboards and alerts do not break when a message changes.

Use levels deliberately: debug for local detail, info for normal milestones, warn for recoverable surprises, and error for failures that need attention. Attach a request id to every log line for one request and return it in a response header. Never log passwords, tokens, full card numbers, or personal data you do not need.

logger.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

04Measure before you optimize

Performance work starts with a measurement, not an opinion. performance.now() gives a monotonic millisecond clock for timing a section. For a real profile, run Node with --cpu-prof and inspect the generated profile in Chrome DevTools, or use --inspect and the Performance panel. The flame chart shows where time is actually spent.

Heap snapshots answer a different question: what is retaining memory? Take a snapshot, perform the suspect action, take another, and compare. process.memoryUsage() helps spot growth but does not explain it. Optimize the largest measured cost, then measure again. A faster function that is called twice is rarely the problem.

timing.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

05Error tracking and production signals

Unhandled failures should be visible, not silent. A process-level handler can log the error and exit with a failing code; continuing after an unknown exception risks corrupt state. Send a sanitized event to your error tracker with a release version and request id, then fix the cause. Alerts belong on user-visible symptoms such as error rate or latency, not on every log line.

Observability combines logs, metrics, and traces. Logs explain one event, metrics show trends, and traces follow one request across services. Start with a health endpoint, request duration, error count, and saturation signals such as event-loop lag. Review them after each deploy so a regression is caught by a graph, not by a customer.

LET IT CLICK

The ideas worth keeping.

  • Breakpoints and the Node inspector reveal live state more precisely than scattered logging.
  • Structured logs with levels and request ids make production behaviour searchable.
  • Profile and measure first; then optimize the cost the evidence identifies.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Exercise 1: Add request context to every log

Write createRequestLogger(baseLogger, requestId) that returns an object with info, warn, and error methods. Each method should merge requestId into the fields passed by the caller, without mutating the caller's object.

your_turn_1.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
export function createRequestLogger(baseLogger, requestId) {  const withId = (level) => (message, fields = {}) =>    baseLogger[level](message, { ...fields, requestId });  return {    info: withId('info'),    warn: withId('warn'),    error: withId('error'),  };}

Spreading fields first and then adding requestId creates a new object and makes the request id authoritative. The base logger stays independent, so the same logger can serve many requests.

02

Exercise 2: Time one operation

Write measure(label, operation) that times a synchronous function, logs the label and duration rounded to whole milliseconds, and returns the function result. Use performance.now().

your_turn_2.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
import { performance } from 'node:perf_hooks';export function measure(label, operation) {  const start = performance.now();  const result = operation();  const ms = Math.round(performance.now() - start);  console.log(JSON.stringify({ label, ms }));  return result;}

The start time is captured before the call and the end time after it, so the difference covers the operation. Returning the result keeps the helper usable as a transparent wrapper.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01A bug only appears when an order total exceeds 5000. Which debugging tool is the best fit?
02What does node --inspect-brk app.js do?
03Which log entry is most useful for correlating every message from one HTTP request?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

Exercise 1: Add request context to every log

Write createRequestLogger(baseLogger, requestId) that returns an object with info, warn, and error methods. Each method should merge requestId into the fields passed by the caller, without mutating the caller's object.

main.jsJavaScript
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock lesson completion.