← Back to Node.js Course | Chapter 10: Deployment & Best Practices | Lesson 5 of 7

Logging

Good logs help you understand what your app did, especially after something goes wrong.

In this page:

  1. Logging
Syntax
javascript
console.error(message);
console.warn(message);
console.info(message);
console.debug(message);

Logging

Use log levels (error, warn, info, debug), include timestamps and context, and prefer structured JSON logs that tools can search. Libraries such as pino and winston handle levels and formats. Never log passwords or tokens.

Note: Write logs to stdout and let the platform collect them.

Example: Logging

javascript
function log(level, msg, extra = {}) {
  console.log(JSON.stringify({ level, msg, ...extra, ts: "2024-01-01T00:00:00.000Z" }));
}
log("info", "server started", { port: 3000 });
log("error", "db connection failed", { attempt: 2 });

// Output:
// {"level":"info","msg":"server started","port":3000,"ts":"2024-01-01T00:00:00.000Z"}
// {"level":"error","msg":"db connection failed","attempt":2,"ts":"2024-01-01T00:00:00.000Z"}

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Logging secrets
  2. Using console.log for everything
  3. Unstructured messages that cannot be searched
Chapter Summary
  • Use log levels
  • Structured JSON logs
  • Include context and timestamps
  • Never log secrets
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.