【问题标题】:How do I make Winston globally available in Sails.js application?如何使 Winston 在 Sails.js 应用程序中全局可用?
【发布时间】:2016-08-16 04:08:34
【问题描述】:

我有一个 Sails.js 应用程序,我希望能够使用 Winston 和 Loggly 来记录消息。现在,我有这样的服务:

log: function(type, message, content) {
    // Require and configure Winston with Loggly
    const winston = require('winston');
    require('winston-loggly');

    winston.add(winston.transports.Loggly, {
        token       : ***,    // Hiding my real token
        subdomain   : ***,
        tags        : ['sails-web-service'],
        json        :true
    });

    // Attach context to the content
    var finalContent = { timestamp: Date.now(), pid: process.pid };
    for (var attribute in content) { finalContent[attribute] = content[attribute]; }

    // Send the log
    winston.log(type, message, finalContent);
}

我可以通过以下方式调用此服务:LogService.log('info', 'Log in attempt', { email: req.body.email });

理想情况下,我只想在应用程序的任何地方直接使用 Winston,如下所示:winston.log('info', 'Log in attempt', { email: req.body.email });,而不必创建服务或必须在我想使用它的每个控制器中要求和配置 Winston。如何使其全球可用?

【问题讨论】:

    标签: javascript node.js logging sails.js winston


    【解决方案1】:

    如果你有它在api/services 你不需要每次都初始化它。如果你不想每次都需要模块,你可以这样做。移动那些线

    winston = require('winston')
    require('winston-loggly')
    

    config/bootstrap.js 并将其更改为:

    sails.winston = require('winston');
    sails.winston-loggly = require('winston-loggly');
    

    和你的服务

    log: function(type, message, content) {
       // Require and configure Winston with Loggly
    
        sails.winston.add(winston.transports.Loggly, {
            token       : ***,    // Hiding my real token
            subdomain   : ***,
            tags        : ['sails-web-service'],
            json        :true
        });
    
    // Attach context to the content
        var finalContent = { timestamp: Date.now(), pid: process.pid };
        for (var attribute in content) { finalContent[attribute] = content[attribute]; }
    
        // Send the log
        sails.winston.log(type, message, finalContent);
    }
    

    您可以尝试使用sails-hook-winston

    库扩展了日志,所以它的配置转到config/log.js。在您的情况下,它应该看起来更像这样:

    transports: [
        {
            module: require('winston-loggly').Loggly,
            config: {
                token       : ***,    // Hiding my real token
                subdomain   : ***,
                tags        : ['sails-web-service'],
                json        :true
            }
        }
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-07
      • 1970-01-01
      • 2020-04-06
      • 2016-12-23
      • 2018-04-04
      • 2015-05-11
      • 1970-01-01
      相关资源
      最近更新 更多