Hay más AWS SDK ejemplos disponibles en el GitHub repositorio de AWS Doc SDK Examples
Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.
CloudWatch Registra ejemplos que se utilizan SDK para Java 2.x
Los siguientes ejemplos de código muestran cómo realizar acciones e implementar escenarios comunes mediante el uso AWS SDK for Java 2.x de CloudWatch registros.
Las acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Mientras las acciones muestran cómo llamar a las funciones de servicio individuales, es posible ver las acciones en contexto en los escenarios relacionados.
Cada ejemplo incluye un enlace al código fuente completo, donde puede encontrar instrucciones sobre cómo configurar y ejecutar el código en su contexto.
Temas
Acciones
En el siguiente ejemplo de código se muestra cómo usar DeleteSubscriptionFilter
.
- SDKpara Java 2.x
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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); } } }
-
Para API obtener más información, consulte DeleteSubscriptionFilterla AWS SDK for Java 2.x APIReferencia.
-
En el siguiente ejemplo de código se muestra cómo usar DescribeSubscriptionFilters
.
- SDKpara Java 2.x
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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"); } }
-
Para API obtener más información, consulte DescribeSubscriptionFiltersla AWS SDK for Java 2.x APIReferencia.
-
En el siguiente ejemplo de código se muestra cómo usar PutSubscriptionFilter
.
- SDKpara Java 2.x
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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); } } }
-
Para API obtener más información, consulte PutSubscriptionFilterla AWS SDK for Java 2.x APIReferencia.
-
En el siguiente ejemplo de código se muestra cómo usar StartLiveTail
.
- SDKpara Java 2.x
-
Incluir los archivos requeridos.
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;
Gestione los eventos de la sesión de 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 la sesión de 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));
Detenga la sesión de Live Tail una vez transcurrido un periodo de tiempo.
/* 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 obtener más información, consulte StartLiveTailla AWS SDK for Java 2.x APIReferencia.
-