Usar GetMetricWidgetImage
com o AWS SDK ou a 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 no contexto no seguinte exemplo de código:
- .NET
-
- SDK para .NET
-
nota
Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWSCode Examples Repository
. /// <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 GetMetricWidgetImage, na Referência da API AWS SDK para .NET.
-
- CLI
-
- AWS CLI
-
Para recuperar um grafo de snapshot de CPUUtilization
O exemplo
get-metric-widget-image
a seguir recupera o grafo de snapshot da métricaCPUUtilization
da instância do EC2 com o IDi-abcde
e salva a imagem recuperada como um arquivo denominado "image.png" na 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
na Referência de comandos da AWS CLI.
-
- Java
-
- SDK para Java 2.x
-
nota
Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWSCode Examples Repository
. /** * 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 GetMetricWidgetImage, na Referência da API AWS SDK for Java 2.x.
-
- Kotlin
-
- SDK para Kotlin
-
nota
Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWSCode Examples Repository
. 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.fromEnvironment { 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 GetMetricWidgetImage
, na Referência de APIs do AWS SDK para Kotlin.
-
Para ver uma lista completa dos Guias do desenvolvedor e exemplos de código do SDK da AWS, consulte Como usar o CloudWatch com um AWS SDK. Este tópico também inclui informações sobre como começar e detalhes sobre versões anteriores do SDK.