How to add logging with Node.js?

Sometimes, we want to add logging with Node.js.

In this article, we’ll look at how to add logging with Node.js.

How to add logging with Node.js?

To add logging with Node.js, we can use the winston package.

We install it by running

npm i winston

Then we use it by writing

const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  defaultMeta: {
    service: 'user-service'
  },
  transports: [
    new winston.transports.File({
      filename: 'error.log',
      level: 'error'
    }),
    new winston.transports.File({
      filename: 'combined.log'
    }),
  ],
});

We create a new winston logger using the winston.Logger constructor.

We call the constructor with an object that lets us set the transports option to specify where to write the log output.

The transports option is set to an array that specifies we write log items with level error to error.log.

And we write everything else to combined.log.

The format is set to winston.format.json so the log entries are in JSON format.

And the default log item level is 'info'.

We then log entries with

logger.info('log to file');

to log something with level info.

Conclusion

To add logging with Node.js, we can use the winston package.