SDK 사용을 위한 CloudWatch 코드 예제 AWS - AWS SDK 코드 예제

AWS 문서 AWS SDK 예제 리포지토리에 더 많은 SDK 예제가 있습니다. GitHub

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

SDK 사용을 위한 CloudWatch 코드 예제 AWS

다음 코드 예제는 AWS 소프트웨어 개발 키트 (SDK) CloudWatch 와 함께 Amazon을 사용하는 방법을 보여줍니다.

작업은 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 작업은 개별 서비스 함수를 호출하는 방법을 보여 주며 관련 시나리오와 교차 서비스 예시에서 컨텍스트에 맞는 작업을 볼 수 있습니다.

시나리오는 동일한 서비스 내에서 여러 함수를 호출하여 특정 태스크를 수행하는 방법을 보여주는 코드 예시입니다.

교차 서비스 예시는 여러 AWS 서비스전반에서 작동하는 샘플 애플리케이션입니다.

추가 리소스
  • CloudWatch 사용 설명서 — 에 대한 CloudWatch 추가 정보.

  • CloudWatch API 참조 — 사용 가능한 모든 CloudWatch 작업에 대한 세부 정보.

  • AWS 개발자 센터 — 카테고리 또는 전체 텍스트 검색별로 필터링할 수 있는 코드 예제입니다.

  • AWS SDK 예제 — 선호하는 GitHub 언어로 작성된 전체 코드가 포함된 리포지토리 코드 설정 및 실행을 위한 지침이 포함되어 있습니다.

시작하기

다음 코드 예제는 사용을 시작하는 방법을 보여줍니다 CloudWatch.

.NET
AWS SDK for .NET
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

using Amazon.CloudWatch; using Amazon.CloudWatch.Model; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace CloudWatchActions; public static class HelloCloudWatch { static async Task Main(string[] args) { // Use the AWS .NET Core Setup package to set up dependency injection for the Amazon CloudWatch service. // Use your AWS profile name, or leave it blank to use the default profile. using var host = Host.CreateDefaultBuilder(args) .ConfigureServices((_, services) => services.AddAWSService<IAmazonCloudWatch>() ).Build(); // Now the client is available for injection. var cloudWatchClient = host.Services.GetRequiredService<IAmazonCloudWatch>(); // You can use await and any of the async methods to get a response. var metricNamespace = "AWS/Billing"; var response = await cloudWatchClient.ListMetricsAsync(new ListMetricsRequest { Namespace = metricNamespace }); Console.WriteLine($"Hello Amazon CloudWatch! Following are some metrics available in the {metricNamespace} namespace:"); Console.WriteLine(); foreach (var metric in response.Metrics.Take(5)) { Console.WriteLine($"\tMetric: {metric.MetricName}"); Console.WriteLine($"\tNamespace: {metric.Namespace}"); Console.WriteLine($"\tDimensions: {string.Join(", ", metric.Dimensions.Select(m => $"{m.Name}:{m.Value}"))}"); Console.WriteLine(); } } }
  • API 세부 정보는 AWS SDK for .NET API ListMetrics참조를 참조하십시오.

Java
SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudwatch.CloudWatchClient; import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; import software.amazon.awssdk.services.cloudwatch.model.ListMetricsRequest; import software.amazon.awssdk.services.cloudwatch.paginators.ListMetricsIterable; /** * 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 HelloService { public static void main(String[] args) { final String usage = """ Usage: <namespace>\s Where: namespace - The namespace to filter against (for example, AWS/EC2).\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String namespace = args[0]; Region region = Region.US_EAST_1; CloudWatchClient cw = CloudWatchClient.builder() .region(region) .build(); listMets(cw, namespace); cw.close(); } public static void listMets(CloudWatchClient cw, String namespace) { try { ListMetricsRequest request = ListMetricsRequest.builder() .namespace(namespace) .build(); ListMetricsIterable listRes = cw.listMetricsPaginator(request); listRes.stream() .flatMap(r -> r.metrics().stream()) .forEach(metrics -> System.out.println(" Retrieved metric is: " + metrics.metricName())); } catch (CloudWatchException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API 세부 정보는 AWS SDK for Java 2.x API ListMetrics참조를 참조하십시오.

Kotlin
SDK for Kotlin
참고

자세한 내용은 다음과 같습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

/** Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <namespace> Where: namespace - The namespace to filter against (for example, AWS/EC2). """ if (args.size != 1) { println(usage) exitProcess(0) } val namespace = args[0] listAllMets(namespace) } suspend fun listAllMets(namespaceVal: String?) { val request = ListMetricsRequest { namespace = namespaceVal } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient .listMetricsPaginated(request) .transform { it.metrics?.forEach { obj -> emit(obj) } } .collect { obj -> println("Name is ${obj.metricName}") println("Namespace is ${obj.namespace}") } } }
  • API 세부 정보는 Kotlin API용AWS SDK 레퍼런스를 참조하세요 ListMetrics.