Node’s core modules do not provide an ideal logging solution. Luckily, the developer community has created a number of useful third-party logging modules. Among the best is winston, an asynchronous logging library that maintains the simplistic interface of console.log(). Below sample shows how winston is imported and used in a trivial application. Of course, you must first npm install winston in order to use the module.

Below sample demonstrates how the winston.log() method is used. The first argument passed to log() is the logging level. By default, winston provides the log levels info, warn, and error. The second argument to log() is the message being logged.

var winston = require("winston");
winston.log("info", "Hello winston!");
winston.log("warn", "Something not so good happened");
winston.log("error", "Something really bad happened");
The Output
$ node winston-basics.js
info: Hello winston!
warn: Something not so good happened
error: Something really bad happened

Winston makes extensive use of transports. Transports are essentially storage devices for logs. The core transport types supported by winston are Console, File, and Http. As the name implies, the Console transport is used for logging information to the console. The File transport is used for logging to an output file or any other writable stream. The Http transport is used to log data to an arbitrary HTTP (or HTTPS) endpoint. By default, the winston logger uses only the Console transport, but that can be changed. A logger can have multiple transports, or no transports at all.

var winston = require("winston");
winston
      .remove(winston.transports.Console)
      .add(winston.transports.Console, {
           level: "error",
           colorize: true,
           timestamp: true
      });
winston.info("test info");
winston.error("test error");

 

Share Button

Leave a Reply

Your email address will not be published. Required fields are marked *

Post Navigation