Custom log routing
Send application logs to a file or other writable destination.
Node.js · Module
The node:console module provides a global console and a configurable Console class for debugging and logging. Custom instances can direct regular output and errors to chosen writable streams.
The module exposes the Console class and a preconfigured global console. Instantiate Console with writable stdout and stderr streams to direct regular output separately from warnings and errors; the global instance targets process.stdout and process.stderr.
new Console({ stdout, stderr })| Name | Type | Description |
|---|---|---|
stdout | stream.Writable | Writable stream receiving log and informational output. |
stderr | stream.Writable | Writable stream receiving warning and error output. |
A Console instance when constructed with new Console(options).
const { Console } = require('node:console');
const fs = require('node:fs');
const output = fs.createWriteStream('./app.log');
const logger = new Console({ stdout: output, stderr: output });
logger.log('started');
logger.error('something went wrong');
output.end();Creates a Console instance that sends both normal and error messages to a writable file stream.
Send application logs to a file or other writable destination.
Keep warnings and errors separate from routine informational output.
Print quick diagnostics during development or command-line execution.
The module provides a Console class and a global console instance. The class writes through configurable streams, while the global instance is configured for process.stdout and process.stderr.
Follow-up: How would you route errors to a separate destination? Construct Console with the normal destination as stdout and a different writable stream as stderr.
Use new Console({ stdout, stderr }), where stdout is the writable stream for log or informational output and stderr receives warnings and errors.
Follow-up: What happens if stderr is omitted? The documentation states that warning and error output is sent to stdout.
The global console is equivalent to new Console({ stdout: process.stdout, stderr: process.stderr }). It is available directly without importing node:console.
Follow-up: Why use a custom instance instead? It lets the application choose writable destinations rather than the process defaults.
console.log()console.error()console.warn()process.stdoutprocess.stderr