Search code examples
sails.jswinston

Using Winston and Morgan to log in Sails


In the config/log.js file for Sails this is my code:

var express = require("express");
var app = express();
var winston = require('winston');


var logger = new(winston.Logger)({
  transports: [
    new(winston.transports.File)({
      level: 'info',
      timestamp: true,
      filename: './logFile.log',
      handleExceptions: true,
      json: true,
      colorize: false
    }),
    new(winston.transports.Console)({
      level: 'debug',
      timestamp: true,
      handleExceptions: true,
      json: false,
      colorize: true
    })
  ],
  exitOnError: false
});

logger.stream = {
  write: function (message, encoding) {
    logger.verbose(message);
  }
};

app.use(require('morgan')("combined", {"stream": logger.stream}));

module.exports.log = {

  level: 'info',
  custom: logger

};

I'm trying to use morgan along with winston to log all the HTTP requests. I found an example online that said to do it this way, and this makes sense to me, but for some reason my log file isn't showing any of the requests that are made. The winston part is fine as it is logging all the information that it should be, but I don't know how to get morgan to work with winston. Any advice or suggestions? Thanks!


Solution

  • Morgan is an express middleware so it should be loaded as a custom middleware to Sails. To do that add the following to config/http.js:

    customMiddleware: function(app) {
      app.use(require('morgan')("combined", {"stream": sails.config.log.custom.stream}));
    }