重载sails.log函数以包含日志来自的源文件名

时间:2015-10-04 17:46:28

标签: sails.js

我想重载sails.log函数,如info,debug,error等,以包含从中打印日志的文件名的路径。例如,

// api/controllers/UserController.js

module.exports =  {

  create: function (req, res) {
    // some operations
    sails.log.info("created a new user");
  }
}

上面的日志语句应打印

[api/controllers/UserController.js] info: created a new user

我该怎么做?

2 个答案:

答案 0 :(得分:1)

重写SailsJS记录器是错综复杂的。 (https://github.com/balderdashy/sails/issues/2695

我最终使用自己制作的记录器。我只是创建了一个日志服务。 Log.js文件夹中的api/services

在这个文件中我

module.exports = {
    e:function(message){
        //do other stuffs here
        console.log(message);
    }
};

然后我可以这样做:

Log.e(message);

要获取脚本文件的名称,您可以使用__filename。这将返回脚本/控制器的整个路径,如下所示:

//console.log(__filename)

/Users/blab/Desktop/SM/api/controllers/BrandController.js

我希望这有帮助!

答案 1 :(得分:1)

我得到了关于gitter的答案,https://gitter.im/balderdashy/sails#

在此发布:

var winston = require('winston');

var getCaller = function ()
{
  var stack = getStack();
  stack.shift();
  var obj = stack[3];
  // Return caller's caller
  return obj.getFileName();
};

var getStack = function ()
{
  // Save original Error.prepareStackTrace
  var origPrepareStackTrace = Error.prepareStackTrace;

  // Override with function that just returns `stack`
  Error.prepareStackTrace = function (_, stack)
  {
    return stack;
  };

  // Create a new `Error`, which automatically gets `stack`
  var err = new Error();

  // Evaluate `err.stack`, which calls our new `Error.prepareStackTrace`
  var stack = err.stack;

  // Restore original `Error.prepareStackTrace`
  Error.prepareStackTrace = origPrepareStackTrace;

  // Remove superfluous function call on stack
  stack.shift(); // getStack --> Error

  return stack
};


var customLogger = new winston.Logger({
  transports: [
    new(winston.transports.File)({
      level: 'debug',
      filename: './logs/application.log'
    }),
    new (winston.transports.Console)({
      level: 'silly',
      colorize: true,
      timestamp: true
    })
  ]
});
customLogger.log = function(){
  var args = arguments;
  args[1] = getCaller()+" - "+args[1];

  winston.Logger.prototype.log.apply(this,args);
};
module.exports.log = {
  colors: false,
  custom: customLogger
};