AceDevHub
Beginner Node.js Interview QuestionsBeginnerConcept

Node.js · Question 32

How does console and logging work in Node.js?

Direct answer

console methods (log, error, warn, time) write to stdout/stderr — fine for dev; production APIs use structured loggers (pino in Fastify) with levels, JSON output, and request correlation IDs.

Node's console is a thin wrapper around process.stdout and process.stderr. It is synchronous for small writes — acceptable in scripts, risky as the only observability in high-traffic servers.

  • console.log / info — general output; objects print with util.inspect depth.
  • console.error — stderr; survives when stdout is piped or captured differently.
  • console.time / timeEnd — quick duration labels for local profiling.
  • Structured logging — pino/bunyan: level, msg, reqId, err stack as JSON lines for log aggregators.
logging-basics.mjs
console.log("Server starting on port", process.env.PORT ?? 4000);

console.time("import");
// await importInterviewFile(...)
console.timeEnd("import");

// Production-style (Fastify uses pino internally)
const log = {
  info: (obj, msg) => console.log(JSON.stringify({ level: 30, ...obj, msg })),
  error: (obj, msg) => console.error(JSON.stringify({ level: 50, ...obj, msg })),
};

log.info({ topicSlug: "nodejs-interview-questions" }, "content imported");