当我尝试使用 aws sdk 捕获 aws could 监视日志时,我遇到了同样的问题。
当我使用 logStreamNamePrefix 时,我终于解决了这个问题,在我的例子中是设备的 uuid。
所以我创建了下面的函数,当我第一次运行它时,我在没有 nextToken 的情况下执行它,随后我在请求中获取令牌并使用令牌再次调用它以继续搜索。
loadCloudWatchLogs(nextToken?: string) {
// Set the region
AWS.config.update({
region: 'sa-east-1',
credentials: {
accessKeyId: environment.awsAccessKeyId,
secretAccessKey: environment.awsSecretAccessKey,
},
});
// Create the CloudWatchLogs service object
const cloudwatchlogs = new AWS.CloudWatchLogs({ apiVersion: '2014-03-28' });
// Defines the params attributes pattern.
let params: AWSCloudWatchParams;
// Check if token was provided to permorm a next query to AWSCloudWatchLogs.
if (nextToken) {
params = {
logGroupName: 'group-name' /* required */,
startTime: this.startTime,
endTime: this.endTime,
logStreamNamePrefix: this.device,
filterPattern: `{ ($.device="${this.device}") }`,
nextToken,
};
} else {
params = {
logGroupName: 'group-name' /* required */,
startTime: this.startTime,
endTime: this.endTime,
logStreamNamePrefix: this.device,
filterPattern: `{ ($.device="${this.device}") }`,
};
}
// Execute a filter for logs.
cloudwatchlogs.filterLogEvents(params, (err, data) => {
if (err) {
console.log(err, err.stack);
} else {
if (data.searchedLogStreams.length > 0) {
// Chegk if exists more logs for query.
const loadMoreLogs = !data.searchedLogStreams[
data.searchedLogStreams.length - 1
].searchedCompletely;
// Update the token for the next query.
this.nextToken = data.nextToken;
data.events.forEach(log => {
// log proccessing...
});
}
}
});
}
这个功能我在一个 Angular 项目中做的,但即使对 javascript vanila 进行一些调整,它也可以工作。