You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java获取AWS指定Log Group下的最新Log Stream名称

修复后可直接运行的代码

import com.amazonaws.regions.Regions;
import com.amazonaws.services.logs.AWSLogs;
import com.amazonaws.services.logs.AWSLogsClientBuilder;
import com.amazonaws.services.logs.model.DescribeLogStreamsRequest;
import com.amazonaws.services.logs.model.DescribeLogStreamsResult;
import com.amazonaws.services.logs.model.LogStream;
import java.util.Optional;

public class GetLatestLogStream {
    public static void main(String[] args) {
        // 替换为自身实际的凭证实例即可
        // AWSCredentials credentials = new BasicAWSCredentials("你的AccessKey", "你的SecretKey");
        
        AWSLogs awsLogs = AWSLogsClientBuilder
                .standard()
                // 若不需要硬编码凭证可删除此行,SDK会自动从环境变量、EC2实例角色等位置加载凭证
                // .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withRegion(Regions.EU_WEST_1)
                .build();

        String logGroupName = "/aws/lambda/a250348-ecndesc-conversion-lambda-reci-euw1-qe";
        DescribeLogStreamsRequest describeLogStreamsRequest = new DescribeLogStreamsRequest()
                .withLogGroupName(logGroupName)
                // 直接指定服务端按最后一次事件时间排序
                .withOrderBy("LastEventTime")
                // 倒序排列,第一条就是最新的流
                .withDescending(true)
                // 仅返回1条结果,减少冗余数据传输
                .withLimit(1);

        DescribeLogStreamsResult describeLogStreamsResult = awsLogs.describeLogStreams(describeLogStreamsRequest);
        Optional<LogStream> latestLogStreamOpt = describeLogStreamsResult.getLogStreams().stream().findFirst();
        
        if (latestLogStreamOpt.isPresent()) {
            LogStream latestLogStream = latestLogStreamOpt.get();
            String latestLogStreamName = latestLogStream.getLogStreamName();
            System.out.println("最新Log Stream名称:" + latestLogStreamName);
            // 如需获取最后事件时间可直接调用 latestLogStream.getLastEventTimestamp()
        } else {
            System.out.println("当前Log Group下无可用Log Stream");
        }
    }
}

优化说明

  • 解决分页问题:describeLogStreams 接口默认单次最多返回50条Log Stream,若Log Group下流数量超过50,未处理分页的代码仅能拿到第一页数据,筛选结果必然不准确。优化方案通过指定排序规则+单次拉取1条的方式,无需处理分页即可拿到全量数据中的最新流。
  • 提升运行效率:本地遍历所有返回的流、收集时间再做排序计算的方案性能损耗高。直接通过接口参数指定服务端排序,无需本地额外计算即可直接拿到目标结果。
  • 增强容错能力:未处理Log Group下无流的场景极易出现索引越界异常,优化方案通过Optional做判空处理,运行更稳定。

内容的提问来源于stack exchange,提问作者kaushik karuna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 03:54:03