使用 CloudWatch for Java 2.x 的 SDK Logs 範例 - AWS SDK 程式碼範例

文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的 GitHub 範例。

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用 CloudWatch for Java 2.x 的 SDK Logs 範例

下列程式碼範例示範如何使用 AWS SDK for Java 2.x 搭配 CloudWatch Logs 來執行動作和實作常見案例。

Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會示範如何呼叫個別服務函數,但您可以在相關案例中查看內容中的動作。

每個範例都包含完整原始程式碼的連結,您可以在其中找到如何在內容中設定和執行程式碼的指示。

主題

動作

下列程式碼範例示範如何使用 DeleteSubscriptionFilter

Java 2.x 的 SDK
注意

還有更多 on 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); } } }

下列程式碼範例示範如何使用 DescribeSubscriptionFilters

Java 2.x 的 SDK
注意

還有更多 on 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"); } }

下列程式碼範例示範如何使用 PutSubscriptionFilter

Java 2.x 的 SDK
注意

還有更多 on 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); } } }

下列程式碼範例示範如何使用 StartLiveTail

Java 2.x 的 SDK

包括必需的檔案。

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 詳細資訊,請參閱 StartLiveTail AWS SDK for Java 2.x 參考中的 API