Logging with Winston

A very popular alternative to Pino is the Winston logger.

In the main, the winston logger has the same Log4J interface as Pino, however, it differs greatly from pino in philosophy.

The winston logger supplies a large amount of features and configuration options - such as log rotation, multiple destinations based on log levels, and in process logging transformations.

These come with the winston logger as standard, and are used in the same Node process as the server (which from a performance perspective is something of a trade off).

Let's copy the express-views folder from our previous recipe into a new folder that we'll call express-winston-logging, and install winston and express-winston:

$ cp -fr adding-a-view-layer/express-views express-morgan-logging
$ cd express-morgan-logging
$ npm install --save morgan

Now we'll add the following to our dependencies at the top of the index.js file:

const winston = require('winston') 
const expressWinston = require('express-winston') 

Just above where we instantiate the Express app (const app = express()), we'll create a Winston logger instance, configured to output to process.stdout in JSON format:

const logger = new winston.Logger({ 
  transports: [ 
    new winston.transports.Console({ 
      json: true 
    }) 
  ] 
}) 

By default, the winston.transports.Console transport will output logs in the format ${level}: ${message}. However, we can set the json option to true to enable JSON logging.

In the middleware section of index.js we'll register the express-winston middleware, passing it the Winston logger instance (logger) like so:

app.use(expressWinston.logger({ 
  winstonInstance: logger 
})) 

Finally at the bottom of index.js we'll use the logger instance to output the initial server log:

app.listen(port, () => { 
  logger.info(`Server listening on port ${port}`) 
}) 

We won't modify the routes/index.js file to log a request-linked message, as Winston does not support this.

If we run our server (node index.js) and make a request to http://localhost:3000 we should see output similar to the following:

The winston logger and its express-winston counterpart have a vast API with many options, see the respective readmes (http://npm.im/winston and http://npm.im/express-winston) for more information.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.161.225