Há mais exemplos de AWS SDK disponíveis no repositório AWS Doc SDK Examples
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á.
Use GetMetricWidgetImage
com um AWS SDK ou CLI
Os exemplos de código a seguir mostram como usar o GetMetricWidgetImage
.
Exemplos de ações são trechos de código de programas maiores e devem ser executados em contexto. É possível ver essa ação em contexto no seguinte exemplo de código:
- .NET
-
- AWS SDK for .NET
-
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
. /// <summary> /// Get an image for a metric graphed over time. /// </summary> /// <param name="metricNamespace">The namespace of the metric.</param> /// <param name="metric">The name of the metric.</param> /// <param name="stat">The name of the stat to chart.</param> /// <param name="period">The period to use for the chart.</param> /// <returns>A memory stream for the chart image.</returns> public async Task<MemoryStream> GetTimeSeriesMetricImage(string metricNamespace, string metric, string stat, int period) { var metricImageWidget = new { title = "Example Metric Graph", view = "timeSeries", stacked = false, period = period, width = 1400, height = 600, metrics = new List<List<object>> { new() { metricNamespace, metric, new { stat } } } }; var metricImageWidgetString = JsonSerializer.Serialize(metricImageWidget); var imageResponse = await _amazonCloudWatch.GetMetricWidgetImageAsync( new GetMetricWidgetImageRequest() { MetricWidget = metricImageWidgetString }); return imageResponse.MetricWidgetImage; } /// <summary> /// Save a metric image to a file. /// </summary> /// <param name="memoryStream">The MemoryStream for the metric image.</param> /// <param name="metricName">The name of the metric.</param> /// <returns>The path to the file.</returns> public string SaveMetricImage(MemoryStream memoryStream, string metricName) { var metricFileName = $"{metricName}_{DateTime.Now.Ticks}.png"; using var sr = new StreamReader(memoryStream); // Writes the memory stream to a file. File.WriteAllBytes(metricFileName, memoryStream.ToArray()); var filePath = Path.Join(AppDomain.CurrentDomain.BaseDirectory, metricFileName); return filePath; }
-
Para obter detalhes da API, consulte GetMetricWidgetImagea Referência AWS SDK for .NET da API.
-
- CLI
-
- AWS CLI
-
Para recuperar um gráfico instantâneo de CPUUtilization
O
get-metric-widget-image
exemplo a seguir recupera o gráfico instantâneo da métricaCPUUtilization
da EC2 instância com o IDi-abcde
e salva a imagem recuperada como um arquivo chamado "image.png" na sua máquina local.aws cloudwatch get-metric-widget-image \ --metric-widget '
{"metrics":[["AWS/EC2","CPUUtilization","InstanceId","i-abcde"]]}
' \ --output-formatpng
\ --outputtext
|
base64
--decode>
image.png
Este comando não produz saída.
-
Para obter detalhes da API, consulte GetMetricWidgetImage
em Referência de AWS CLI Comandos.
-
- Java
-
- SDK para 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
. /** * Retrieves and saves a custom metric image to a file. * * @param fileName the name of the file to save the metric image to * @return a {@link CompletableFuture} that completes when the image has been saved to the file */ public CompletableFuture<Void> downloadAndSaveMetricImageAsync(String fileName) { logger.info("Getting Image data for custom metric."); String myJSON = """ { "title": "Example Metric Graph", "view": "timeSeries", "stacked ": false, "period": 10, "width": 1400, "height": 600, "metrics": [ [ "AWS/Billing", "EstimatedCharges", "Currency", "USD" ] ] } """; GetMetricWidgetImageRequest imageRequest = GetMetricWidgetImageRequest.builder() .metricWidget(myJSON) .build(); return getAsyncClient().getMetricWidgetImage(imageRequest) .thenCompose(response -> { SdkBytes sdkBytes = response.metricWidgetImage(); byte[] bytes = sdkBytes.asByteArray(); return CompletableFuture.runAsync(() -> { try { File outputFile = new File(fileName); try (FileOutputStream outputStream = new FileOutputStream(outputFile)) { outputStream.write(bytes); } } catch (IOException e) { throw new RuntimeException("Failed to write image to file", e); } }); }) .whenComplete((result, exception) -> { if (exception != null) { throw new RuntimeException("Error getting and saving metric image", exception); } else { logger.info("Image data saved successfully to {}", fileName); } }); }
-
Para obter detalhes da API, consulte GetMetricWidgetImagea Referência AWS SDK for Java 2.x da API.
-
- Kotlin
-
- SDK para Kotlin
-
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
. suspend fun getAndOpenMetricImage(fileName: String) { println("Getting Image data for custom metric.") val myJSON = """{ "title": "Example Metric Graph", "view": "timeSeries", "stacked ": false, "period": 10, "width": 1400, "height": 600, "metrics": [ [ "AWS/Billing", "EstimatedCharges", "Currency", "USD" ] ] }""" val imageRequest = GetMetricWidgetImageRequest { metricWidget = myJSON } CloudWatchClient { region = "us-east-1" }.use { cwClient -> val response = cwClient.getMetricWidgetImage(imageRequest) val bytes = response.metricWidgetImage if (bytes != null) { File(fileName).writeBytes(bytes) } } println("You have successfully written data to $fileName") }
-
Para obter detalhes da API, consulte a GetMetricWidgetImage
referência da API AWS SDK for Kotlin.
-