Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.
CloudWatch Log contoh menggunakan SDK untuk Java 2.x
Contoh kode berikut menunjukkan cara melakukan tindakan dan mengimplementasikan skenario umum dengan menggunakan AWS SDK for Java 2.x With CloudWatch Logs.
Tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Sementara tindakan menunjukkan cara memanggil fungsi layanan individual, Anda dapat melihat tindakan dalam konteks dalam skenario terkait.
Setiap contoh menyertakan tautan ke kode sumber lengkap, di mana Anda dapat menemukan instruksi tentang cara mengatur dan menjalankan kode dalam konteks.
Topik
Tindakan
Contoh kode berikut menunjukkan cara menggunakanDeleteSubscriptionFilter
.
- SDKuntuk Java 2.x
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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); } } }
-
Untuk API detailnya, lihat DeleteSubscriptionFilterdi AWS SDK for Java 2.x APIReferensi.
-
Contoh kode berikut menunjukkan cara menggunakanDescribeSubscriptionFilters
.
- SDKuntuk Java 2.x
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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"); } }
-
Untuk API detailnya, lihat DescribeSubscriptionFiltersdi AWS SDK for Java 2.x APIReferensi.
-
Contoh kode berikut menunjukkan cara menggunakanPutSubscriptionFilter
.
- SDKuntuk Java 2.x
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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); } } }
-
Untuk API detailnya, lihat PutSubscriptionFilterdi AWS SDK for Java 2.x APIReferensi.
-
Contoh kode berikut menunjukkan cara menggunakanStartLiveTail
.
- SDKuntuk Java 2.x
-
Sertakan file-file yang diperlukan.
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;
Tangani acara dari sesi 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(); }
Mulai sesi 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));
Hentikan sesi Live Tail setelah periode waktu berlalu.
/* 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"); }
-
Untuk API detailnya, lihat StartLiveTaildi AWS SDK for Java 2.x APIReferensi.
-