GetLogEvents.java - AWS Code Sample

GetLogEvents.java

GetLogEvents.java demonstrates how to get log events from Amazon CloudWatch.

Note

To run this Java (SDK V2) code example, ensure that you have set up your development environment, including your credentials. For more information, see AWS SDK for Java 2.x Developer Guide.

/* 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.cloudwatch.model.CloudWatchException; import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; import software.amazon.awssdk.services.cloudwatchlogs.model.GetLogEventsRequest; /** * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. * * For information, see this 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 = "\n" + "Usage:\n" + " GetLogEvents <logStreamName> <logGroupName>\n\n" + "Where:\n" + " logStreamName - the name of the log stream (for example, mystream).\n" + " logGroupName - the name of the log group (for example, myloggroup).\n" ; if (args.length != 2) { System.out.print(USAGE); System.exit(1); } String logStreamName = args[0]; String logGroupName = 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); } } }

Sample Details

Service: Amazon CloudWatch

Last tested: 11/02/2020

Author: scmacdon - aws

Type: full-example