PutDashboard 搭配 a AWS SDK 或 CLI 使用 - AWS SDK 程式碼範例

文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的 GitHub 範例。

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

PutDashboard 搭配 a AWS SDK 或 CLI 使用

下列程式碼範例示範如何使用 PutDashboard

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/// <summary> /// Set up a dashboard using a call to the wrapper class. /// </summary> /// <param name="customMetricNamespace">The metric namespace.</param> /// <param name="customMetricName">The metric name.</param> /// <param name="dashboardName">The name of the dashboard.</param> /// <returns>A list of validation messages.</returns> private static async Task<List<DashboardValidationMessage>> SetupDashboard( string customMetricNamespace, string customMetricName, string dashboardName) { // Get the dashboard model from configuration. var newDashboard = new DashboardModel(); _configuration.GetSection("dashboardExampleBody").Bind(newDashboard); // Add a new metric to the dashboard. newDashboard.Widgets.Add(new Widget { Height = 8, Width = 8, Y = 8, X = 0, Type = "metric", Properties = new Properties { Metrics = new List<List<object>> { new() { customMetricNamespace, customMetricName } }, View = "timeSeries", Region = "us-east-1", Stat = "Sum", Period = 86400, YAxis = new YAxis { Left = new Left { Min = 0, Max = 100 } }, Title = "Custom Metric Widget", LiveData = true, Sparkline = true, Trend = true, Stacked = false, SetPeriodToTimeRange = false } }); var newDashboardString = JsonSerializer.Serialize(newDashboard, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }); var validationMessages = await _cloudWatchWrapper.PutDashboard(dashboardName, newDashboardString); return validationMessages; } /// <summary> /// Wrapper to create or add to a dashboard with metrics. /// </summary> /// <param name="dashboardName">The name for the dashboard.</param> /// <param name="dashboardBody">The metric data in JSON for the dashboard.</param> /// <returns>A list of validation messages for the dashboard.</returns> public async Task<List<DashboardValidationMessage>> PutDashboard(string dashboardName, string dashboardBody) { // Updating a dashboard replaces all contents. // Best practice is to include a text widget indicating this dashboard was created programmatically. var dashboardResponse = await _amazonCloudWatch.PutDashboardAsync( new PutDashboardRequest() { DashboardName = dashboardName, DashboardBody = dashboardBody }); return dashboardResponse.DashboardValidationMessages; }
  • 如需 API 詳細資訊,請參閱 PutDashboard AWS SDK for .NET 參考中的 API

Java
Java 2.x 的 SDK
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/** * Creates a new dashboard with the specified name and metrics from the given file. * * @param dashboardName the name of the dashboard to be created * @param fileName the name of the file containing the dashboard body * @return a {@link CompletableFuture} representing the asynchronous operation of creating the dashboard * @throws IOException if there is an error reading the dashboard body from the file */ public CompletableFuture<PutDashboardResponse> createDashboardWithMetricsAsync(String dashboardName, String fileName) throws IOException { String dashboardBody = readFileAsString(fileName); PutDashboardRequest dashboardRequest = PutDashboardRequest.builder() .dashboardName(dashboardName) .dashboardBody(dashboardBody) .build(); return getAsyncClient().putDashboard(dashboardRequest) .handle((response, ex) -> { if (ex != null) { logger.info("Failed to create dashboard: {}", ex.getMessage()); throw new RuntimeException("Dashboard creation failed", ex); } else { // Handle the normal response case logger.info("{} was successfully created.", dashboardName); List<DashboardValidationMessage> messages = response.dashboardValidationMessages(); if (messages.isEmpty()) { logger.info("There are no messages in the new Dashboard."); } else { for (DashboardValidationMessage message : messages) { logger.info("Message: {}", message.message()); } } return response; // Return the response for further use } }); }
  • 如需 API 詳細資訊,請參閱 PutDashboard AWS SDK for Java 2.x 參考中的 API

Kotlin
SDK for Kotlin
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

suspend fun createDashboardWithMetrics( dashboardNameVal: String, fileNameVal: String, ) { val dashboardRequest = PutDashboardRequest { dashboardName = dashboardNameVal dashboardBody = readFileAsString(fileNameVal) } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.putDashboard(dashboardRequest) println("$dashboardNameVal was successfully created.") val messages = response.dashboardValidationMessages if (messages != null) { if (messages.isEmpty()) { println("There are no messages in the new Dashboard") } else { for (message in messages) { println("Message is: ${message.message}") } } } } }
  • 如需 API 詳細資訊,請參閱 PutDashboard AWS for Kotlin SDK 參考中的 API

PowerShell
for PowerShell 工具

範例 1:建立或更新名為 'Dashboard1' 的儀表板,以並排包含兩個指標小工具。

$dashBody = @" { "widgets":[ { "type":"metric", "x":0, "y":0, "width":12, "height":6, "properties":{ "metrics":[ [ "AWS/EC2", "CPUUtilization", "InstanceId", "i-012345" ] ], "period":300, "stat":"Average", "region":"us-east-1", "title":"EC2 Instance CPU" } }, { "type":"metric", "x":12, "y":0, "width":12, "height":6, "properties":{ "metrics":[ [ "AWS/S3", "BucketSizeBytes", "BucketName", "amzn-s3-demo-bucket" ] ], "period":86400, "stat":"Maximum", "region":"us-east-1", "title":"amzn-s3-demo-bucket bytes" } } ] } "@ Write-CWDashboard -DashboardName Dashboard1 -DashboardBody $dashBody

範例 2:建立或更新儀表板,將描述儀表板的內容導入 cmdlet。

$dashBody = @" { ... } "@ $dashBody | Write-CWDashboard -DashboardName Dashboard1
  • 如需 API 詳細資訊,請參閱 AWS Tools for PowerShell Cmdlet 參考中的 PutDashboard