AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
CloudWatch 使用SDK适用于 Java 2.x 的日志示例
以下代码示例向您展示了如何使用 with Logs 来执行操作和实现常见场 CloudWatch 景。 AWS SDK for Java 2.x
操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景的上下文查看操作。
每个示例都包含一个指向完整源代码的链接,您可以在其中找到有关如何在上下文中设置和运行代码的说明。
主题
操作
以下代码示例演示如何使用 DeleteSubscriptionFilter
。
- SDK适用于 Java 2.x
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; import software.amazon.awssdk.services.cloudwatchlogs.model.DeleteSubscriptionFilterRequest; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DeleteSubscriptionFilter { public static void main(String[] args) { final String usage = """ Usage: <filter> <logGroup> Where: filter - The name of the subscription filter (for example, MyFilter). logGroup - The name of the log group. (for example, testgroup). """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String filter = args[0]; String logGroup = args[1]; CloudWatchLogsClient logs = CloudWatchLogsClient.builder() .build(); deleteSubFilter(logs, filter, logGroup); logs.close(); } public static void deleteSubFilter(CloudWatchLogsClient logs, String filter, String logGroup) { try { DeleteSubscriptionFilterRequest request = DeleteSubscriptionFilterRequest.builder() .filterName(filter) .logGroupName(logGroup) .build(); logs.deleteSubscriptionFilter(request); System.out.printf("Successfully deleted CloudWatch logs subscription filter %s", filter); } catch (CloudWatchException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
-
有关API详细信息,请参阅 “AWS SDK for Java 2.x API参考 DeleteSubscriptionFilter” 中的。
-
以下代码示例演示如何使用 DescribeSubscriptionFilters
。
- SDK适用于 Java 2.x
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeSubscriptionFiltersRequest; import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeSubscriptionFiltersResponse; import software.amazon.awssdk.services.cloudwatchlogs.model.SubscriptionFilter; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DescribeSubscriptionFilters { public static void main(String[] args) { final String usage = """ Usage: <logGroup> Where: logGroup - A log group name (for example, myloggroup). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String logGroup = args[0]; CloudWatchLogsClient logs = CloudWatchLogsClient.builder() .credentialsProvider(ProfileCredentialsProvider.create()) .build(); describeFilters(logs, logGroup); logs.close(); } public static void describeFilters(CloudWatchLogsClient logs, String logGroup) { try { boolean done = false; String newToken = null; while (!done) { DescribeSubscriptionFiltersResponse response; if (newToken == null) { DescribeSubscriptionFiltersRequest request = DescribeSubscriptionFiltersRequest.builder() .logGroupName(logGroup) .limit(1).build(); response = logs.describeSubscriptionFilters(request); } else { DescribeSubscriptionFiltersRequest request = DescribeSubscriptionFiltersRequest.builder() .nextToken(newToken) .logGroupName(logGroup) .limit(1).build(); response = logs.describeSubscriptionFilters(request); } for (SubscriptionFilter filter : response.subscriptionFilters()) { System.out.printf("Retrieved filter with name %s, " + "pattern %s " + "and destination arn %s", filter.filterName(), filter.filterPattern(), filter.destinationArn()); } if (response.nextToken() == null) { done = true; } else { newToken = response.nextToken(); } } } catch (CloudWatchException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } System.out.printf("Done"); } }
-
有关API详细信息,请参阅 “AWS SDK for Java 2.x API参考 DescribeSubscriptionFilters” 中的。
-
以下代码示例演示如何使用 PutSubscriptionFilter
。
- SDK适用于 Java 2.x
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; import software.amazon.awssdk.services.cloudwatchlogs.model.CloudWatchLogsException; import software.amazon.awssdk.services.cloudwatchlogs.model.PutSubscriptionFilterRequest; /** * Before running this code example, you need to grant permission to CloudWatch * Logs the right to execute your Lambda function. * To perform this task, you can use this CLI command: * * aws lambda add-permission --function-name "lamda1" --statement-id "lamda1" * --principal "logs.us-west-2.amazonaws.com" --action "lambda:InvokeFunction" * --source-arn "arn:aws:logs:us-west-2:111111111111:log-group:testgroup:*" * --source-account "111111111111" * * Make sure you replace the function name with your function name and replace * '111111111111' with your account details. * For more information, see "Subscription Filters with AWS Lambda" in the * Amazon CloudWatch Logs Guide. * * * Also, before running this Java V2 code example,set up your development * environment,including your credentials. * * For more information,see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * */ public class PutSubscriptionFilter { public static void main(String[] args) { final String usage = """ Usage: <filter> <pattern> <logGroup> <functionArn>\s Where: filter - A filter name (for example, myfilter). pattern - A filter pattern (for example, ERROR). logGroup - A log group name (testgroup). functionArn - An AWS Lambda function ARN (for example, arn:aws:lambda:us-west-2:111111111111:function:lambda1) . """; if (args.length != 4) { System.out.println(usage); System.exit(1); } String filter = args[0]; String pattern = args[1]; String logGroup = args[2]; String functionArn = args[3]; Region region = Region.US_WEST_2; CloudWatchLogsClient cwl = CloudWatchLogsClient.builder() .region(region) .build(); putSubFilters(cwl, filter, pattern, logGroup, functionArn); cwl.close(); } public static void putSubFilters(CloudWatchLogsClient cwl, String filter, String pattern, String logGroup, String functionArn) { try { PutSubscriptionFilterRequest request = PutSubscriptionFilterRequest.builder() .filterName(filter) .filterPattern(pattern) .logGroupName(logGroup) .destinationArn(functionArn) .build(); cwl.putSubscriptionFilter(request); System.out.printf( "Successfully created CloudWatch logs subscription filter %s", filter); } catch (CloudWatchLogsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
-
有关API详细信息,请参阅 “AWS SDK for Java 2.x API参考 PutSubscriptionFilter” 中的。
-
以下代码示例演示如何使用 StartLiveTail
。
- SDK适用于 Java 2.x
-
包含所需的文件。
import io.reactivex.FlowableSubscriber; import io.reactivex.annotations.NonNull; import org.reactivestreams.Subscription; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsAsyncClient; import software.amazon.awssdk.services.cloudwatchlogs.model.LiveTailSessionLogEvent; import software.amazon.awssdk.services.cloudwatchlogs.model.LiveTailSessionStart; import software.amazon.awssdk.services.cloudwatchlogs.model.LiveTailSessionUpdate; import software.amazon.awssdk.services.cloudwatchlogs.model.StartLiveTailRequest; import software.amazon.awssdk.services.cloudwatchlogs.model.StartLiveTailResponseHandler; import software.amazon.awssdk.services.cloudwatchlogs.model.CloudWatchLogsException; import software.amazon.awssdk.services.cloudwatchlogs.model.StartLiveTailResponseStream; import java.util.Date; import java.util.List; import java.util.concurrent.atomic.AtomicReference;
处理 Live Tail 会话中的事件。
private static StartLiveTailResponseHandler getStartLiveTailResponseStreamHandler( AtomicReference<Subscription> subscriptionAtomicReference) { return StartLiveTailResponseHandler.builder() .onResponse(r -> System.out.println("Received initial response")) .onError(throwable -> { CloudWatchLogsException e = (CloudWatchLogsException) throwable.getCause(); System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); }) .subscriber(() -> new FlowableSubscriber<>() { @Override public void onSubscribe(@NonNull Subscription s) { subscriptionAtomicReference.set(s); s.request(Long.MAX_VALUE); } @Override public void onNext(StartLiveTailResponseStream event) { if (event instanceof LiveTailSessionStart) { LiveTailSessionStart sessionStart = (LiveTailSessionStart) event; System.out.println(sessionStart); } else if (event instanceof LiveTailSessionUpdate) { LiveTailSessionUpdate sessionUpdate = (LiveTailSessionUpdate) event; List<LiveTailSessionLogEvent> logEvents = sessionUpdate.sessionResults(); logEvents.forEach(e -> { long timestamp = e.timestamp(); Date date = new Date(timestamp); System.out.println("[" + date + "] " + e.message()); }); } else { throw CloudWatchLogsException.builder().message("Unknown event type").build(); } } @Override public void onError(Throwable throwable) { System.out.println(throwable.getMessage()); System.exit(1); } @Override public void onComplete() { System.out.println("Completed Streaming Session"); } }) .build(); }
启动 Live Tail 会话。
CloudWatchLogsAsyncClient cloudWatchLogsAsyncClient = CloudWatchLogsAsyncClient.builder() .credentialsProvider(ProfileCredentialsProvider.create()) .build(); StartLiveTailRequest request = StartLiveTailRequest.builder() .logGroupIdentifiers(logGroupIdentifiers) .logStreamNames(logStreamNames) .logEventFilterPattern(logEventFilterPattern) .build(); /* Create a reference to store the subscription */ final AtomicReference<Subscription> subscriptionAtomicReference = new AtomicReference<>(null); cloudWatchLogsAsyncClient.startLiveTail(request, getStartLiveTailResponseStreamHandler(subscriptionAtomicReference));
经过一段时间后停止 Live Tail 会话。
/* Set a timeout for the session and cancel the subscription. This will: * 1). Close the stream * 2). Stop the Live Tail session */ try { Thread.sleep(10000); } catch (InterruptedException e) { throw new RuntimeException(e); } if (subscriptionAtomicReference.get() != null) { subscriptionAtomicReference.get().cancel(); System.out.println("Subscription to stream closed"); }
-
有关API详细信息,请参阅 “AWS SDK for Java 2.x API参考 StartLiveTail” 中的。
-