安装包
<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一下)