我有一个 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/