Winston Logging - 如果另一个传输失败,则恢复传输

时间:2014-10-07 15:02:49

标签: node.js elasticsearch winston

我使用winston和winston-elasticsearch登录Elastic Search。我没有问题设置传输,一切正常工作。

无论如何,如果ES服务器无法访问,在停机期间发送的日志似乎永远丢失。

当Elastic-Search传输失败时,是否有办法告诉Winston登录文件?

1 个答案:

答案 0 :(得分:2)

我也试图处理这种情况(即当一个传输无法记录消息时(在我的情况下是一个文件记录器,如果有人在配置中提到了错误的文件路径,它可能会失败))通过订阅“错误”记录器的事件。但我无法让它发挥作用。

我尝试的是实例化2个不同的Logger One和File Transport,另一个使用Mail Transport然后订阅了第一个记录器的“error”事件,并在错误事件中使用Logger with Mail传输发送邮件,但错误事件是如果我指定了错误的文件路径并且Node进程崩溃,则不会被触发。

var config = require('config');
var smtpConfig = config.get('serving.smtp');
var adClickLogConfig = config.get('adClick.logging');
var adClickMailConfig = config.get('adClick.mail');

var winston = require('winston');
require('winston-mail').Mail;

function AdClickLoggingService (staticFunctions){
    this.staticFunctions = staticFunctions;
    var fileName  = adClickLogConfig.filePath + "/" + adClickLogConfig.fileName;
    this.fileLogger = new (winston.Logger)({
        transports: [
            new (winston.transports.File)({
                filename: fileName,
                level: adClickLogConfig.level,
                timestamp : adClickLogConfig.timeStamp,
                maxsize : adClickLogConfig.maxSize,
                maxFiles : adClickLogConfig.maxFiles,
                json : adClickLogConfig.json
            })
        ]
    });

    this.fileLogger.on('error', function (err) {
        this.emailLogger.info(err);
    });


    this.fileLogger.on('logging', function (transport, level, msg, meta) {
        console.log('Message logged' + msg);
        // [msg] and [meta] have now been logged at [level] to [transport]
    });

    this.emailLogger = new (winston.Logger)({
        transports: [
            new (winston.transports.Mail)({
                host: smtpConfig.host,
                tls: smtpConfig.tls,
                to : adClickMailConfig.toAddress.join(),
                from : adClickMailConfig.fromAddress,
                subject : adClickMailConfig.subject
            })
        ]
    });

    this.fileLogger.on('error', function (err) {
        console.log(err);
    });
};

AdClickLoggingService.prototype = {
    logAdClick:function(id, msg){
        msg.adClickId = id;
        msg = this.staticFunctions.convertToString(msg);
        return this.fileLogger.info(msg);
    }
};