【发布时间】:2021-11-04 04:24:21
【问题描述】:
我有一个小函数可以将日志发送给它。在函数中,我试图将其发送到 AWS Cloudwatch,但是我遇到了一些问题。一旦发送了一个日志,我就无法发送另一个日志,直到第一个日志完成,因为我需要下一个 sequenceToken,以便下一个日志知道在哪里添加自己。我知道异步迭代器是这里的关键,但不确定如何在我的代码中实现它们。这是我当前的代码,在发送第一个日志后失败:
const build = require('pino-abstract-stream');
const stream = async (options) => {
// Creates the AWS connection
const client = await createClient();
// Gets the first token
let sequenceToken = await getInitSequenceToken(client);
return build(function (source) {
source.on("data", async function (obj) {
// Every time the log is sent to my worker thread it prints out here. Obj contains the info from the log
const command = new PutLogEventsCommand({
logGroupName: "api",
logStreamName: `executive-${Config.env}-${Config.location}`,
logEvents: [
{
message: obj.msg,
timestamp: obj.time,
},
],
sequenceToken,
});
// Here I am sending the log to Clouwatch
const response = await client.send(command);
// Here I was updating the token but this fails as the next log is already sending
sequenceToken = response.nextSequenceToken;
});
});
};
【问题讨论】:
-
什么是
source,一个websocket? -
使用自定义传输的 pino 日志:github.com/pinojs/pino-abstract-transport
-
使用该链接中的第一个示例,即带有
for await的示例,即“同步”版本。 -
我知道我可以使用第一个示例并一次发送一个请求,但肯定会更好地对它们进行批处理,而这正是我不知道该怎么做的地方。
-
您可以将
response存储在外部变量(数组)中,然后一旦流关闭(source.on('end')),您将循环使用reduce over the client.send
标签: javascript node.js amazon-web-services asynchronous async-await