javascript - 如何使 Winston 在 Sails.js 应用程序中全局可用?

标签 javascript node.js logging sails.js winston

我有一个 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 });,而无需创建服务或必须在我想使用它的每个 Controller 中要求和配置 Winston。如何让它在全局范围内可用?

最佳答案

如果你在 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
        }
    }
]

关于javascript - 如何使 Winston 在 Sails.js 应用程序中全局可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36795315/

相关文章:

javascript - 如何在 Node 中模拟 require.main?

node.js - 如何在 puppeteer 中将 url 添加到 Flash 白名单

Nginx 日志格式 - 删除变量后面的空格

python-3.x - python : Creating a time rotating log from a config file

javascript - 有没有一种方法可以使用 rgba 颜色 [0, 15, 31, 0.4 ] 在 vue js 中设置 TD 元素的样式

JavaScript 在 Chrome 和 Safari 中在后台而不是前台打开窗口

node.js - AWS elastic beanstalk 上的默认代理配置将请求转发到的 Web 应用程序的端口号是多少?

c++ - 如果我想在 C++ 或 Java 中构建记录器类,它应该是单例还是静态的

javascript - Chrome 中的轻微 CSS 对齐问题

javascript - 通用React应用程序中的全局变量,Node抛出ReferenceError