public void Initializer_IsIdempotent() { // Create a Metric telemetry with SDK version starting with "af_" string originalVersion = "af_azwapccore:2.9.1-26132"; var metricTelemetry = new MetricTelemetry("metric", 100.00); metricTelemetry.Context.GetInternalContext().SdkVersion = originalVersion; // Apply Initializer, more than once. var initializer = new MetricSdkVersionTelemetryInitializer(); initializer.Initialize(metricTelemetry); initializer.Initialize(metricTelemetry); // Validate that initializer does not modify the SDKVersion as it is already prefixed with "af_" var actualSdkVersion = metricTelemetry.Context.GetInternalContext().SdkVersion; Assert.Equal(originalVersion, actualSdkVersion); }
private async Task PostMetric2Async(YEngine engine, YMetricPayload2 payload, string instrumentationKey) { using TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault(); configuration.InstrumentationKey = instrumentationKey; var telemetryClient = new TelemetryClient(configuration); var telemetry = new MetricTelemetry(payload.Namespace, payload.Name, payload.Count, payload.Sum, payload.Min, payload.Max, 0); foreach (var d in payload.Dimensions) { telemetry.Properties.Add(d.Name, d.Value); } telemetryClient.TrackMetric(telemetry); telemetryClient.Flush(); }
public static void TrackRetrieveDimensionDuration(string dimension, long value, string logFileName) { if (!_initialized) { return; } var telemetryClient = new TelemetryClient(); var telemetry = new MetricTelemetry("Retrieve Dimension duration (ms)", value); telemetry.Properties.Add("Dimension", dimension); if (!string.IsNullOrWhiteSpace(logFileName)) { telemetry.Properties.Add("LogFile", logFileName); } telemetryClient.TrackMetric(telemetry); telemetryClient.Flush(); }
public async Task <IActionResult> Index() { TelemetryClient telemetry = new TelemetryClient(); telemetry.TrackEvent("StartofAnewFlow"); var sample = new MetricTelemetry(); sample.Name = "usercomputertime"; sample.Sum = 45; telemetry.TrackMetric(sample); CloudStorageAccount storageAccount; // Get information about a storage account from a connection string. storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=myjumlstorage;AccountKey=JlEoLSkdSvL0z4S73JPjp+AdMipXwt3sMYKB7hW6Kl4Kp3IYVa6Kaf9C9uFI6kdZh6vJx7D3gj5N73cWEk5rCg==;EndpointSuffix=core.windows.net"); // Create a local client for working with the storage account. CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Get a reference to a container in the storage account. CloudBlobContainer container = blobClient.GetContainerReference("jums2"); await container.CreateIfNotExistsAsync(); // Create a page blob in the newly created container. Guid g = Guid.NewGuid(); string name = "myblob-" + g.ToString() + ".jpg"; CloudPageBlob pageBlob = container.GetPageBlobReference(name); await pageBlob.CreateAsync(512 * 2 /*size*/); // size needs to be multiple of 512 bytes // Write data to the new blob. byte[] samplePagedata = new byte[512]; Random random = new Random(); random.NextBytes(samplePagedata); await pageBlob.UploadFromByteArrayAsync(samplePagedata, 0, samplePagedata.Length); return(View()); }
public void SessionIdIsSetToSessionHeader() { var metricTelemetry = new MetricTelemetry("name", 0); var source = new TestableWebTestTelemetryInitializer(new Dictionary <string, string> { { "SyntheticTest-RunId", "ID" }, { "SyntheticTest-Session", "SESSIONID" } }); source.Filters.Add(new WebTestHeaderFilter { FilterHeader = "SyntheticTest-RunId", SourceName = "Application Insights Availability Monitoring", UserIdHeader = "SyntheticTest-Location", SessionIdHeader = "SyntheticTest-Session" }); source.Initialize(metricTelemetry); Assert.AreEqual("SESSIONID", metricTelemetry.Context.Session.Id); }
public static void Run([TimerTrigger("%TimerScheduleExpression%")] TimerInfo myTimer, ILogger insightsLog, ExecutionContext context) { var msg = $"C# Timer trigger function executed at: {DateTime.Now}"; insightsLog.LogInformation(msg); var config = GetConfiguration(context); var key = config[APPINSIGHTS_INSTRUMENTATIONKEY_KEY]; var telemetryClient = new TelemetryClient() { InstrumentationKey = key }; DateTime start = DateTime.UtcNow; var username = "******"; // Track an Event //var evt = new EventTelemetry("Function called"); //UpdateTelemetryContext(evt.Context, context, username); //telemetryClient.TrackEvent(evt); // Track a Metric var r = new Random((int)DateTime.Now.Ticks); var metric = new MetricTelemetry("File Upload to Box", r.Next(200, 500)); UpdateTelemetryContext(metric.Context, context, username); telemetryClient.TrackMetric(metric); //insightsLog.LogMetric("Test Metric New", DateTime.Now.Millisecond); // Track a Dependency //var dependency = new DependencyTelemetry //{ // Name = "GET users/me", // Target = "box.com", // Timestamp = start, // Duration = TimeSpan.FromSeconds(1), // Success = false //}; //UpdateTelemetryContext(dependency.Context, context, username); //telemetryClient.TrackDependency(dependency); }
public bool Metric(string name, double value = 1, Dictionary <string, string> data = null) { try { MetricTelemetry telemetry = new MetricTelemetry(name, value); telemetry.SetOperationInfo(this); telemetry.MergeProperties(data.Safe()); this.internalTelemetryClient.TrackMetric(telemetry); return(true); } catch (Exception ex) { DiagnosticTrace.Instance.Error("An unexpected error occured when attempting to track a metric", ex, "L7i4RxdczEM"); return(false); } }
/// <summary> /// Calls AI to report a metric. /// </summary> /// <param name="roleName">Name of the role. Usually the service name.</param> /// <param name="instance">Instance identifier.</param> /// <param name="name">Name of the metric.</param> /// <param name="value">Value if the metric.</param> /// <param name="count">Number of samples for this metric.</param> /// <param name="min">Minimum value of the samples.</param> /// <param name="max">Maximum value of the samples.</param> /// <param name="sum">Sum of all of the samples.</param> /// <param name="deviation">Standard deviation of the sample set.</param> /// <param name="properties">IDictionary<string>,<string> containing name/value pairs of additional properties.</param> /// <param name="cancellationToken">CancellationToken instance.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public Task ReportMetricAsync( string roleName, string instance, string name, long value, int count, long min, long max, long sum, double deviation, IDictionary <string, string> properties, CancellationToken cancellationToken) { if (!this.IsEnabled || cancellationToken.IsCancellationRequested) { return(Task.FromResult(false)); } MetricTelemetry mt = new MetricTelemetry(name, value) { Count = count, Min = min, Max = max, StandardDeviation = deviation, }; mt.Context.Cloud.RoleName = roleName; mt.Context.Cloud.RoleInstance = instance; // Set the properties. if (properties != null) { foreach (var prop in properties) { mt.Properties.Add(prop); } } // Track the telemetry. this.telemetryClient.TrackMetric(mt); return(Task.FromResult(0)); }
private static void SerializeMetricTelemetry(MetricTelemetry metricTelemetry, JsonWriter writer) { writer.WriteStartObject(); metricTelemetry.WriteTelemetryName(writer, MetricTelemetry.TelemetryName); metricTelemetry.WriteEnvelopeProperties(writer); writer.WritePropertyName("data"); { writer.WriteStartObject(); // TODO: MetricTelemetry should write type as this.data.baseType once Common Schema 2.0 compliant. writer.WriteProperty("baseType", metricTelemetry.BaseType); writer.WritePropertyName("baseData"); { writer.WriteStartObject(); writer.WriteProperty("ver", metricTelemetry.Data.ver); writer.WritePropertyName("metrics"); { writer.WriteStartArray(); writer.WriteStartObject(); writer.WriteProperty("name", metricTelemetry.Metric.name); writer.WriteProperty("kind", metricTelemetry.Metric.kind.ToString()); writer.WriteProperty("value", metricTelemetry.Metric.value); writer.WriteProperty("count", metricTelemetry.Metric.count); writer.WriteProperty("min", metricTelemetry.Metric.min); writer.WriteProperty("max", metricTelemetry.Metric.max); writer.WriteProperty("stdDev", metricTelemetry.Metric.stdDev); writer.WriteEndObject(); writer.WriteEndArray(); } writer.WriteProperty("properties", metricTelemetry.Data.properties); writer.WriteEndObject(); } writer.WriteEndObject(); } writer.WriteEndObject(); }
/// <summary> /// Takes snapshot of all active metric aggregators and turns results into metric telemetry. /// </summary> private void Snapshot() { ConcurrentDictionary <Metric, SimpleMetricStatisticsAggregator> aggregatorSnapshot = Interlocked.Exchange(ref this.metricDictionary, new ConcurrentDictionary <Metric, SimpleMetricStatisticsAggregator>()); // calculate aggregation interval duration interval TimeSpan aggregationIntervalDuation = DateTimeOffset.UtcNow - this.lastSnapshotStartDateTime; this.lastSnapshotStartDateTime = DateTimeOffset.UtcNow; // prevent zero duration for interval if (aggregationIntervalDuation.TotalMilliseconds < 1) { aggregationIntervalDuation = TimeSpan.FromMilliseconds(1); } // adjust interval duration to exactly snapshot frequency if it is close (within 1%) double difference = Math.Abs(aggregationIntervalDuation.TotalMilliseconds - aggregationPeriod.TotalMilliseconds); if (difference <= aggregationPeriod.TotalMilliseconds / 100) { aggregationIntervalDuation = aggregationPeriod; } if (aggregatorSnapshot.Count > 0) { foreach (KeyValuePair <Metric, SimpleMetricStatisticsAggregator> aggregatorWithStats in aggregatorSnapshot) { if (aggregatorWithStats.Value.Count > 0) { MetricTelemetry aggergatedMetricTelemetry = CreateAggergatedMetricTelemetry(aggregatorWithStats.Key, aggregatorWithStats.Value); aggergatedMetricTelemetry.Properties.Add(intervalDurationPropertyName, ((long)aggregationIntervalDuation.TotalMilliseconds).ToString(CultureInfo.InvariantCulture)); // set the timestamp back by aggregation period aggergatedMetricTelemetry.Timestamp = DateTimeOffset.Now - aggregationPeriod; this.telemetryClient.Track(aggergatedMetricTelemetry); } } } }
private MetricTelemetry ConvertAggregateToTelemetry(MetricAggregate aggregate) { MetricTelemetry telemetryItem = new MetricTelemetry(); // Set data values: telemetryItem.Name = aggregate.MetricId; PopulateDataValues(telemetryItem, aggregate); // Set timing values: IDictionary <string, string> props = telemetryItem.Properties; if (props != null) { long periodMillis = (long)aggregate.AggregationPeriodDuration.TotalMilliseconds; props.Add(AggregationIntervalMonikerPropertyKey, periodMillis.ToString(CultureInfo.InvariantCulture)); } telemetryItem.Timestamp = aggregate.AggregationPeriodStart; // Populate TelemetryContext: IEnumerable <KeyValuePair <string, string> > nonContextDimensions; PopulateTelemetryContext(aggregate.Dimensions, telemetryItem.Context, out nonContextDimensions); // Set dimensions. We do this after the context, becasue dimensions take precedence (i.e. we potentially overwrite): if (nonContextDimensions != null) { foreach (KeyValuePair <string, string> nonContextDimension in nonContextDimensions) { telemetryItem.Properties[nonContextDimension.Key] = nonContextDimension.Value; } } // Set SDK version moniker: Util.StampSdkVersionToContext(telemetryItem); return(telemetryItem); }
private async Task AggregatorLoopAsync() { while (_isDisposed == false) { try { // Wait for end end of the aggregation period: await Task.Delay(AggregationPeriod).ConfigureAwait(continueOnCapturedContext: false); // Atomically snap the current aggregation: MetricAggregator nextAggregator = new MetricAggregator(DateTimeOffset.UtcNow); MetricAggregator prevAggregator = Interlocked.Exchange(ref _aggregator, nextAggregator); // Only send anything is at least one value was measured: if (prevAggregator != null && prevAggregator.Count > 0) { // Compute the actual aggregation period length: TimeSpan aggPeriod = nextAggregator.StartTimestamp - prevAggregator.StartTimestamp; if (aggPeriod.TotalMilliseconds < 1) { aggPeriod = TimeSpan.FromMilliseconds(1); } // Construct the metric telemetry item and send: var aggregatedMetricTelemetry = new MetricTelemetry( Name, prevAggregator.Count, prevAggregator.Sum, prevAggregator.Min, prevAggregator.Max, prevAggregator.StandardDeviation); aggregatedMetricTelemetry.Properties["AggregationPeriod"] = aggPeriod.ToString("c"); _telemetryClient.Track(aggregatedMetricTelemetry); } } catch (Exception) { //TODO log it for now just stop the error. } } }
/// <summary> /// Generates telemetry object based on the metric aggregator. /// </summary> /// <param name="metric">Metric definition.</param> /// <param name="statistics">Metric aggregator statistics calculated for a period of time.</param> /// <returns>Metric telemetry object resulting from aggregation.</returns> private static MetricTelemetry CreateAggergatedMetricTelemetry(Metric metric, SimpleMetricStatisticsAggregator statistics) { var telemetry = new MetricTelemetry( metric.Name, statistics.Count, statistics.Sum, statistics.Min, statistics.Max, statistics.StandardDeviation); if (metric.Dimensions != null) { foreach (KeyValuePair <string, string> property in metric.Dimensions) { telemetry.Properties.Add(property); } } return(telemetry); }
public void SimpleGaugeUsageExample() { TelemetryConfiguration configuraiton = new TelemetryConfiguration(); TelemetryClient client = new TelemetryClient(configuraiton); client.Context.Properties["a"] = "b"; client.Gauge("test", () => { return(10); }); var counters = configuraiton.GetCounters(); Assert.AreEqual(1, counters.Count); MetricTelemetry metric = counters[0].GetValueAndReset(); Assert.AreEqual(10, metric.Value); Assert.AreEqual(null, metric.Count); Assert.AreEqual("test", metric.Name); Assert.AreEqual("b", metric.Context.Properties["a"]); }
public void Initializer_AddsPrefix_MetricTelemetry() { // Create a Metric telemetry with some SDK version string originalVersion = "azwapccore:2.9.1-26132"; var metricTelemetry = new MetricTelemetry("metric", 100.00); metricTelemetry.Context.GetInternalContext().SdkVersion = originalVersion; // Apply Initializer var initializer = new MetricSdkVersionTelemetryInitializer(); initializer.Initialize(metricTelemetry); var actualSdkVersion = metricTelemetry.Context.GetInternalContext().SdkVersion; // Validate that "f_" is prefixed Assert.StartsWith("f_", actualSdkVersion); // And validate that original version is kept after "f_" Assert.EndsWith(originalVersion, actualSdkVersion); }
public void Initializer_DoesNotThrowOnEmptyOrNullVersion_MetricTelemetry() { // Create a Metric telemetry. var metricTelemetry = new MetricTelemetry("metric", 100.00); var initializer = new MetricSdkVersionTelemetryInitializer(); // Assign Empty Version metricTelemetry.Context.GetInternalContext().SdkVersion = string.Empty; // Apply Initializer initializer.Initialize(metricTelemetry); // Assign Null Version metricTelemetry.Context.GetInternalContext().SdkVersion = null; // Apply Initializer initializer.Initialize(metricTelemetry); // Nothing to validate. If an exception was thrown, test would fail. }
/// <summary> /// Write an metric to Application Insights /// </summary> /// <param name="name">Name of the metric</param> /// <param name="sum">Total sum of all samples taken in this metric</param> /// <param name="count">Total count of samples in this metric</param> /// <param name="max">Maximum value of this metric</param> /// <param name="min">Minimum value of this metric</param> /// <param name="standardDeviation">Standard deviation of this metric</param> /// <param name="customProperties">Custom properties that provide context for the specific metric</param> /// <exception cref="ArgumentNullException">Exception thrown when event name was not valid</exception> public void TrackSampledMetric(string name, double sum, int?count, double?max, double?min, double?standardDeviation, Dictionary <string, string> customProperties) { Guard.AgainstNullOrWhitespace(name, nameof(name)); Guard.AgainstNull(customProperties, nameof(customProperties)); var metricTelemetry = new MetricTelemetry { Name = name, Sum = sum, Count = count, Max = max, Min = min, StandardDeviation = standardDeviation }; metricTelemetry.Properties.AddRange(customProperties); telemetryClient.TrackMetric(metricTelemetry); }
private MetricTelemetry CreateMetricTelemetry(string metricName, RunningStatistics statistics) { var telemetry = new MetricTelemetry() { Name = metricName, Count = (int)statistics.Count, Value = statistics.Mean, Max = statistics.Maximum, Min = statistics.Minimum }; if (statistics.Count >= 2) { telemetry.StandardDeviation = statistics.StandardDeviation; } SetCommonProperties(telemetry.Properties); return(telemetry); }
/// <summary> /// Returns the current value of the rate counter if enough information exists. /// </summary> /// <returns> MetricTelemetry object.</returns> public MetricTelemetry GetValueAndReset() { MetricTelemetry metric = new MetricTelemetry(); DateTimeOffset currentTime = System.DateTimeOffset.Now; var timeDifferenceInSeconds = currentTime.Subtract(this.dateTime).Seconds; metric.Name = this.name; metric.Context.GetInternalContext().SdkVersion = SdkVersionAzureWebApp.sdkVersionAzureWebApp; if (this.lastValue == null) { if (this.counter == null) { this.lastValue = this.cacheHelper.GetCounterValue(this.jsonId, this.environmentVariable); } else { this.lastValue = this.counter.GetValueAndReset().Value; } this.dateTime = currentTime; return(metric); } if (this.counter == null) { metric.Value = (timeDifferenceInSeconds != 0) ? (this.cacheHelper.GetCounterValue(this.jsonId, this.environmentVariable) - (double)this.lastValue) / timeDifferenceInSeconds : 0; this.lastValue = this.cacheHelper.GetCounterValue(this.jsonId, this.environmentVariable); } else { metric.Value = (timeDifferenceInSeconds != 0) ? (this.counter.GetValueAndReset().Value - (double)this.lastValue) / timeDifferenceInSeconds : 0; this.lastValue = this.counter.GetValueAndReset().Value; } this.dateTime = currentTime; return(metric); }
private void TrackMetric(EventData e, IReadOnlyCollection <EventMetadata> metadata) { Debug.Assert(metadata != null); foreach (EventMetadata metricMetadata in metadata) { MetricData metricData; var result = MetricData.TryGetData(e, metricMetadata, out metricData); if (result.Status != DataRetrievalStatus.Success) { this.healthReporter.ReportWarning("ApplicationInsightsOutput: " + result.Message, EventFlowContextIdentifiers.Output); continue; } MetricTelemetry mt = new MetricTelemetry(); mt.Name = metricData.MetricName; mt.Value = metricData.Value; AddProperties(mt, e); telemetryClient.TrackMetric(mt); } }
private MetricTelemetry GetTelemetry(MetricType metric, string name, object value, double sampleRate, IEnumerable <string> tags) { var telemetry = new MetricTelemetry(name, Convert.ToDouble(value)); if (tags == null || !tags.Any()) { return(telemetry); } foreach (string tag in tags) { string[] nvp = tag.Split(':'); if (nvp.Length != 2) { continue; //invalid tag pair, so skip it } telemetry.Properties.Add(nvp[0], nvp[1]); } return(telemetry); }
private void PostProcess(string functionName, DateTime start, DateTime end) { PostProcess(); var elapse = end - start; // Track an Event var evt = new EventTelemetry($"Function - '{functionName}' ended on {end}"); TelemetryClient.TrackEvent(evt); // Track a Metric var metric = new MetricTelemetry($"Function - '{functionName}' spent", elapse.TotalMilliseconds) { MetricNamespace = $"{functionName}.ProcessedTime" }; TelemetryClient.TrackMetric(metric); Logger.LogMetric($"Function - '{functionName}'", elapse.TotalMilliseconds); }
private void TrackMetric(LogLevel logLevel, EventId eventId, string message, MetricLog metric) { var telemetry = new MetricTelemetry(metric.Name, metric.Value); telemetry.Count = metric.Count; telemetry.Min = metric.Min; telemetry.Max = metric.Max; telemetry.StandardDeviation = metric.StandardDeviation; if (metric.Properties != null) { foreach (var item in metric.Properties) { telemetry.Properties[item.Key] = item.Value?.ToString(); } } telemetry.Properties["logger"] = categoryName; telemetry.Properties["eventName"] = eventId.Name; telemetry.Properties["eventId"] = eventId.Id.ToString(); telemetry.Properties["remark"] = metric.Remark; telemetryClient.TrackMetric(telemetry); }
/// <summary> /// This method was separated because will be invoked for LighTelemetry. /// When the method 'EndAggregation' is called, the method above will send all data aggregated to AppInsights /// </summary> public void SendAggregationMetrics() { try { /// Atomically snap the current aggregation: LightMetricAggregator nextAggregator = new LightMetricAggregator(DateTimeOffset.UtcNow); LightMetricAggregator prevAggregator = Interlocked.Exchange(ref _aggregator, nextAggregator); /// Only send anything is at least one value was measured: if (prevAggregator != null && prevAggregator.Count > 0) { /// Compute the actual aggregation period length: TimeSpan aggPeriod = nextAggregator.StartTimestamp - prevAggregator.StartTimestamp; if (aggPeriod.TotalMilliseconds < 1) { /// Just if the timestamp is smaller than one second, we send to appinsights the milliseconds aggPeriod = TimeSpan.FromMilliseconds(1); } /// Construct the metric telemetry item and send to AppInsights var aggregatedMetricTelemetry = new MetricTelemetry( Name, prevAggregator.Count, prevAggregator.Sum, prevAggregator.Min, prevAggregator.Max, prevAggregator.StandardDeviation); aggregatedMetricTelemetry.Properties["AggregationPeriod"] = aggPeriod.ToString("c"); ///Send aggregated data to AppInsights _telemetry.TrackAggregateMetric(aggregatedMetricTelemetry); } } catch (Exception ex) { ///There are some erros AppInsights will be notified. this._telemetry.TrackException(ex); } }
public void CanSetEnvelopeNameForSupportedTypes() { string testEnvelopeName = "Non_Standard*Envelope.Name"; var at = new AvailabilityTelemetry(); var dt = new DependencyTelemetry(); var et = new EventTelemetry(); var ext = new ExceptionTelemetry(); var mt = new MetricTelemetry(); var pvpt = new PageViewPerformanceTelemetry(); var pvt = new PageViewTelemetry(); var rt = new RequestTelemetry(); #pragma warning disable CS0618 // Type or member is obsolete var pct = new PerformanceCounterTelemetry(); var sst = new SessionStateTelemetry(); #pragma warning restore CS0618 // Type or member is obsolete Assert.IsTrue(at.TrySetEnvelopeName(testEnvelopeName)); Assert.IsTrue(dt.TrySetEnvelopeName(testEnvelopeName)); Assert.IsTrue(et.TrySetEnvelopeName(testEnvelopeName)); Assert.IsTrue(ext.TrySetEnvelopeName(testEnvelopeName)); Assert.IsTrue(mt.TrySetEnvelopeName(testEnvelopeName)); Assert.IsTrue(pvpt.TrySetEnvelopeName(testEnvelopeName)); Assert.IsTrue(pvt.TrySetEnvelopeName(testEnvelopeName)); Assert.IsTrue(rt.TrySetEnvelopeName(testEnvelopeName)); Assert.IsTrue(pct.TrySetEnvelopeName(testEnvelopeName)); Assert.IsTrue(sst.TrySetEnvelopeName(testEnvelopeName)); Assert.AreEqual(testEnvelopeName, at.GetEnvelopeName()); Assert.AreEqual(testEnvelopeName, dt.GetEnvelopeName()); Assert.AreEqual(testEnvelopeName, et.GetEnvelopeName()); Assert.AreEqual(testEnvelopeName, ext.GetEnvelopeName()); Assert.AreEqual(testEnvelopeName, mt.GetEnvelopeName()); Assert.AreEqual(testEnvelopeName, pvpt.GetEnvelopeName()); Assert.AreEqual(testEnvelopeName, pvt.GetEnvelopeName()); Assert.AreEqual(testEnvelopeName, rt.GetEnvelopeName()); Assert.AreEqual(testEnvelopeName, pct.Data.GetEnvelopeName()); Assert.AreEqual(testEnvelopeName, sst.Data.GetEnvelopeName()); }
public Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("SunTest C# HTTP trigger function processed a request."); DateTime start = DateTime.UtcNow; // Parse query parameter string name = req.Query .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0) .Value; // Track an Event var evt = new EventTelemetry("Function called"); evt.Context.User.Id = name; this.telemetryClient.TrackEvent(evt); // Track a Metric var metric = new MetricTelemetry("Test Metric", DateTime.Now.Millisecond); metric.Context.User.Id = name; this.telemetryClient.TrackMetric(metric); // Track a Dependency var dependency = new DependencyTelemetry { Name = "GET api/planets/1/", Target = "swapi.co", Data = "https://swapi.co/api/planets/1/", Timestamp = start, Duration = DateTime.UtcNow - start, Success = true }; dependency.Context.User.Id = name; this.telemetryClient.TrackDependency(dependency); return(Task.FromResult <IActionResult>(new OkResult())); }
public void AiTelemetryConverterTests_ThrowsOnEmptyMetric() { // ARRANGE var timestamp = DateTimeOffset.UtcNow; Telemetry telemetry = new Telemetry() { Ver = 5, DataTypeName = "Metric", DateTime = timestamp.ToString("o"), SamplingRate = new Google.Protobuf.WellKnownTypes.DoubleValue() { Value = 25 }, SequenceNumber = "50", InstrumentationKey = "ikey", Metric = new Metric() { Ver = 6 } }; // empty telemetry.Metric.Metrics //telemetry.Metric.Metrics.Add(new DataPoint() { Ns = "ns1", Name = "Metric1", Kind = DataPointType.Measurement, Value = 11, Count = new Google.Protobuf.WellKnownTypes.Int32Value() { Value = 1 } }); // ACT try { MetricTelemetry result = AiTelemetryConverter.ConvertMetricToSdkApi(telemetry); } catch (ArgumentException e) { // ASSERT Assert.AreEqual("Metrics list can't be empty", e.Message); return; } Assert.Fail("Expected an exception"); }
public void TestMetricTelemetry() { var telemetry = new Microsoft.ApplicationInsights.TelemetryClient { InstrumentationKey = "2119853a-bc51-429e-962d-4b7f9cda9a3f" .ToString() }; for (int i = 0; i < 100; i++) { MetricTelemetry metricTelemetry = new MetricTelemetry(); DateTime dt = DateTime.Now; metricTelemetry.Count = 1; metricTelemetry.Max = 10; metricTelemetry.Min = 0; metricTelemetry.Sequence = i.ToString(); metricTelemetry.Sum = Math.Sqrt(i * 12334); telemetry.TrackMetric(metricTelemetry); } telemetry.Flush(); }
public static void ValidateNumericAggregateValues(ITelemetry aggregate, string ns, string name, int count, double sum, double max, double min, double?stdDev) { Assert.IsNotNull(aggregate); MetricTelemetry metricAggregate = aggregate as MetricTelemetry; Assert.IsNotNull(metricAggregate); Assert.AreEqual(ns, metricAggregate.MetricNamespace, "metricAggregate.MetricNamespace mismatch"); Assert.AreEqual(name, metricAggregate.Name, "metricAggregate.Name mismatch"); Assert.AreEqual(count, metricAggregate.Count, "metricAggregate.Count mismatch"); Assert.AreEqual(sum, metricAggregate.Sum, TestUtil.MaxAllowedPrecisionError, "metricAggregate.Sum mismatch"); Assert.AreEqual(max, metricAggregate.Max.Value, TestUtil.MaxAllowedPrecisionError, "metricAggregate.Max mismatch"); Assert.AreEqual(min, metricAggregate.Min.Value, TestUtil.MaxAllowedPrecisionError, "metricAggregate.Min mismatch"); // For very large numbers we perform an approx comparison. if (!stdDev.HasValue) { Assert.IsNull(metricAggregate.StandardDeviation); } else { if (Math.Abs(stdDev.Value) > Int64.MaxValue) { double expectedStdDevScale = Math.Floor(Math.Log10(Math.Abs(stdDev.Value))); double actualStdDevScale = Math.Floor(Math.Log10(Math.Abs(metricAggregate.StandardDeviation.Value))); Assert.AreEqual(expectedStdDevScale, actualStdDevScale, "metricAggregate.StandardDeviation (exponent) mismatch"); Assert.AreEqual( stdDev.Value / Math.Pow(10, expectedStdDevScale), metricAggregate.StandardDeviation.Value / Math.Pow(10, actualStdDevScale), TestUtil.MaxAllowedPrecisionError, "metricAggregate.StandardDeviation (significant part) mismatch"); } else { Assert.AreEqual(stdDev.Value, metricAggregate.StandardDeviation.Value, TestUtil.MaxAllowedPrecisionError, "metricAggregate.StandardDeviation mismatch"); } } }
public void StampSdkVersionToContext() { Util.StampSdkVersionToContext(null); ITelemetry eventTelemetry = new EventTelemetry("FooEvent"); Assert.IsNull(eventTelemetry?.Context?.GetInternalContext()?.SdkVersion); Util.StampSdkVersionToContext(eventTelemetry); Assert.IsNotNull(eventTelemetry.Context); Assert.IsNotNull(eventTelemetry.Context.GetInternalContext()); TestUtil.ValidateSdkVersionString(eventTelemetry.Context.GetInternalContext().SdkVersion); ITelemetry metricTelemetry = new MetricTelemetry("FooMetric", count: 3, sum: 30, min: 10, max: 10, standardDeviation: 0); Util.StampSdkVersionToContext(metricTelemetry); Assert.IsNotNull(metricTelemetry.Context); Assert.IsNotNull(metricTelemetry.Context.GetInternalContext()); TestUtil.ValidateSdkVersionString(metricTelemetry.Context.GetInternalContext().SdkVersion); }
/// <summary> /// Send a <see cref="MetricTelemetry"/> for aggregation in Metric Explorer. /// </summary> /// <param name="name">Metric name.</param> /// <param name="value">Metric value.</param> /// <param name="properties">Named string values you can use to classify and filter metrics.</param> public void TrackMetric(string name, double value, IDictionary<string, string> properties = null) { var telemetry = new MetricTelemetry(name, value); if (properties != null && properties.Count > 0) { Utils.CopyDictionary(properties, telemetry.Properties); } this.TrackMetric(telemetry); }
/// <summary> /// Send a <see cref="MetricTelemetry"/> for aggregation in Metric Explorer. /// </summary> public void TrackMetric(MetricTelemetry telemetry) { if (telemetry == null) { telemetry = new MetricTelemetry(); } this.Track(telemetry); }