上传日志到aws日志服务

安装包

        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>cloudwatchlogs</artifactId>
            <version>2.16.60</version>
        </dependency>

使用

        HashMap<String, Object> map = new HashMap<>();
        map.put("key1", "val1");
        map.put("key2", "val2");
        CloudWatchLog.putLog(map);

工具类

public class CloudWatchLog {
    private static final String accessKey = "<your key>";
    private static final String secretKey = "<your secret>";
    private static final String region = "us-west-1";
    // 日志组的名称
    private static final String groupName = "klover-test";
    // 日志流的名称
    private static final String streamName = "klover";

    private static CloudWatchLogsClient slsClient;

    static {
        AwsBasicCredentials credentials = AwsBasicCredentials.create(
                accessKey,
                secretKey
        );
        slsClient = CloudWatchLogsClient.builder()
                .region(Region.of(region))
                .credentialsProvider(() -> credentials)
                .build();
    }

    /**
     * 上传日志
     *
     * @param params 参数
     */
    public static void putLog(Map<String, Object> params) {
        DescribeLogStreamsRequest logStreamRequest = DescribeLogStreamsRequest.builder()
                .logGroupName(groupName)
                .logStreamNamePrefix(streamName)
                .build();

        DescribeLogStreamsResponse describeLogStreamsResponse = slsClient.describeLogStreams(logStreamRequest);

        // Assume that a single stream is returned since a specific stream name was
        // specified in the previous request.
        String sequenceToken = describeLogStreamsResponse.logStreams().getFirst().uploadSequenceToken();

        // Build an input log message to put to CloudWatch.
        InputLogEvent inputLogEvent = InputLogEvent.builder()
                .message(JsonUtil.toJSONString(params))
                .timestamp(System.currentTimeMillis())
                .build();

        // Specify the request parameters.
        // Sequence token is required so that the log can be written to the
        // latest location in the stream.
        PutLogEventsRequest putLogEventsRequest = PutLogEventsRequest.builder()
                .logEvents(Collections.singletonList(inputLogEvent))
                .logGroupName(groupName)
                .logStreamName(streamName)
                .sequenceToken(sequenceToken)
                .build();

        slsClient.putLogEvents(putLogEventsRequest);
    }
}

点击查看完整代码示例(觉得有用,帮忙在githup项目star一下)

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值