public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.CloudWatch.Model.PutMetricDataRequest(); if (cmdletContext.MetricData != null) { request.MetricData = cmdletContext.MetricData; } if (cmdletContext.Namespace != null) { request.Namespace = cmdletContext.Namespace; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return(output); }
public void TrackEvent(string eventName, TimeSpan elapsed, IDictionary <string, string> properties = null) { var dimension = new Amazon.CloudWatch.Model.Dimension { Name = eventName, Value = eventName }; var metric1 = new Amazon.CloudWatch.Model.MetricDatum { Dimensions = new List <Amazon.CloudWatch.Model.Dimension> { dimension }, MetricName = eventName, StatisticValues = new Amazon.CloudWatch.Model.StatisticSet(), Timestamp = DateTime.Today, Unit = StandardUnit.Count }; if (properties?.ContainsKey("value") == true) { metric1.Value = long.Parse(properties["value"]); } else { metric1.Value = 1; } var request = new Amazon.CloudWatch.Model.PutMetricDataRequest { MetricData = new List <Amazon.CloudWatch.Model.MetricDatum>() { metric1 }, Namespace = eventName }; _telemetryClient.PutMetricDataAsync(request).Wait(); }
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListMetrics /// operation.</returns> public IAsyncResult BeginListMetrics(ListMetricsRequest listMetricsRequest, AsyncCallback callback, object state) { return invokeListMetrics(listMetricsRequest, callback, state, false); } /// <summary>
internal PutMetricDataResponse PutMetricData(PutMetricDataRequest request) { var task = PutMetricDataAsync(request); try { return task.Result; } catch(AggregateException e) { ExceptionDispatchInfo.Capture(e.InnerException).Throw(); return null; } }
/// <summary> /// Initiates the asynchronous execution of the PutMetricData operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutMetricData operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<PutMetricDataResponse> PutMetricDataAsync(PutMetricDataRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new PutMetricDataRequestMarshaller(); var unmarshaller = PutMetricDataResponseUnmarshaller.Instance; return InvokeAsync<PutMetricDataRequest,PutMetricDataResponse>(request, marshaller, unmarshaller, cancellationToken); }
private void SendItOff(PutMetricDataRequest metricDataRequest) { if (_client == null) SetupClient(); var tokenSource = new CancellationTokenSource(); CancellationToken ct = tokenSource.Token; try { var task1 = Task.Factory.StartNew(() => { var task = Task.Factory.StartNew(() => { try { var tmpCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB", false); System.Diagnostics.Debug.WriteLine("Sending"); var response = _client.PutMetricData(metricDataRequest); System.Diagnostics.Debug.WriteLine("RequestID: " + response.ToString()); Thread.CurrentThread.CurrentCulture = tmpCulture; } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); } }, ct); try { if (!task.Wait(30000)) { tokenSource.Cancel(); System.Diagnostics.Debug.WriteLine( string.Format( "CloudWatchAppender timed out while submitting to CloudWatch. There was an exception. {0}", task.Exception)); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine( string.Format( "CloudWatchAppender encountered an error while submitting to cloudwatch. {0}", e)); } }); if (!task1.IsCompleted) _tasks.TryAdd(task1.Id, task1); task1.ContinueWith(t => { Task task2; _tasks.TryRemove(task1.Id, out task2); System.Diagnostics.Debug.WriteLine("Cloudwatch complete"); if (task1.Exception != null) System.Diagnostics.Debug.WriteLine(string.Format("CloudWatchAppender encountered an error while submitting to CloudWatch. {0}", task1.Exception)); }); } catch (Exception e) { System.Diagnostics.Debug.WriteLine( string.Format( "CloudWatchAppender encountered an error while submitting to cloudwatch. {0}", e)); } }
/// Initiates the asynchronous execution of the DescribeAlarmHistory operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DescribeAlarmHistory"/> /// </summary> /// /// <param name="describeAlarmHistoryRequest">Container for the necessary parameters to execute the DescribeAlarmHistory operation on /// AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndDescribeAlarmHistory operation.</returns> public IAsyncResult BeginDescribeAlarmHistory(DescribeAlarmHistoryRequest describeAlarmHistoryRequest, AsyncCallback callback, object state) { return invokeDescribeAlarmHistory(describeAlarmHistoryRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the DescribeAlarmHistory operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DescribeAlarmHistory"/>
/// <para> Deletes all specified alarms. In the event of an error, no alarms are deleted. </para> /// </summary> /// /// <param name="deleteAlarmsRequest">Container for the necessary parameters to execute the DeleteAlarms service method on /// AmazonCloudWatch.</param> /// /// <exception cref="ResourceNotFoundException"/> public DeleteAlarmsResponse DeleteAlarms(DeleteAlarmsRequest deleteAlarmsRequest)
/// <summary> /// <para> Publishes metric data points to Amazon CloudWatch. Amazon /// Cloudwatch associates the data points with the specified metric. If /// the specified metric does not exist, Amazon CloudWatch creates the /// metric. </para> <para><b>NOTE:</b> If you create a metric with the /// PutMetricData action, allow up to fifteen minutes for the metric to /// appear in calls to the ListMetrics action. </para> <para> The size of /// a PutMetricData request is limited to 8 KB for HTTP GET requests and /// 40 KB for HTTP POST requests. </para> <para><b>IMPORTANT:</b> Although /// the Value parameter accepts numbers of type Double, Amazon CloudWatch /// truncates values with very large exponents. Values with base-10 /// exponents greater than 126 (1 x 10^126) are truncated. Likewise, /// values with base-10 exponents less than -130 (1 x 10^-130) are also /// truncated. </para> /// </summary> /// /// <param name="putMetricDataRequest">Container for the necessary /// parameters to execute the PutMetricData service method on /// AmazonCloudWatch.</param> /// /// <exception cref="InvalidParameterValueException"/> /// <exception cref="InternalServiceException"/> /// <exception cref="InvalidParameterCombinationException"/> /// <exception cref="MissingRequiredParameterException"/> public PutMetricDataResponse PutMetricData(PutMetricDataRequest putMetricDataRequest) { IRequest<PutMetricDataRequest> request = new PutMetricDataRequestMarshaller().Marshall(putMetricDataRequest); PutMetricDataResponse response = Invoke<PutMetricDataRequest, PutMetricDataResponse> (request, this.signer, PutMetricDataResponseUnmarshaller.GetInstance()); return response; }
private Amazon.CloudWatch.Model.PutMetricDataResponse CallAWSServiceOperation(IAmazonCloudWatch client, Amazon.CloudWatch.Model.PutMetricDataRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon CloudWatch", "PutMetricData"); try { #if DESKTOP return(client.PutMetricData(request)); #elif CORECLR return(client.PutMetricDataAsync(request).GetAwaiter().GetResult()); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } }
private void UpdateMetrics() { if (!PopulateInstanceId()) return; if (!PopulateRegion()) return; var metrics = new List<MetricDatum>(); if (_isSubmitDiskSpaceAvailable || _isSubmitDiskSpaceUsed || _isSubmitDiskSpaceUtilization) { // Get the list of drives from the system DriveInfo[] drives = DriveInfo.GetDrives(); foreach (DriveInfo drive in drives) { AddDriveMetrics(drive, metrics); } } if (_isSubmitMemoryAvailable || _isSubmitMemoryUsed || _isSubmitMemoryUtilization || _isSubmitPhysicalMemoryAvailable || _isSubmitPhysicalMemoryUsed || _isSubmitPhysicalMemoryUtilization || _isSubmitVirtualMemoryAvailable || _isSubmitVirtualMemoryUsed || _isSubmitVirtualMemoryUtilization) { SubmitMemoryMetrics(metrics); } Info("\tSubmitting metric data"); for (int skip = 0;; skip += 20) { IEnumerable<MetricDatum> metricsThisRound = metrics.Skip(skip).Take(20); if (metricsThisRound.Count() == 0) break; PutMetricDataRequest request = new PutMetricDataRequest() .WithNamespace(CloudWatchNamespace) .WithMetricData(metricsThisRound); AmazonCloudWatch client = CreateClient(); PutMetricDataResponse response = client.PutMetricData(request); } // We don't care about the response Info("Done."); }
/// <summary> /// Initiates the asynchronous execution of the PutMetricData operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutMetricData operation on AmazonCloudWatchClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutMetricData /// operation.</returns> public IAsyncResult BeginPutMetricData(PutMetricDataRequest request, AsyncCallback callback, object state) { var marshaller = new PutMetricDataRequestMarshaller(); var unmarshaller = PutMetricDataResponseUnmarshaller.Instance; return BeginInvoke<PutMetricDataRequest>(request, marshaller, unmarshaller, callback, state); }
/// <summary> /// Publishes metric data points to Amazon CloudWatch. Amazon Cloudwatch associates the /// data points with the specified metric. If the specified metric does not exist, Amazon /// CloudWatch creates the metric. It can take up to fifteen minutes for a new metric /// to appear in calls to the <a>ListMetrics</a> action. /// /// /// <para> /// The size of a PutMetricData request is limited to 8 KB for HTTP GET requests and /// 40 KB for HTTP POST requests. /// </para> /// <important> Although the <code>Value</code> parameter accepts numbers of type <code>Double</code>, /// Amazon CloudWatch truncates values with very large exponents. Values with base-10 /// exponents greater than 126 (1 x 10^126) are truncated. Likewise, values with base-10 /// exponents less than -130 (1 x 10^-130) are also truncated. </important> /// <para> /// Data that is timestamped 24 hours or more in the past may take in excess of 48 hours /// to become available from submission time using <code>GetMetricStatistics</code>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutMetricData service method.</param> /// /// <returns>The response from the PutMetricData service method, as returned by CloudWatch.</returns> /// <exception cref="Amazon.CloudWatch.Model.InternalServiceException"> /// Indicates that the request processing has failed due to some unknown error, exception, /// or failure. /// </exception> /// <exception cref="Amazon.CloudWatch.Model.InvalidParameterCombinationException"> /// Parameters that must not be used together were used together. /// </exception> /// <exception cref="Amazon.CloudWatch.Model.InvalidParameterValueException"> /// Bad or out-of-range value was supplied for the input parameter. /// </exception> /// <exception cref="Amazon.CloudWatch.Model.MissingRequiredParameterException"> /// An input parameter that is mandatory for processing the request is not supplied. /// </exception> public PutMetricDataResponse PutMetricData(PutMetricDataRequest request) { var marshaller = new PutMetricDataRequestMarshaller(); var unmarshaller = PutMetricDataResponseUnmarshaller.Instance; return Invoke<PutMetricDataRequest,PutMetricDataResponse>(request, marshaller, unmarshaller); }
/// <summary> /// <para> Publishes metric data points to Amazon CloudWatch. Amazon Cloudwatch associates the data points with the specified metric. If the /// specified metric does not exist, Amazon CloudWatch creates the metric. It can take up to fifteen minutes for a new metric to appear in calls /// to the ListMetrics action.</para> <para> The size of a PutMetricData request is limited to 8 KB for HTTP GET requests and 40 KB for HTTP /// POST requests. </para> <para><b>IMPORTANT:</b> Although the Value parameter accepts numbers of type Double, Amazon CloudWatch truncates /// values with very large exponents. Values with base-10 exponents greater than 126 (1 x 10^126) are truncated. Likewise, values with base-10 /// exponents less than -130 (1 x 10^-130) are also truncated. </para> <para>Data that is timestamped 24 hours or more in the past may take in /// excess of 48 hours to become available from submission time using <c>GetMetricStatistics</c> .</para> /// </summary> /// /// <param name="putMetricDataRequest">Container for the necessary parameters to execute the PutMetricData service method on /// AmazonCloudWatch.</param> /// /// <exception cref="T:Amazon.CloudWatch.Model.InvalidParameterValueException" /> /// <exception cref="T:Amazon.CloudWatch.Model.InternalServiceException" /> /// <exception cref="T:Amazon.CloudWatch.Model.InvalidParameterCombinationException" /> /// <exception cref="T:Amazon.CloudWatch.Model.MissingRequiredParameterException" /> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> public Task<PutMetricDataResponse> PutMetricDataAsync(PutMetricDataRequest putMetricDataRequest, CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new PutMetricDataRequestMarshaller(); var unmarshaller = PutMetricDataResponseUnmarshaller.GetInstance(); return Invoke<IRequest, PutMetricDataRequest, PutMetricDataResponse>(putMetricDataRequest, marshaller, unmarshaller, signer, cancellationToken); }
internal PutMetricDataResponse PutMetricData(PutMetricDataRequest request) { var task = PutMetricDataAsync(request); try { return task.Result; } catch(AggregateException e) { throw e.InnerException; } }
/// <summary> /// <para> Publishes metric data points to Amazon CloudWatch. Amazon Cloudwatch associates the data points with the specified metric. If the /// specified metric does not exist, Amazon CloudWatch creates the metric. It can take up to fifteen minutes for a new metric to appear in calls /// to the ListMetrics action.</para> <para> The size of a PutMetricData request is limited to 8 KB for HTTP GET requests and 40 KB for HTTP /// POST requests. </para> <para><b>IMPORTANT:</b> Although the Value parameter accepts numbers of type Double, Amazon CloudWatch truncates /// values with very large exponents. Values with base-10 exponents greater than 126 (1 x 10^126) are truncated. Likewise, values with base-10 /// exponents less than -130 (1 x 10^-130) are also truncated. </para> <para>Data that is timestamped 24 hours or more in the past may take in /// excess of 48 hours to become available from submission time using <c>GetMetricStatistics</c> .</para> /// </summary> /// /// <param name="putMetricDataRequest">Container for the necessary parameters to execute the PutMetricData service method on /// AmazonCloudWatch.</param> /// /// <exception cref="T:Amazon.CloudWatch.Model.InvalidParameterValueException" /> /// <exception cref="T:Amazon.CloudWatch.Model.InternalServiceException" /> /// <exception cref="T:Amazon.CloudWatch.Model.InvalidParameterCombinationException" /> /// <exception cref="T:Amazon.CloudWatch.Model.MissingRequiredParameterException" /> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> public async Task<PutMetricDataResponse> PutMetricDataAsync(PutMetricDataRequest putMetricDataRequest, CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new PutMetricDataRequestMarshaller(); var unmarshaller = PutMetricDataResponseUnmarshaller.GetInstance(); var response = await Invoke<IRequest, PutMetricDataRequest, PutMetricDataResponse>(putMetricDataRequest, marshaller, unmarshaller, signer, cancellationToken) .ConfigureAwait(continueOnCapturedContext: false); return response; }
protected override void Write(LogEventInfo logEvent) { InternalLogger.Debug("Sending log to AWSCloudWatch '{0}' {1}.{2}", Endpoint, this.Namespace, this.MetricName); try { string logMessage = this.Layout.Render(logEvent); var metricRequest = new PutMetricDataRequest { Namespace = this.Namespace }; metricRequest.MetricData.Add(new MetricDatum { MetricName = this.MetricName, Timestamp = DateTime.UtcNow, Unit = this.Unit, Value = this.Value }); try { var response = client.PutMetricData(metricRequest); InternalLogger.Debug("Sent log to AWSCloudWatch, response received. HttpStatusCode: {0}, RequestId: {1}", response.HttpStatusCode, response.ResponseMetadata.RequestId); } catch (InternalServiceException e) { InternalLogger.Fatal("RequestId: {0}, ErrorType: {1}, Status: {2}\nFailed to send log with\n{3}\n{4}", e.RequestId, e.ErrorType, e.StatusCode, e.Message, e.StackTrace); } } catch (Exception e) { InternalLogger.Fatal("Failed to write log to Amazon CloudWatch with\n{0}\n{1}", e.Message, e.StackTrace); } }
public static void CWPutMetricData() { #region CWPutMetricData var client = new AmazonCloudWatchClient(); var dimension = new Dimension { Name = "Desktop Machine Metrics", Value = "Virtual Desktop Machine Usage" }; var metric1 = new MetricDatum { Dimensions = new List<Dimension>(), MetricName = "Desktop Machines Online", StatisticValues = new StatisticSet(), Timestamp = DateTime.Today, Unit = StandardUnit.Count, Value = 14 }; var metric2 = new MetricDatum { Dimensions = new List<Dimension>(), MetricName = "Desktop Machines Offline", StatisticValues = new StatisticSet(), Timestamp = DateTime.Today, Unit = StandardUnit.Count, Value = 7 }; var metric3 = new MetricDatum { Dimensions = new List<Dimension>(), MetricName = "Desktop Machines Online", StatisticValues = new StatisticSet(), Timestamp = DateTime.Today, Unit = StandardUnit.Count, Value = 12 }; var metric4 = new MetricDatum { Dimensions = new List<Dimension>(), MetricName = "Desktop Machines Offline", StatisticValues = new StatisticSet(), Timestamp = DateTime.Today, Unit = StandardUnit.Count, Value = 9 }; var request = new PutMetricDataRequest { MetricData = new List<MetricDatum>() { metric1, metric2, metric3, metric4 }, Namespace = "Example.com Custom Metrics" }; client.PutMetricData(request); #endregion }