在Nodejs日志中间件(例如:morgan,pino)中登录到AWS CloudWatch日志



morgan,pino是node.js日志中间件。我想将日志导出到AWS cloudWatchLogs。

例如

express:的morgan

var express = require('express');
var loggerM= require('morgan');
var app = express();
app.use(logger('dev'));

通过此设置,您可以在终端上查看日志。但它只能在终端上显示,我不知道如何获取日志字符串,我必须获取日志字符串才能将其传输到云。

我目前只找到stream方法,只能直接保存到本地文件:

const appLogStream = fs.createWriteStream(path.join(__dirname, 'app.log'), { flags: 'a' })
app.use(morgan('combined', { stream: appLogStream}));

AWS clouldWatchLogsputLogEventsapi:

var params = {
logEvents: [ /* required */
{
message: 'STRING_VALUE', /* required */
timestamp: 'NUMBER_VALUE' /* required */
},
/* more items */
],
logGroupName: 'STRING_VALUE', /* required */
logStreamName: 'STRING_VALUE', /* required */
sequenceToken: 'STRING_VALUE'
};
cloudwatchlogs.putLogEvents(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else     console.log(data);           // successful response
});

可以在日志信息中填写参数消息。

由于morgan为我们提供了将日志流附加到其生成的日志的选项。我们可以使用它来将日志写入cloudwatch日志。但是,我们如何将流连接到aws cloudwatch?

我们可以这样做:

//Create a logger using winston
var winston = require('winston'),
CloudWatchTransport = require('winston-aws-cloudwatch');
const auth = require('./config/auth');
//add console transport to logger ---> logs to machine console
const logger = new winston.createLogger({
transports: [
new (winston.transports.Console)({
timestamp: true,
colorize: true,
})
]
});
//below config creates a new log stream (snippet) in the same log gp specified at every new version of deployment
var config = {
logGroupName: 'server-log-gp', //your aws cloudwatch log gp name
logStreamName: `app.${new Date().getTime()}`, //log stream name
createLogGroup: false,
createLogStream: true, //creates new stream at deployment
awsConfig: {
accessKeyId: auth.aws.accessKeyId,
secretAccessKey: auth.aws.secretAccessKey,
region: auth.aws.region
},
formatLog: function (item) {
return item.level + ': ' + item.message + ' ' + JSON.stringify(item.meta)
}
}
//add cloudwatch logs transport to logger only in production mode
//may add in dev mode as well if you want
if (process.env.NODE_ENV === 'production') logger.add(new CloudWatchTransport(config));
logger.level = process.env.LOG_LEVEL || "silly";
logger.stream = {
write: function(message, encoding) {
logger.info(message);
}
};

现在,您需要添加morgan作为中间件,并将上面的logger.stream附加到它。

app.use(
require('morgan')(
'dev',
{ stream: logger.stream }
)
);

参见此以供参考:

Node.js-日志记录/使用morgan和winston

相关内容

  • 没有找到相关文章

最新更新