0

问题是,当我从 http 调用的控制器内的导出函数调用记录器时,它仅适用于本地策略,slack 和 sentry 永远不会得到通知。

记录器设置类似于:

服务器.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'
        })
    ],
}); 
//...

(我没有看到使用全局变量的示例,如果这不是一个好主意,请告诉我,但是像这样它可以在所有文件中使用,而无需导入。)

测试控制器:

测试.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)
}
//...
4

1 回答 1

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();
};
于 2014-10-28T10:50:12.420 回答