From caee933f10638d32e423f28a0113ccc52eac0243 Mon Sep 17 00:00:00 2001 From: Macdonald Date: Wed, 8 Oct 2025 17:20:40 -0400 Subject: [PATCH 1/5] added cloudlog examples in own project and own readme --- .../example_code/cloudwatch-logs/.gitignore | 38 ++++++ javav2/example_code/cloudwatch-logs/README.md | 82 +++++++++++++ javav2/example_code/cloudwatch-logs/pom.xml | 108 ++++++++++++++++++ .../com/example/logs/CloudWatchLogQuery.java | 88 ++++++++++++++ .../example/logs/CloudWatchLogsSearch.java | 97 ++++++++++++++++ .../logs/DeleteSubscriptionFilter.java | 63 ++++++++++ .../logs/DescribeSubscriptionFilters.java | 92 +++++++++++++++ .../com/example/logs/FilterLogEvents.java | 79 +++++++++++++ .../java/com/example/logs/GetLogEvents.java | 106 +++++++++++++++++ .../java/com/example/logs/PutLogEvents.java | 99 ++++++++++++++++ .../example/logs/PutSubscriptionFilter.java | 96 ++++++++++++++++ .../src/main/resources/log4j2.xml | 15 +++ .../src/test/java/CloudWatchLogsTest.java | 100 ++++++++++++++++ 13 files changed, 1063 insertions(+) create mode 100644 javav2/example_code/cloudwatch-logs/.gitignore create mode 100644 javav2/example_code/cloudwatch-logs/README.md create mode 100644 javav2/example_code/cloudwatch-logs/pom.xml create mode 100644 javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/CloudWatchLogQuery.java create mode 100644 javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/CloudWatchLogsSearch.java create mode 100644 javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/DeleteSubscriptionFilter.java create mode 100644 javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/DescribeSubscriptionFilters.java create mode 100644 javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/FilterLogEvents.java create mode 100644 javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/GetLogEvents.java create mode 100644 javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/PutLogEvents.java create mode 100644 javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/PutSubscriptionFilter.java create mode 100644 javav2/example_code/cloudwatch-logs/src/main/resources/log4j2.xml create mode 100644 javav2/example_code/cloudwatch-logs/src/test/java/CloudWatchLogsTest.java diff --git a/javav2/example_code/cloudwatch-logs/.gitignore b/javav2/example_code/cloudwatch-logs/.gitignore new file mode 100644 index 00000000000..5ff6309b719 --- /dev/null +++ b/javav2/example_code/cloudwatch-logs/.gitignore @@ -0,0 +1,38 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/javav2/example_code/cloudwatch-logs/README.md b/javav2/example_code/cloudwatch-logs/README.md new file mode 100644 index 00000000000..496f4481f59 --- /dev/null +++ b/javav2/example_code/cloudwatch-logs/README.md @@ -0,0 +1,82 @@ +# CloudWatch Logs code examples for the SDK for Java 2.x + +## Overview + +Shows how to use the AWS SDK for Java 2.x to work with Amazon CloudWatch Logs. + + + + +_CloudWatch Logs monitor, store, and access your log files from Amazon Elastic Compute Cloud instances, AWS CloudTrail, or other sources._ + +## ⚠ Important + +* Running this code might result in charges to your AWS account. For more details, see [AWS Pricing](https://aws.amazon.com/pricing/) and [Free Tier](https://aws.amazon.com/free/). +* Running the tests might result in charges to your AWS account. +* We recommend that you grant your code least privilege. At most, grant only the minimum permissions required to perform the task. For more information, see [Grant least privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege). +* This code is not tested in every AWS Region. For more information, see [AWS Regional Services](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services). + + + + +## Code examples + +### Prerequisites + +For prerequisites, see the [README](../../README.md#Prerequisites) in the `javav2` folder. + + + + + +### Single actions + +Code excerpts that show you how to call individual service functions. + +- [DeleteSubscriptionFilter](src/main/java/com/example/logs/DeleteSubscriptionFilter.java#L6) +- [DescribeLogStreams](src/main/java/com/example/logs/CloudWatchLogsSearch.java#L18) +- [DescribeSubscriptionFilters](src/main/java/com/example/logs/DescribeSubscriptionFilters.java#L6) +- [GetLogEvents](src/main/java/com/example/logs/GetLogEvents.java#L6) +- [PutSubscriptionFilter](src/main/java/com/example/logs/PutSubscriptionFilter.java#L6) + + + + + +## Run the examples + +### Instructions + + + + + + + +### Tests + +⚠ Running tests might result in charges to your AWS account. + + +To find instructions for running these tests, see the [README](../../README.md#Tests) +in the `javav2` folder. + + + + + + +## Additional resources + +- [CloudWatch Logs User Guide](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html) +- [CloudWatch Logs API Reference](https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/Welcome.html) +- [SDK for Java 2.x CloudWatch Logs reference](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/cloudwatch-logs/package-summary.html) + + + + +--- + +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: Apache-2.0 diff --git a/javav2/example_code/cloudwatch-logs/pom.xml b/javav2/example_code/cloudwatch-logs/pom.xml new file mode 100644 index 00000000000..2a37361f6ac --- /dev/null +++ b/javav2/example_code/cloudwatch-logs/pom.xml @@ -0,0 +1,108 @@ + + + 4.0.0 + + org.example + cloudwatch_logs + 1.0-SNAPSHOT + + + UTF-8 + 21 + 21 + 21 + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.2 + + + + + + + software.amazon.awssdk + bom + 2.31.8 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 + pom + import + + + + + + org.junit.jupiter + junit-jupiter + 5.11.4 + test + + + com.fasterxml.jackson.core + jackson-core + 2.14.2 + + + software.amazon.awssdk + secretsmanager + + + com.google.code.gson + gson + 2.10.1 + + + com.fasterxml.jackson.core + jackson-databind + 2.14.2 + + + software.amazon.awssdk + cloudwatch + + + software.amazon.awssdk + cloudwatchlogs + + + software.amazon.awssdk + sso + + + software.amazon.awssdk + ssooidc + + + org.apache.logging.log4j + log4j-core + + + software.amazon.awssdk + netty-nio-client + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + + + \ No newline at end of file diff --git a/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/CloudWatchLogQuery.java b/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/CloudWatchLogQuery.java new file mode 100644 index 00000000000..ab56d903792 --- /dev/null +++ b/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/CloudWatchLogQuery.java @@ -0,0 +1,88 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + + +package com.example.logs; + +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.DescribeLogStreamsRequest; +import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsResponse; +import software.amazon.awssdk.services.cloudwatchlogs.model.LogStream; +import software.amazon.awssdk.services.cloudwatchlogs.model.OrderBy; + +import java.util.List; + +// snippet-start:[cloudwatch.javav2.describe.log.streams.main] + +/** + * 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 CloudWatchLogQuery { + public static void main(final String[] args) { + final String usage = """ + Usage: + + + Where: + logGroupName - The name of the log group (for example, /aws/lambda/ChatAIHandler). + """; + + if (args.length != 1) { + System.out.print(usage); + System.exit(1); + } + + String logGroupName = "/aws/lambda/ChatAIHandler" ; //args[0]; + CloudWatchLogsClient logsClient = CloudWatchLogsClient.builder() + .region(Region.US_EAST_1) + .build(); + + describeMostRecentLogStream(logsClient, logGroupName); + } + + /** + * Describes and prints metadata about the most recent log stream in the specified log group. + * + * @param logsClient the CloudWatchLogsClient used to interact with AWS CloudWatch Logs + * @param logGroupName the name of the log group + */ + public static void describeMostRecentLogStream(CloudWatchLogsClient logsClient, String logGroupName) { + DescribeLogStreamsRequest streamsRequest = DescribeLogStreamsRequest.builder() + .logGroupName(logGroupName) + .orderBy(OrderBy.LAST_EVENT_TIME) + .descending(true) + .limit(1) + .build(); + + try { + DescribeLogStreamsResponse streamsResponse = logsClient.describeLogStreams(streamsRequest); + List logStreams = streamsResponse.logStreams(); + + if (logStreams.isEmpty()) { + System.out.println("No log streams found for log group: " + logGroupName); + return; + } + + LogStream stream = logStreams.get(0); + System.out.println("Most Recent Log Stream:"); + System.out.println(" Name: " + stream.logStreamName()); + System.out.println(" ARN: " + stream.arn()); + System.out.println(" Creation Time: " + stream.creationTime()); + System.out.println(" First Event Time: " + stream.firstEventTimestamp()); + System.out.println(" Last Event Time: " + stream.lastEventTimestamp()); + System.out.println(" Stored Bytes: " + stream.storedBytes()); + System.out.println(" Upload Sequence Token: " + stream.uploadSequenceToken()); + + } catch (CloudWatchLogsException e) { + System.err.println("Failed to describe log stream: " + e.awsErrorDetails().errorMessage()); + } + } +} +// snippet-end:[cloudwatch.javav2.describe.log.streams.main] \ No newline at end of file diff --git a/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/CloudWatchLogsSearch.java b/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/CloudWatchLogsSearch.java new file mode 100644 index 00000000000..132a249e8fa --- /dev/null +++ b/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/CloudWatchLogsSearch.java @@ -0,0 +1,97 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.logs; + +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; +import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsRequest; +import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsResponse; +import software.amazon.awssdk.services.cloudwatchlogs.model.FilterLogEventsRequest; +import software.amazon.awssdk.services.cloudwatchlogs.model.FilterLogEventsResponse; +import software.amazon.awssdk.services.cloudwatchlogs.model.FilteredLogEvent; +import software.amazon.awssdk.services.cloudwatchlogs.model.LogStream; + +import java.util.List; + + +// snippet-start:[cloudwatch.javav2.read.log.streams.main] + +/** + * 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 CloudWatchLogsSearch { + + public static void main(String[] args) { + final String usage = """ + + Usage: + + + Where: + logGroupName - The name of the log group (for example, WeathertopJavaContainerLogs). + logStreamName - The name of the log stream (for example, weathertop-java-stream). + pattern - the pattern to use (for example, INFO) + + """; + + if (args.length != 3) { + System.out.print(usage); + System.exit(1); + } + + String logGroupName = args[0] ; + String logStreamName = args[1] ; + String pattern = args[2] ; + + CloudWatchLogsClient cwlClient = CloudWatchLogsClient.builder() + .region(Region.US_EAST_1) + .build(); + + searchLogStreamsAndFilterEvents(cwlClient, logGroupName, logStreamName, pattern); + } + + /** + * Searches for log streams with a specific prefix within a log group and filters log events based on a specified pattern. + * + * @param cwlClient the CloudWatchLogsClient used to interact with AWS CloudWatch Logs + * @param logGroupName the name of the log group to search within + * @param logStreamPrefix the prefix of the log streams to search for + * @param pattern the pattern to filter log events by + */ + public static void searchLogStreamsAndFilterEvents(CloudWatchLogsClient cwlClient, String logGroupName, String logStreamPrefix, String pattern) { + DescribeLogStreamsRequest describeLogStreamsRequest = DescribeLogStreamsRequest.builder() + .logGroupName(logGroupName) + .logStreamNamePrefix(logStreamPrefix) + .build(); + + DescribeLogStreamsResponse describeLogStreamsResponse = cwlClient.describeLogStreams(describeLogStreamsRequest); + + List logStreams = describeLogStreamsResponse.logStreams(); + + for (LogStream logStream : logStreams) { + String logStreamName = logStream.logStreamName(); + System.out.println("Searching in log stream: " + logStreamName); + + FilterLogEventsRequest filterLogEventsRequest = FilterLogEventsRequest.builder() + .logGroupName(logGroupName) + .logStreamNames(logStreamName) + .filterPattern(pattern) + .build(); + + FilterLogEventsResponse filterLogEventsResponse = cwlClient.filterLogEvents(filterLogEventsRequest); + + for (FilteredLogEvent event : filterLogEventsResponse.events()) { + System.out.println(event.message()); + } + + System.out.println("--------------------------------------------------"); // Separator for better readability + } + } +} +// snippet-end:[cloudwatch.javav2.read.log.streams.main] \ No newline at end of file diff --git a/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/DeleteSubscriptionFilter.java b/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/DeleteSubscriptionFilter.java new file mode 100644 index 00000000000..48ae6ba5994 --- /dev/null +++ b/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/DeleteSubscriptionFilter.java @@ -0,0 +1,63 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.logs; + +// snippet-start:[cloudwatch.java2.delete_subscription_filter.main] +// snippet-start:[cloudwatch.java2.delete_subscription_filter.import] +import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; +import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; +import software.amazon.awssdk.services.cloudwatchlogs.model.DeleteSubscriptionFilterRequest; +// snippet-end:[cloudwatch.java2.delete_subscription_filter.import] + +/** + * 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: + + + 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); + } + } +} +// snippet-end:[cloudwatch.java2.delete_subscription_filter.main] diff --git a/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/DescribeSubscriptionFilters.java b/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/DescribeSubscriptionFilters.java new file mode 100644 index 00000000000..d71d35b7cb5 --- /dev/null +++ b/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/DescribeSubscriptionFilters.java @@ -0,0 +1,92 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.logs; + +// snippet-start:[cloudwatch.java2.describe_subscription_filters.main] +// snippet-start:[cloudwatch.java2.describe_subscription_filters.import] +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; +// snippet-end:[cloudwatch.java2.describe_subscription_filters.import] + +/** + * 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: + + + 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"); + } +} +// snippet-end:[cloudwatch.java2.describe_subscription_filters.main] diff --git a/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/FilterLogEvents.java b/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/FilterLogEvents.java new file mode 100644 index 00000000000..56a74493481 --- /dev/null +++ b/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/FilterLogEvents.java @@ -0,0 +1,79 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.logs; + +// snippet-start:[cloudwatch.java2.filter_logs.main] +// snippet-start:[cloudwatch.java2.filter_logs.import] + +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; +import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; +import software.amazon.awssdk.services.cloudwatchlogs.model.FilterLogEventsRequest; +import software.amazon.awssdk.services.cloudwatchlogs.model.FilteredLogEvent; + +import java.util.List; +// snippet-end:[cloudwatch.java2.filter_logs.import] + +/** + * 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 FilterLogEvents { + public static void main(String[] args) { + + final String usage = """ + + Usage: + + + Where: + logGroupName - The name of the log group (for example, myloggroup). + startTime - The start of the time range, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC (for example, 1620940080). + endTime - The end of the time range, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC (for example, 1620949080) + """; + + if (args.length != 3) { + System.out.print(usage); + System.exit(1); + } + + String logGroupName = args[0]; + Long startTime = Long.parseLong(args[1]); + Long endTime = Long.parseLong(args[2]); + Region region = Region.US_WEST_2; + CloudWatchLogsClient cloudWatchLogsClient = CloudWatchLogsClient.builder() + .region(region) + .build(); + + filterCWLogEvents(cloudWatchLogsClient, logGroupName, startTime, endTime); + cloudWatchLogsClient.close(); + } + + public static void filterCWLogEvents(CloudWatchLogsClient cloudWatchLogsClient, String logGroupName, Long startTime, + Long endTime) { + try { + FilterLogEventsRequest filterLogEventsRequest = FilterLogEventsRequest.builder() + .logGroupName(logGroupName) + .startTime(startTime) + .endTime(endTime) + .build(); + + List events = cloudWatchLogsClient.filterLogEvents(filterLogEventsRequest).events(); + for (FilteredLogEvent event : events) { + System.out.println(event.message()); + } + + System.out.println("Successfully got CloudWatch log events!"); + + } catch (CloudWatchException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[cloudwatch.java2.filter_logs.main] diff --git a/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/GetLogEvents.java b/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/GetLogEvents.java new file mode 100644 index 00000000000..e044de998c1 --- /dev/null +++ b/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/GetLogEvents.java @@ -0,0 +1,106 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.logs; + +// snippet-start:[cloudwatch.java2.get_logs.main] +// snippet-start:[cloudwatch.java2.get_logs.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; +import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; +import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsRequest; +import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsResponse; +import software.amazon.awssdk.services.cloudwatchlogs.model.GetLogEventsRequest; +import software.amazon.awssdk.services.cloudwatchlogs.model.GetLogEventsResponse; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +// snippet-end:[cloudwatch.java2.get_logs.import] + +/** + * 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 GetLogEvents { + + public static void main(String[] args) { + + final String usage = """ + + Usage: + + + Where: + logGroupName - The name of the log group (for example, myloggroup). + logStreamName - The name of the log stream (for example, mystream). + + """; + + // if (args.length != 2) { + // System.out.print(usage); + // System.exit(1); +// } + + String logGroupName = "WeathertopJavaContainerLogs" ; //args[0]; + String logStreamName = "weathertop-java-stream" ; //args[1]; + + Region region = Region.US_EAST_1 ; + CloudWatchLogsClient cloudWatchLogsClient = CloudWatchLogsClient.builder() + .region(region) + .build(); + + getCWLogEvents(cloudWatchLogsClient, logGroupName, logStreamName); + cloudWatchLogsClient.close(); + } + + public static void getCWLogEvents(CloudWatchLogsClient cloudWatchLogsClient, + String logGroupName, + String logStreamPrefix) { + try { + // First, find the exact log stream name + DescribeLogStreamsRequest describeRequest = DescribeLogStreamsRequest.builder() + .logGroupName(logGroupName) + .logStreamNamePrefix(logStreamPrefix) + .limit(1) // get the first matching stream + .build(); + + DescribeLogStreamsResponse describeResponse = cloudWatchLogsClient.describeLogStreams(describeRequest); + + if (describeResponse.logStreams().isEmpty()) { + System.out.println("No matching log streams found for prefix: " + logStreamPrefix); + return; + } + + String exactLogStreamName = describeResponse.logStreams().get(0).logStreamName(); + System.out.println("Using exact log stream: " + exactLogStreamName); + + long startTime = Instant.now().minus(7, ChronoUnit.DAYS).toEpochMilli(); + long endTime = Instant.now().toEpochMilli(); + + GetLogEventsRequest getLogEventsRequest = GetLogEventsRequest.builder() + .logGroupName(logGroupName) + .logStreamName(exactLogStreamName) // <-- exact name, not prefix + .startTime(startTime) + .endTime(endTime) + .startFromHead(true) + .build(); + + GetLogEventsResponse response = cloudWatchLogsClient.getLogEvents(getLogEventsRequest); + + if (response.events().isEmpty()) { + System.out.println("No log events found in the past 7 days."); + } else { + response.events().forEach(e -> System.out.println(e.message())); + } + + } catch (CloudWatchException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[cloudwatch.java2.get_logs.main] diff --git a/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/PutLogEvents.java b/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/PutLogEvents.java new file mode 100644 index 00000000000..2c1efed8e51 --- /dev/null +++ b/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/PutLogEvents.java @@ -0,0 +1,99 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.logs; + +// snippet-start:[cloudwatch.java2.put_log_events.main] +// snippet-start:[cloudwatch.java2.put_log_events.import] + +import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; +import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; +import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsRequest; +import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsResponse; +import software.amazon.awssdk.services.cloudwatchlogs.model.InputLogEvent; +import software.amazon.awssdk.services.cloudwatchlogs.model.PutLogEventsRequest; + +import java.util.Arrays; +import java.util.Collections; +// snippet-end:[cloudwatch.java2.put_log_events.import] + +/** + * 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 PutLogEvents { + public static void main(String[] args) { + final String usage = """ + + Usage: + + + Where: + logGroupName - A log group name. + streamName - A stream name. + """; + + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } + + String logGroupName = args[0]; + String streamName = args[1]; + CloudWatchLogsClient logsClient = CloudWatchLogsClient.builder() + .build(); + + putCWLogEvents(logsClient, logGroupName, streamName); + logsClient.close(); + } + + public static void putCWLogEvents(CloudWatchLogsClient logsClient, String logGroupName, String streamNamePrefix) { + try { + // First resolve the exact log stream name + DescribeLogStreamsRequest logStreamRequest = DescribeLogStreamsRequest.builder() + .logGroupName(logGroupName) + .logStreamNamePrefix(streamNamePrefix) + .limit(1) // get the first matching stream + .build(); + + DescribeLogStreamsResponse describeLogStreamsResponse = logsClient.describeLogStreams(logStreamRequest); + + if (describeLogStreamsResponse.logStreams().isEmpty()) { + System.err.println("No matching log stream found for prefix: " + streamNamePrefix); + return; + } + + String exactStreamName = describeLogStreamsResponse.logStreams().get(0).logStreamName(); + String sequenceToken = describeLogStreamsResponse.logStreams().get(0).uploadSequenceToken(); + + // Build an input log message to put to CloudWatch. + InputLogEvent inputLogEvent = InputLogEvent.builder() + .message("{ \"key1\": \"value1\", \"key2\": \"value2\" }") + .timestamp(System.currentTimeMillis()) + .build(); + + PutLogEventsRequest.Builder putLogEventsBuilder = PutLogEventsRequest.builder() + .logEvents(Collections.singletonList(inputLogEvent)) + .logGroupName(logGroupName) + .logStreamName(exactStreamName); + + // Only set sequenceToken if it exists + if (sequenceToken != null) { + putLogEventsBuilder.sequenceToken(sequenceToken); + } + + logsClient.putLogEvents(putLogEventsBuilder.build()); + System.out.println("Successfully put CloudWatch log event to stream: " + exactStreamName); + + } catch (CloudWatchException e) { + System.err.println("CloudWatch error: " + e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + +} +// snippet-end:[cloudwatch.java2.put_log_events.main] diff --git a/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/PutSubscriptionFilter.java b/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/PutSubscriptionFilter.java new file mode 100644 index 00000000000..0ab511e6d32 --- /dev/null +++ b/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/PutSubscriptionFilter.java @@ -0,0 +1,96 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.logs; + +// snippet-start:[cloudwatch.java2.put_subscription_filter.main] +// snippet-start:[cloudwatch.java2.put_subscription_filter.import] +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; +// snippet-end:[cloudwatch.java2.put_subscription_filter.import] + +/** + * 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: + \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); + } + } +} +// snippet-end:[cloudwatch.java2.put_subscription_filter.main] diff --git a/javav2/example_code/cloudwatch-logs/src/main/resources/log4j2.xml b/javav2/example_code/cloudwatch-logs/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..4d900326937 --- /dev/null +++ b/javav2/example_code/cloudwatch-logs/src/main/resources/log4j2.xml @@ -0,0 +1,15 @@ + + + + + + %msg%n + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/cloudwatch-logs/src/test/java/CloudWatchLogsTest.java b/javav2/example_code/cloudwatch-logs/src/test/java/CloudWatchLogsTest.java new file mode 100644 index 00000000000..68219981f79 --- /dev/null +++ b/javav2/example_code/cloudwatch-logs/src/test/java/CloudWatchLogsTest.java @@ -0,0 +1,100 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import com.example.logs.CloudWatchLogQuery; +import com.example.logs.CloudWatchLogsSearch; +import com.example.logs.DescribeSubscriptionFilters; +import com.example.logs.FilterLogEvents; +import com.example.logs.GetLogEvents; +import com.example.logs.PutLogEvents; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.TestMethodOrder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudwatch.CloudWatchClient; +import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; + +import java.io.IOException; +import java.time.Instant; +import java.time.temporal.ChronoUnit; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +@TestInstance(TestInstance.Lifecycle.PER_METHOD) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +public class CloudWatchLogsTest { + private static final Logger logger = LoggerFactory.getLogger(CloudWatchLogsTest.class); + private static CloudWatchLogsClient logsClient; + + private static String logGroupName = ""; + private static String logStreamName = ""; + private static String pattern = ""; + + + @BeforeAll + public static void setUp() throws IOException { + logsClient = CloudWatchLogsClient.builder() + .region(Region.US_EAST_1) + .build(); + + logGroupName = "WeathertopJavaContainerLogs"; + logStreamName = "weathertop-java-stream"; + pattern = "INFO"; + } + + @Test + @Tag("IntegrationTest") + @Order(1) + public void testSearchLogStreams() { + assertDoesNotThrow(() -> CloudWatchLogsSearch.searchLogStreamsAndFilterEvents(logsClient, logGroupName, logStreamName, pattern)); + logger.info(" Test 1 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(2) + public void testDescribeMostRecent() { + assertDoesNotThrow(() -> CloudWatchLogQuery.describeMostRecentLogStream(logsClient, logGroupName)); + logger.info(" Test 2 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(3) + public void testDescribeSubscriptionFilters() { + assertDoesNotThrow(() -> DescribeSubscriptionFilters.describeFilters(logsClient, logGroupName)); + logger.info(" Test 3 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(4) + public void testterFilterLogEvents() { + Long startTime = Instant.now().minus(7, ChronoUnit.DAYS).toEpochMilli(); + Long endTime = Instant.now().toEpochMilli(); + assertDoesNotThrow(() -> FilterLogEvents.filterCWLogEvents(logsClient, logGroupName, startTime, endTime)); + logger.info(" Test 4 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(5) + public void testGetCWLogEvents() { + assertDoesNotThrow(() -> GetLogEvents.getCWLogEvents(logsClient, logGroupName, logStreamName)); + logger.info(" Test 5 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(6) + public void testputCWLogEvents() { + assertDoesNotThrow(() -> PutLogEvents.putCWLogEvents(logsClient, logGroupName, logStreamName)); + logger.info(" Test 6 passed"); + } +} From ff7511dab7377d4eb6407dd6cd8376d83a360391 Mon Sep 17 00:00:00 2001 From: Macdonald Date: Wed, 8 Oct 2025 17:48:34 -0400 Subject: [PATCH 2/5] removed Cloudwatch-log examples from CloudWatch --- javav2/example_code/cloudwatch-logs/README.md | 2 +- .../cloudwatch/CloudWatchLogQuery.java | 89 ----------------- .../cloudwatch/DeleteSubscriptionFilter.java | 63 ------------ .../DescribeSubscriptionFilters.java | 92 ------------------ .../example/cloudwatch/FilterLogEvents.java | 77 --------------- .../com/example/cloudwatch/GetLogEvents.java | 77 --------------- .../com/example/cloudwatch/PutLogEvents.java | 88 ----------------- .../cloudwatch/PutSubscriptionFilter.java | 96 ------------------- 8 files changed, 1 insertion(+), 583 deletions(-) delete mode 100644 javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/CloudWatchLogQuery.java delete mode 100644 javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DeleteSubscriptionFilter.java delete mode 100644 javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DescribeSubscriptionFilters.java delete mode 100644 javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/FilterLogEvents.java delete mode 100644 javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/GetLogEvents.java delete mode 100644 javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutLogEvents.java delete mode 100644 javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutSubscriptionFilter.java diff --git a/javav2/example_code/cloudwatch-logs/README.md b/javav2/example_code/cloudwatch-logs/README.md index 496f4481f59..bd3e423be66 100644 --- a/javav2/example_code/cloudwatch-logs/README.md +++ b/javav2/example_code/cloudwatch-logs/README.md @@ -34,7 +34,7 @@ For prerequisites, see the [README](../../README.md#Prerequisites) in the `javav Code excerpts that show you how to call individual service functions. - [DeleteSubscriptionFilter](src/main/java/com/example/logs/DeleteSubscriptionFilter.java#L6) -- [DescribeLogStreams](src/main/java/com/example/logs/CloudWatchLogsSearch.java#L18) +- [DescribeLogStreams](src/main/java/com/example/logs/CloudWatchLogQuery.java#L17) - [DescribeSubscriptionFilters](src/main/java/com/example/logs/DescribeSubscriptionFilters.java#L6) - [GetLogEvents](src/main/java/com/example/logs/GetLogEvents.java#L6) - [PutSubscriptionFilter](src/main/java/com/example/logs/PutSubscriptionFilter.java#L6) diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/CloudWatchLogQuery.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/CloudWatchLogQuery.java deleted file mode 100644 index 034f3b40a30..00000000000 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/CloudWatchLogQuery.java +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - - -package com.example.cloudwatch; - -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.DescribeLogStreamsRequest; -import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsResponse; -import software.amazon.awssdk.services.cloudwatchlogs.model.GetLogEventsRequest; -import software.amazon.awssdk.services.cloudwatchlogs.model.GetLogEventsResponse; -import software.amazon.awssdk.services.cloudwatchlogs.model.LogStream; -import software.amazon.awssdk.services.cloudwatchlogs.model.OrderBy; -import software.amazon.awssdk.services.cloudwatchlogs.model.OutputLogEvent; -import java.util.List; - -// snippet-start:[cloudwatch.javav2.describe.log.streams.main] -/** - * 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 CloudWatchLogQuery { - public static void main(final String[] args) { - final String usage = """ - Usage: - - - Where: - logGroupName - The name of the log group (for example, /aws/lambda/ChatAIHandler). - """; - - if (args.length != 1) { - System.out.print(usage); - System.exit(1); - } - - String logGroupName = "/aws/lambda/ChatAIHandler" ; //args[0]; - CloudWatchLogsClient logsClient = CloudWatchLogsClient.builder() - .region(Region.US_EAST_1) - .build(); - - describeMostRecentLogStream(logsClient, logGroupName); - } - - /** - * Describes and prints metadata about the most recent log stream in the specified log group. - * - * @param logsClient the CloudWatchLogsClient used to interact with AWS CloudWatch Logs - * @param logGroupName the name of the log group - */ - public static void describeMostRecentLogStream(CloudWatchLogsClient logsClient, String logGroupName) { - DescribeLogStreamsRequest streamsRequest = DescribeLogStreamsRequest.builder() - .logGroupName(logGroupName) - .orderBy(OrderBy.LAST_EVENT_TIME) - .descending(true) - .limit(1) - .build(); - - try { - DescribeLogStreamsResponse streamsResponse = logsClient.describeLogStreams(streamsRequest); - List logStreams = streamsResponse.logStreams(); - - if (logStreams.isEmpty()) { - System.out.println("No log streams found for log group: " + logGroupName); - return; - } - - LogStream stream = logStreams.get(0); - System.out.println("Most Recent Log Stream:"); - System.out.println(" Name: " + stream.logStreamName()); - System.out.println(" ARN: " + stream.arn()); - System.out.println(" Creation Time: " + stream.creationTime()); - System.out.println(" First Event Time: " + stream.firstEventTimestamp()); - System.out.println(" Last Event Time: " + stream.lastEventTimestamp()); - System.out.println(" Stored Bytes: " + stream.storedBytes()); - System.out.println(" Upload Sequence Token: " + stream.uploadSequenceToken()); - - } catch (CloudWatchLogsException e) { - System.err.println("Failed to describe log stream: " + e.awsErrorDetails().errorMessage()); - } - } -} -// snippet-end:[cloudwatch.javav2.describe.log.streams.main] \ No newline at end of file diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DeleteSubscriptionFilter.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DeleteSubscriptionFilter.java deleted file mode 100644 index 787c930d5b2..00000000000 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DeleteSubscriptionFilter.java +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.cloudwatch; - -// snippet-start:[cloudwatch.java2.delete_subscription_filter.main] -// snippet-start:[cloudwatch.java2.delete_subscription_filter.import] -import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; -import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; -import software.amazon.awssdk.services.cloudwatchlogs.model.DeleteSubscriptionFilterRequest; -// snippet-end:[cloudwatch.java2.delete_subscription_filter.import] - -/** - * 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: - - - 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); - } - } -} -// snippet-end:[cloudwatch.java2.delete_subscription_filter.main] diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DescribeSubscriptionFilters.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DescribeSubscriptionFilters.java deleted file mode 100644 index 00debca652f..00000000000 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DescribeSubscriptionFilters.java +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.cloudwatch; - -// snippet-start:[cloudwatch.java2.describe_subscription_filters.main] -// snippet-start:[cloudwatch.java2.describe_subscription_filters.import] -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; -// snippet-end:[cloudwatch.java2.describe_subscription_filters.import] - -/** - * 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: - - - 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"); - } -} -// snippet-end:[cloudwatch.java2.describe_subscription_filters.main] diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/FilterLogEvents.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/FilterLogEvents.java deleted file mode 100644 index cb28c7824c3..00000000000 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/FilterLogEvents.java +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.cloudwatch; - -// snippet-start:[cloudwatch.java2.filter_logs.main] -// snippet-start:[cloudwatch.java2.filter_logs.import] -import java.util.List; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; -import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; -import software.amazon.awssdk.services.cloudwatchlogs.model.FilterLogEventsRequest; -import software.amazon.awssdk.services.cloudwatchlogs.model.FilteredLogEvent; -// snippet-end:[cloudwatch.java2.filter_logs.import] - -/** - * 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 FilterLogEvents { - public static void main(String[] args) { - - final String usage = """ - - Usage: - - - Where: - logGroupName - The name of the log group (for example, myloggroup). - startTime - The start of the time range, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC (for example, 1620940080). - endTime - The end of the time range, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC (for example, 1620949080) - """; - - if (args.length != 3) { - System.out.print(usage); - System.exit(1); - } - - String logGroupName = args[0]; - Long startTime = Long.parseLong(args[1]); - Long endTime = Long.parseLong(args[2]); - Region region = Region.US_WEST_2; - CloudWatchLogsClient cloudWatchLogsClient = CloudWatchLogsClient.builder() - .region(region) - .build(); - - filterCWLogEvents(cloudWatchLogsClient, logGroupName, startTime, endTime); - cloudWatchLogsClient.close(); - } - - public static void filterCWLogEvents(CloudWatchLogsClient cloudWatchLogsClient, String logGroupName, Long startTime, - Long endTime) { - try { - FilterLogEventsRequest filterLogEventsRequest = FilterLogEventsRequest.builder() - .logGroupName(logGroupName) - .startTime(startTime) - .endTime(endTime) - .build(); - - List events = cloudWatchLogsClient.filterLogEvents(filterLogEventsRequest).events(); - for (FilteredLogEvent event : events) { - System.out.println(event.message()); - } - - System.out.println("Successfully got CloudWatch log events!"); - - } catch (CloudWatchException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[cloudwatch.java2.filter_logs.main] diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/GetLogEvents.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/GetLogEvents.java deleted file mode 100644 index ab51aedaf95..00000000000 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/GetLogEvents.java +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.cloudwatch; - -// snippet-start:[cloudwatch.java2.get_logs.main] -// snippet-start:[cloudwatch.java2.get_logs.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; -import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; -import software.amazon.awssdk.services.cloudwatchlogs.model.GetLogEventsRequest; -// snippet-end:[cloudwatch.java2.get_logs.import] - -/** - * 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 GetLogEvents { - - public static void main(String[] args) { - - final String usage = """ - - Usage: - - - Where: - logGroupName - The name of the log group (for example, myloggroup). - logStreamName - The name of the log stream (for example, mystream). - - """; - - if (args.length != 2) { - System.out.print(usage); - System.exit(1); - - } - - String logGroupName = args[0]; - String logStreamName = args[1]; - - Region region = Region.US_WEST_2; - CloudWatchLogsClient cloudWatchLogsClient = CloudWatchLogsClient.builder() - .region(region) - .build(); - - getCWLogEvents(cloudWatchLogsClient, logGroupName, logStreamName); - cloudWatchLogsClient.close(); - } - - public static void getCWLogEvents(CloudWatchLogsClient cloudWatchLogsClient, String logGroupName, - String logStreamName) { - try { - GetLogEventsRequest getLogEventsRequest = GetLogEventsRequest.builder() - .logGroupName(logGroupName) - .logStreamName(logStreamName) - .startFromHead(true) - .build(); - - int logLimit = cloudWatchLogsClient.getLogEvents(getLogEventsRequest).events().size(); - for (int c = 0; c < logLimit; c++) { - System.out.println(cloudWatchLogsClient.getLogEvents(getLogEventsRequest).events().get(c).message()); - } - - System.out.println("Successfully got CloudWatch log events!"); - - } catch (CloudWatchException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[cloudwatch.java2.get_logs.main] diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutLogEvents.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutLogEvents.java deleted file mode 100644 index 3f3b06ff861..00000000000 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutLogEvents.java +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.cloudwatch; - -// snippet-start:[cloudwatch.java2.put_log_events.main] -// snippet-start:[cloudwatch.java2.put_log_events.import] -import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; -import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; -import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsRequest; -import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsResponse; -import software.amazon.awssdk.services.cloudwatchlogs.model.InputLogEvent; -import software.amazon.awssdk.services.cloudwatchlogs.model.PutLogEventsRequest; -import java.util.Arrays; -// snippet-end:[cloudwatch.java2.put_log_events.import] - -/** - * 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 PutLogEvents { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - logGroupName - A log group name. - streamName - A stream name. - """; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } - - String logGroupName = args[0]; - String streamName = args[1]; - CloudWatchLogsClient logsClient = CloudWatchLogsClient.builder() - .build(); - - putCWLogEvents(logsClient, logGroupName, streamName); - logsClient.close(); - } - - public static void putCWLogEvents(CloudWatchLogsClient logsClient, String logGroupName, String streamName) { - try { - DescribeLogStreamsRequest logStreamRequest = DescribeLogStreamsRequest.builder() - .logGroupName(logGroupName) - .logStreamNamePrefix(streamName) - .build(); - DescribeLogStreamsResponse describeLogStreamsResponse = logsClient.describeLogStreams(logStreamRequest); - - // Assume that a single stream is returned since a specific stream name was - // specified in the previous request. - String sequenceToken = describeLogStreamsResponse.logStreams().get(0).uploadSequenceToken(); - - // Build an input log message to put to CloudWatch. - InputLogEvent inputLogEvent = InputLogEvent.builder() - .message("{ \"key1\": \"value1\", \"key2\": \"value2\" }") - .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(Arrays.asList(inputLogEvent)) - .logGroupName(logGroupName) - .logStreamName(streamName) - .sequenceToken(sequenceToken) - .build(); - - logsClient.putLogEvents(putLogEventsRequest); - System.out.println("Successfully put CloudWatch log event"); - - } catch (CloudWatchException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[cloudwatch.java2.put_log_events.main] diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutSubscriptionFilter.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutSubscriptionFilter.java deleted file mode 100644 index 222b4fe380a..00000000000 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutSubscriptionFilter.java +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.cloudwatch; - -// snippet-start:[cloudwatch.java2.put_subscription_filter.main] -// snippet-start:[cloudwatch.java2.put_subscription_filter.import] -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; -// snippet-end:[cloudwatch.java2.put_subscription_filter.import] - -/** - * 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: - \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); - } - } -} -// snippet-end:[cloudwatch.java2.put_subscription_filter.main] From 90d3caa6ddb5f9018009a1085e11952db51b8973 Mon Sep 17 00:00:00 2001 From: Macdonald Date: Thu, 9 Oct 2025 11:50:16 -0400 Subject: [PATCH 3/5] modified tests --- .../src/main/java/com/example/logs/CloudWatchLogsSearch.java | 1 - .../cloudwatch-logs/src/test/java/CloudWatchLogsTest.java | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/CloudWatchLogsSearch.java b/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/CloudWatchLogsSearch.java index 132a249e8fa..eb814e8a62f 100644 --- a/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/CloudWatchLogsSearch.java +++ b/javav2/example_code/cloudwatch-logs/src/main/java/com/example/logs/CloudWatchLogsSearch.java @@ -71,7 +71,6 @@ public static void searchLogStreamsAndFilterEvents(CloudWatchLogsClient cwlClien .build(); DescribeLogStreamsResponse describeLogStreamsResponse = cwlClient.describeLogStreams(describeLogStreamsRequest); - List logStreams = describeLogStreamsResponse.logStreams(); for (LogStream logStream : logStreams) { diff --git a/javav2/example_code/cloudwatch-logs/src/test/java/CloudWatchLogsTest.java b/javav2/example_code/cloudwatch-logs/src/test/java/CloudWatchLogsTest.java index 68219981f79..e94664e1a58 100644 --- a/javav2/example_code/cloudwatch-logs/src/test/java/CloudWatchLogsTest.java +++ b/javav2/example_code/cloudwatch-logs/src/test/java/CloudWatchLogsTest.java @@ -36,13 +36,13 @@ public class CloudWatchLogsTest { private static String logStreamName = ""; private static String pattern = ""; - @BeforeAll public static void setUp() throws IOException { logsClient = CloudWatchLogsClient.builder() .region(Region.US_EAST_1) .build(); + // CHANGE THESE VALUES TO RUN THE TESTS logGroupName = "WeathertopJavaContainerLogs"; logStreamName = "weathertop-java-stream"; pattern = "INFO"; From 41106754c9a7bce22e89a9fe4825e6826e943297 Mon Sep 17 00:00:00 2001 From: Macdonald Date: Thu, 9 Oct 2025 12:10:41 -0400 Subject: [PATCH 4/5] modified YAML --- .doc_gen/metadata/cloudwatch-logs_metadata.yaml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.doc_gen/metadata/cloudwatch-logs_metadata.yaml b/.doc_gen/metadata/cloudwatch-logs_metadata.yaml index 6a424e23c1b..efb2633c861 100644 --- a/.doc_gen/metadata/cloudwatch-logs_metadata.yaml +++ b/.doc_gen/metadata/cloudwatch-logs_metadata.yaml @@ -119,7 +119,10 @@ cloudwatch-logs_DescribeLogStreams: github: javav2/example_code/cloudwatch sdkguide: excerpts: - - description: + - description: Searches for log streams within a specified log group that match a given prefix. + snippet_tags: + - cloudwatch.javav2.read.log.streams.main + - description: Prints metadata about the most recent log stream in a specified log group. snippet_tags: - cloudwatch.javav2.describe.log.streams.main services: From be87b4b16c8ec2dd7f45e7e5a99144e5a12d90ff Mon Sep 17 00:00:00 2001 From: Macdonald Date: Thu, 9 Oct 2025 13:34:43 -0400 Subject: [PATCH 5/5] modified YAML --- .doc_gen/metadata/cloudwatch-logs_metadata.yaml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.doc_gen/metadata/cloudwatch-logs_metadata.yaml b/.doc_gen/metadata/cloudwatch-logs_metadata.yaml index efb2633c861..beac1ce1a8a 100644 --- a/.doc_gen/metadata/cloudwatch-logs_metadata.yaml +++ b/.doc_gen/metadata/cloudwatch-logs_metadata.yaml @@ -116,7 +116,7 @@ cloudwatch-logs_DescribeLogStreams: Java: versions: - sdk_version: 2 - github: javav2/example_code/cloudwatch + github: javav2/example_code/cloudwatch-logs sdkguide: excerpts: - description: Searches for log streams within a specified log group that match a given prefix. @@ -161,7 +161,7 @@ cloudwatch-logs_DescribeSubscriptionFilters: Java: versions: - sdk_version: 2 - github: javav2/example_code/cloudwatch + github: javav2/example_code/cloudwatch-logs sdkguide: excerpts: - description: @@ -211,7 +211,7 @@ cloudwatch-logs_DeleteSubscriptionFilter: Java: versions: - sdk_version: 2 - github: javav2/example_code/cloudwatch + github: javav2/example_code/cloudwatch-logs sdkguide: excerpts: - description: @@ -251,7 +251,7 @@ cloudwatch-logs_PutSubscriptionFilter: Java: versions: - sdk_version: 2 - github: javav2/example_code/cloudwatch + github: javav2/example_code/cloudwatch-logs sdkguide: excerpts: - description: