How to add timestamps to all console messages with Express and Node.js?

Sometimes, we want to add timestamps to all console messages with Express and Node.js.

In this article, we’ll look at how to add timestamps to all console messages with Express and Node.js.

How to add timestamps to all console messages with Express and Node.js?

To add timestamps to all console messages with Express and Node.js, we can customize the Express logger with express.logger.format.

For instance, we write

const df = require('console-stamp/node_modules/dateformat');

express.logger.format('mydate', () => {
  return df(new Date(), 'HH:MM:ss.l');
});

app.use(express.logger('[:mydate] :method :url :status :res[content-length] - :remote-addr - :response-time ms'));

to require the console-stamp module.

We install it by running

npm i console-stamp

Then we call express.logger.format with the name of the logger and a function to returns the logger formatter object by calling df to include the date in the log entries.

Then we call express.logger to return the logging middleware with the custom format.

And we call app.use to use the logger middleware.

Conclusion

To add timestamps to all console messages with Express and Node.js, we can customize the Express logger with express.logger.format.