Node.js

Lesson 09

Structured logging

Log machine-readable events with request context and without sensitive data.

Good Code

src/logging.ts
type LogEvent = {
  level: "info" | "error";
  message: string;
  requestId: string;
  durationMs?: number;
};

export function logEvent(event: LogEvent) {
  console.log(JSON.stringify({
    time: new Date().toISOString(),
    ...event,
  }));
}

Bad Code

src/login.ts
export function logLoginAttempt(email: string, password: string) {
  console.log("Login failed for " + email + " with password " + password);
}

Review Notes

What to review

Good Code

The good version emits structured JSON with stable fields that log systems can search and aggregate.

Bad Code

The bad version logs a free-form string and includes a password, turning logs into a security incident.

Takeaways

  • Logs should help correlate behavior without leaking secrets or personal data.