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.
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
transports: [new winston.transports.Console()],
});
logger.info('Server started');
logger.error('Something failed');info: Server started
error: Something failedWinston formats logs with a level and timestamp automatically.
console.error('Failed to connect:', err.message);Failed to connect: connection refusedconsole.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.
