问题在于,当我从http调用的控制器内部的导出函数调用记录器时,它只适用于本地策略,松弛和哨兵永远不会得到通知。
记录器设置类似于:
server.js
//...
winston = require('winston'),
Sentry = require('winston-sentry'),
slack = require('winston-slack').Slack,
winstonMongodb = require('winston-mongodb').MongoDB;
global.log = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
handleExceptions: true,
prettyPrint: true,
colorize: true,
}),
new (winston.transports.File)({
filename: 'logs.log',
json: true,
handleExceptions: true
}),
new Sentry({
dsn: "XXXXXXXXXXXXXXXXXXXXXXXXXX",
patchGlobal: true,
}),
new slack({
domain: "XXXXXXXXXXXXXXXXXXXXXXXXXX",
apiToken: "XXXXXXXXXXXXXXXXXXXXXXXXXX",
channel: "#XXXXXXXXXXXXXXXXXXXXXXXXXX",
username: "XXXXXXXXXXXXXXXXXXXXXXXXXX",
handleExceptions : true
}),
new(winston.transports.MongoDB)({
dbUri: 'mongodb://XXXXXX:XXXXXXXX@XXXXXX.mongohq.com:XXXXXX/XXXXXX'
})
],
});
//...
(我没有看到使用全局var的例子,如果它不是一个好主意让我知道,但是像这样它可以在所有文件中使用而无需导入。)
测试控制器:
test.js
//...
//called on server starts
log.info('test') //works with all transports
//called later by an HTTP request
exports.test = function(req, res, next){
log.info('test') //only works with local transports (console and file)
}
//...
答案 0 :(得分:0)
应尽可能避免使用全局变量,因为在这种情况下。您可以使用单例而不是使用全局“日志”,如下所示:
var winston = require('winston');
var LoggerSingle = (function () {
var instance = null;
function Logger () {};
Logger.prototype = new (winston.Logger)({
transports: [...]
});
return {
getInstance: function () {
if (instance === null)
instance = new Logger();
return instance;
}
};
})();
exports.single = function () {
return LoggerSingle.getInstance();
};