CloudWatch Exemplos de registros usando SDK para Java 2.x - AWS SDK for Java 2.x

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

CloudWatch Exemplos de registros usando SDK para Java 2.x

Os exemplos de código a seguir mostram como realizar ações e implementar cenários comuns usando o AWS SDK for Java 2.x with CloudWatch Logs.

Ações são trechos de código de programas maiores e devem ser executadas em contexto. Embora as ações mostrem como chamar funções de serviço individuais, você pode ver as ações no contexto em seus cenários relacionados.

Cada exemplo inclui um link para o código-fonte completo, onde você pode encontrar instruções sobre como configurar e executar o código no contexto.

Tópicos

Ações

O código de exemplo a seguir mostra como usar DeleteSubscriptionFilter.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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); } } }

O código de exemplo a seguir mostra como usar DescribeSubscriptionFilters.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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"); } }

O código de exemplo a seguir mostra como usar PutSubscriptionFilter.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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); } } }

O código de exemplo a seguir mostra como usar StartLiveTail.

SDKpara Java 2.x

Inclua os arquivos necessários.

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;

Gerencie os eventos da sessão do 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(); }

Inicie a sessão do 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));

Interrompa a sessão do Live Tail após um período decorrido.

/* 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"); }
  • Para API obter detalhes, consulte StartLiveTailem AWS SDK for Java 2.x APIReferência.