使用AWS SDK for JavaScript中的CloudWatch Logs服务API,通过调用describeLogStreams和getLogEvents函数来获取最新的日志事件,以解决Lambda函数日志延迟的问题。以下是示例代码:
const AWS = require('aws-sdk');
const cloudwatchlogs = new AWS.CloudWatchLogs();
exports.handler = async (event, context) => {
const logGroupName = '/aws/lambda/your-function-name';
// Get latest log stream from the log group
const streamResp = await cloudwatchlogs.describeLogStreams({
logGroupName,
descending: true,
orderBy: 'LastEventTime',
limit: 1
}).promise();
const { logStreamName } = streamResp.logStreams[0];
// Get latest log events from the log stream
const eventResp = await cloudwatchlogs.getLogEvents({
logGroupName,
logStreamName,
startFromHead: true
}).promise();
// Process log events
eventResp.events.forEach(event => {
console.log(event.message);
});
};