Node.js - Appending events to the console.log

by
Jeremy Canfield |
Updated: July 22 2024
| Node.js articles
Let's say you have a file named app.js that contains the following.
console.log("Hello World");
If you use the node CLI to run app.js, "Hello World" should be displayed as stdout on your console.
~]$ node app.js
Hello World
Or, if you have some event that is considered an error, you probably want to use console.error.
console.error("naughty naughty!");
On ES6, you could create a constant that contains the timestamp.
const timestamp = () => `[${new Date().toUTCString()}]`
console.log(timestamp() + " Hello World");
Better yet, use backticks to include constant variables without having to use + or , to break in and out of strings and constant variables.
const timestamp = () => `[${new Date().toUTCString()}]`
console.log(`${timestamp()} Hello World`);
The console should then contain the timestamp.
~]$ node app.js
[Mon, 08 May 2023 06:51:27 GMT] Hello World
Better yet, use the Winston Logger.
const { createLogger, format, transports } = require('winston');
const logger = createLogger({
format: format.simple(),
transports: [
new transports.Console(),
new transports.File({ filename: 'all.log' }),
],
});
logger.error("my error message");
logger.warn("my warning message");
logger.info("my info message");
Did you find this article helpful?
If so, consider buying me a coffee over at