Node.js ยท Chapter 36 of 43

Logging

Good logging records what an application is doing, especially in production where you can't attach a debugger. Structured logs make it easier to search, filter, and monitor issues.

While `console.log()` works for small scripts, dedicated libraries like `winston` or `pino` add log levels, timestamps, and structured output for real applications.

Log levels

Common log levels are error, warn, info, and debug, letting you control verbosity and filter noise in production.

Structured logging

Structured loggers output logs as JSON objects, which is easier for log-aggregation tools (like ELK or Datadog) to parse and search.

Example 1 (javascript)
const winston = require('winston');
const logger = winston.createLogger({
  level: 'info',
  transports: [new winston.transports.Console()],
});
logger.info('Server started');
logger.error('Something failed');
Output
info: Server started
error: Something failed

Winston formats logs with a level and timestamp automatically.

Example 2 (javascript)
console.error('Failed to connect:', err.message);
Output
Failed to connect: connection refused

console.error routes to stderr, useful for separating errors from normal output.

Key points

  • Logging records application behaviour, especially useful in production.
  • Log levels (error/warn/info/debug) control verbosity.
  • Structured (JSON) logs are easier for tools to search and analyze.
  • console.error writes to stderr, distinct from console.log's stdout.
๐Ÿ’ก Note: Avoid logging sensitive data like passwords or tokens.

๐Ÿ“ Quick Quiz

1. Which is NOT a typical log level?

2. Why prefer structured (JSON) logs in production?

3. Which console method writes to stderr?