コード例 #1
0
        public async Task ExecuteAsync(EnsurePoolSize command, CancellationToken cancellationToken)
        {
            var vacantInstanceTarget = await repository.GetVacantInstanceTargetAsync(cancellationToken);

            var vacantInstanceCount = await repository.GetVacantInstanceCountAsync(cancellationToken);

            var vacantInstanceDeficit = vacantInstanceTarget - vacantInstanceCount;

            telemetryClient.GetMetric("pools.vacant.count").TrackValue(vacantInstanceCount);
            telemetryClient.GetMetric("pools.vacant.target").TrackValue(vacantInstanceTarget);
            telemetryClient.GetMetric("pools.vacant.deficit").TrackValue(vacantInstanceDeficit);

            if (vacantInstanceDeficit == 0)
            {
                return;
            }

            while (vacantInstanceDeficit > 0)
            {
                var allocationBlockSize = await repository.GetAllocationBlockSizeAsync(cancellationToken);

                telemetryClient.GetMetric("pools.vacant.block.size").TrackValue(vacantInstanceTarget);
                using (telemetryClient.TrackMetricTimer("pools.vacant.grow.block.time"))
                {
                    Task[] addTasks = new Task[Math.Min(allocationBlockSize, vacantInstanceDeficit)];
                    for (var i = 0; i < addTasks.Length; i++)
                    {
                        addTasks[i] = addVacantInstance.ExecuteAsync(new PushVacantInstance(), cancellationToken);
                        vacantInstanceDeficit--;
                    }

                    await Task.WhenAll(addTasks);
                }
            }
        }
コード例 #2
0
        public async Task ExecuteAsync(AddAliasProperties requestContent, DateTime enqueuedTimeUtc)
        {
            _telemetryClient.GetMetric("MethodUsage", "Method").TrackValue(1, "AddAlias");

            var intentionalDelay = Random.Next(3000);
            await Task.Delay(intentionalDelay);

            _logger.LogInformation("Adding alias to database: {alias}", JsonConvert.SerializeObject(requestContent));
            using (var connection = await _sqlConnectionFactory.CreateConnectionAsync())
            {
                using (var command = new SqlCommand(AddAliasQuery, connection))
                {
                    command.Parameters.AddWithValue("url", requestContent.Url);
                    command.Parameters.AddWithValue("alias", requestContent.Alias);
                    await connection.OpenAsync();

                    await command.ExecuteNonQueryAsync();

                    connection.Close();
                }
            }

            var delay = DateTime.UtcNow - enqueuedTimeUtc;
            var delayInMiliSeconds = (int)delay.TotalMilliseconds;

            _logger.LogTrace("Recording delay of {delay} ms in adding alias", delayInMiliSeconds);

            _telemetryClient.GetMetric("AddAliasProcessingDelay").TrackValue(delayInMiliSeconds);
        }
コード例 #3
0
 public void RegisterMetrics(TelemetryClient telemetry)
 {
     NumThreads    = telemetry.GetMetric("dotnet_threadpool_num_threads");
     NumIocThreads = telemetry.GetMetric("dotnet_threadpool_io_num_threads");
     // Throughput = metrics.CreateCounter("dotnet_threadpool_throughput_total", "The total number of work items that have finished execution in the thread pool");
     AdjustmentsTotal = telemetry.GetMetric("dotnet_threadpool_adjustments_total", "adjustment_reason");
 }
        public void GetConfiguration()
        {
            TelemetryConfiguration pipeline = TestUtil.CreateAITelemetryConfig();
            TelemetryClient        client   = new TelemetryClient(pipeline);

            {
                Metric metric = client.GetMetric("CowsSold");
                Assert.AreEqual(MetricConfigurations.Common.Measurement(), metric.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Measurement(), metric.GetConfiguration());
            }
            {
                Metric metric = client.GetMetric("HorsesSold", MetricConfigurations.Common.Measurement());
                Assert.AreEqual(MetricConfigurations.Common.Measurement(), metric.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Measurement(), metric.GetConfiguration());
            }
            {
                MetricConfiguration config = new MetricConfiguration(10, 5, new MetricSeriesConfigurationForMeasurement(false));
                Metric metric = client.GetMetric("ChickensSold", config);
                Assert.AreEqual(config, metric.GetConfiguration());
                Assert.AreSame(config, metric.GetConfiguration());
            }

            TestUtil.CompleteDefaultAggregationCycle(pipeline.GetMetricManager());
            pipeline.Dispose();
        }
コード例 #5
0
        public async Task <ActionResult <string> > Get(string traceGuid, string cpumax)
        {
            const string controllerName = "Aquarius";

            var metricName = $"{controllerName}Transactions";
            var message    = $"{controllerName} has been invoked. TraceGuid={traceGuid}";

            _telemetryClient.TrackEvent(message);
            _telemetryClient.GetMetric(metricName).TrackValue(1);
            _logger.LogInformation(message);


            Metric compundMetric = _telemetryClient.GetMetric("AquariusCount", "Status");
            var    num           = DateTime.Now.Second;

            if (num % 2 == 0)
            {
                compundMetric.TrackValue(1, "AquariusSuccess");
                _logger.LogInformation($"Call to Aquarius was pseudo-succesful");
            }
            else
            {
                compundMetric.TrackValue(1, "AquariusFailure");
                _logger.LogInformation($"Call to Aquarius was pseudo-failure");
            }

            return($"Aquarius is done");
        }
コード例 #6
0
        public void Process(ITelemetry item)
        {
            // Check telemetry type
            if (item is DependencyTelemetry)
            {
                var d = item as DependencyTelemetry;

                Interlocked.Increment(ref totalDependencyCount);
                telemetryClient.GetMetric("# of dependencies").TrackValue(totalDependencyCount);
                telemetryClient.GetMetric($"{d.Type} Dependencies durations (ms)").TrackValue(d.Duration.TotalMilliseconds);

                if (totalDependencyCount % 10 == 0)
                {
                    telemetryClient.Flush();
                }

                if (d.Duration < TimeSpan.FromMilliseconds(100))
                {
                    // If dependency duration > 100 ms then stop telemetry
                    // processing and return from the pipeline
                    return;
                }
            }
            this.next.Process(item);
        }
コード例 #7
0
        public async Task Handle(Message message, IMessageHandler next)
        {
            var processingStartTime = DateTimeOffset.UtcNow;

            try
            {
                await next.Handle(message);

                telemetryClient.GetMetric("Messages Successfully Processed").TrackValue(1);
            }
            catch (Exception)
            {
                telemetryClient.GetMetric("Messages Processing Errors").TrackValue(1);
                throw;
            }

            var dateSent          = (DateTimeOffset)message.UserProperties["DateTimeSent"];
            var processingEndTime = DateTimeOffset.UtcNow;

            var processingTime  = processingEndTime - processingStartTime;
            var criticalTime    = processingEndTime - dateSent;
            var timeToExceedSla = sla - criticalTime;

            telemetryClient.GetMetric("Processing Time").TrackValue(processingTime.TotalSeconds);
            telemetryClient.GetMetric("Critical Time").TrackValue(criticalTime.TotalSeconds);
            telemetryClient.GetMetric("Time to exceed SLA").TrackValue(timeToExceedSla.TotalSeconds);
        }
コード例 #8
0
        public void GetConfiguration()
        {
            TelemetryConfiguration pipeline = Util.CreateAITelemetryConfig();
            TelemetryClient        client   = new TelemetryClient(pipeline);

            {
                Metric metric = client.GetMetric("CowsSold");
                Assert.AreEqual(MetricConfigurations.Measurement, metric.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Measurement, metric.GetConfiguration());
            }
            {
                Metric metric = client.GetMetric("PigsSold", MetricConfigurations.Accumulator);
                Assert.AreEqual(MetricConfigurations.Accumulator, metric.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Accumulator, metric.GetConfiguration());
            }
            {
                Metric metric = client.GetMetric("HorsesSold", MetricConfigurations.Measurement);
                Assert.AreEqual(MetricConfigurations.Measurement, metric.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Measurement, metric.GetConfiguration());
            }
            {
                IMetricConfiguration config = new SimpleMetricConfiguration(10, 5, new SimpleMetricSeriesConfiguration(false));
                Metric metric = client.GetMetric("ChickensSold", config);
                Assert.AreEqual(config, metric.GetConfiguration());
                Assert.AreSame(config, metric.GetConfiguration());
            }

            Util.CompleteDefaultAggregationCycle(pipeline.Metrics());
            pipeline.Dispose();
        }
コード例 #9
0
        private Metric GetAppInsightsMetric(MetricIdentifier id, params string[] dimensionNames)
        {
            if (dimensionNames == null)
            {
                return(_telemetryClient.GetMetric(id));
            }
            switch (dimensionNames.Length)
            {
            case 1:
                return(_telemetryClient.GetMetric(id.MetricId, dimensionNames[0]));

            case 2:
                return(_telemetryClient.GetMetric(id.MetricId, dimensionNames[0], dimensionNames[1]));

            case 3:
                return(_telemetryClient.GetMetric(id.MetricId, dimensionNames[0], dimensionNames[1],
                                                  dimensionNames[2]));

            case 4:
                return(_telemetryClient.GetMetric(id.MetricId, dimensionNames[0], dimensionNames[1],
                                                  dimensionNames[2], dimensionNames[3]));

            default:
                throw new Exception("Too many dimensions");
            }
        }
コード例 #10
0
        public DependencyFilteringWithMetricsTelemetryProcessor(ITelemetryProcessor next, TelemetryConfiguration configuration)
        {
            this.next = next;
            var client = new TelemetryClient(configuration);

            this.numberOfDependencies = client.GetMetric("# of dependencies", "type");
            this.dependenciesDuration = client.GetMetric("dependencies duration (ms)", "type");
        }
コード例 #11
0
        public void TrackMetric(string metricName, double value)
        {
            if (string.IsNullOrWhiteSpace(metricName))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(metricName));
            }

            _telemetryClient.GetMetric(metricName).TrackValue(value);
        }
コード例 #12
0
        public void CreateToken(string user)
        {
            TrackEvent("CreateToken", new Dictionary <string, string>
            {
                { "User", user }
            });

            _telemetryClient.GetMetric("CreateToken").TrackValue(1);
        }
コード例 #13
0
        public ActionResult <IEnumerable <string> > TrackMetric()
        {
            _telemetryClient.GetMetric("MyCustomMetric", "Company", "User").TrackValue(1, "a", "1");
            _telemetryClient.GetMetric("MyCustomMetric", "Company", "User").TrackValue(2, "a", "1");
            _telemetryClient.GetMetric("MyCustomMetric", "Company", "User").TrackValue(3, "a", "1");
            _telemetryClient.GetMetric("MyCustomMetric", "Company", "User").TrackValue(4, "a", "2");
            _telemetryClient.GetMetric(new MetricIdentifier("Performance", "MyOtherMetric")).TrackValue(5);

            return(new[] { "value1", "value2" });
        }
コード例 #14
0
        public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            Task <DateTimeOffset> oldestWaitingToBeDeleated = _backgroundServiceHealthCheckCache.GetOrAddOldestTimeAsync(_indexDataStore.GetOldestDeletedAsync, cancellationToken);
            Task <int>            numReachedMaxedRetry      = _backgroundServiceHealthCheckCache.GetOrAddNumExhaustedDeletionAttemptsAsync(
                t => _indexDataStore.RetrieveNumExhaustedDeletedInstanceAttemptsAsync(_deletedInstanceCleanupConfiguration.MaxRetries, t),
                cancellationToken);

            _telemetryClient.GetMetric("Oldest-Requested-Deletion").TrackValue((await oldestWaitingToBeDeleated).ToUnixTimeSeconds());
            _telemetryClient.GetMetric("Count-Deletions-Max-Retry").TrackValue(await numReachedMaxedRetry);

            return(HealthCheckResult.Healthy("Successfully computed values for background service."));
        }
コード例 #15
0
        public static async Task Run(
            // Incoming events delivered to the IoTHub trigger this Fn
            [IoTHubTrigger(
                 eventHubName: "messages/events",
                 Connection = "IoTHubTriggerConnection",
                 ConsumerGroup = "%IoTHub_ConsumerGroup%")] EventData[] eventHubMessages,

            [CosmosDB(
                 databaseName: "SmartCampusSandbox",
                 collectionName: "Devices",
                 ConnectionStringSetting = "CosmosDBConnection")] DocumentClient docDbClient,

            [CosmosDB(
                 databaseName: "SmartCampusSandbox",
                 collectionName: "Devices",
                 ConnectionStringSetting = "CosmosDBConnection")] IAsyncCollector <DeviceDocument> outputDeviceDocumentsUpdated,

            // Outgoing transformed event data is delivered to this Event Hub
            [EventHub(
                 eventHubName: "iotworxoutputevents",
                 Connection = "EventHubConnectionAppSetting")] IAsyncCollector <string> outputEvents,

            // Incomming messages which aren't found in the reference data set will be sent here instead of to EH
            [Table("UnprovisionedDeviceTelemetry",
                   Connection = "AzureWebJobsStorage")] IAsyncCollector <DeviceTableEntity> outputUnprovisionedDevices,

            ILogger log,
            System.Threading.CancellationToken token)
        {
            //Todo - determine what the inbound BACNet message format is and desrialized/transformed accordingly

            //Deserialize all the inbound messages in the batch, preserving properties
            var messages = eventHubMessages
                           .Select(data => new BACNetIoTHubMessage(
                                       JsonConvert.DeserializeObject <BACNetTelemetryMsg>(Encoding.UTF8.GetString(data.Body)),
                                       data.SystemProperties,
                                       data.Properties))
                           .ToList();

            //Retrieve all the devices by Id in the inbound group
            var knownDeviceDocuments = await GetKnownDeviceData(messages, docDbClient, DocumentCollectionUri, log, token);

            // Handle all the messages in the batch
            await HandleMessageBatch(messages, knownDeviceDocuments, outputDeviceDocumentsUpdated,
                                     outputEvents, outputUnprovisionedDevices, log, token);

            //Track Metrics
            TelemetryClient client = new TelemetryClient();

            client.GetMetric("BACNetIoTHubMessageBatchSize").TrackValue(eventHubMessages.Count());
            client.GetMetric("BACNetIoTHubUnprovisionedDevices").TrackValue(unprovisionedCount);
        }
コード例 #16
0
        public Task ProcessEventsAsync(PartitionContext context, IEnumerable <EventData> messages)
        {
            // Process the received data for futher processing keep it simple fast and reliable.
            try
            {
                foreach (EventData message in messages)
                {
                    // var logContext = $"--- Partition {context.Lease.PartitionId}, Owner: {context.Lease.Owner}, Offset: {message.Body.Offset} --- {DateTime.Now.ToString()}";
                    // Log.Info(logContext);

                    // if(insights) {
                    //    Metric messageRead = telemetryClient.GetMetric("EventMsgProcessed", "Partition");
                    //    messageRead.TrackValue(1, $"Partition${context.Lease.PartitionId}");
                    // }

                    if (insights)
                    {
                        telemetryClient.GetMetric("EventMsgProcessed", "Partition").TrackValue(1, context.Lease.PartitionId);
                    }

                    string data = $"{Encoding.UTF8.GetString(message.Body.Array)}";

                    var logData = JsonConvert.SerializeObject(new { Partition = context.Lease.PartitionId, Size = data.Length });

                    Log.Info($"{DateTime.Now.ToString()} {logData}");
                    Log.Debug($"{data} {Environment.NewLine}");
                }

                if (this.checkpointStopWatch.Elapsed > TimeSpan.FromSeconds(5))
                {
                    if (insights)
                    {
                        telemetryClient.GetMetric("CheckPoint").TrackValue(1);
                    }
                    lock (this)
                    {
                        this.checkpointStopWatch.Restart();
                        return(context.CheckpointAsync());
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                if (insights)
                {
                    telemetryClient.TrackTrace(ex.Message);
                }
            }

            return(Task.FromResult <object>(null));
        }
コード例 #17
0
        public static bool UploadObject(TelemetryClient tc, object obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj));
            }


            List <PropertyInfo> allProperties = null;
            String name = null;

            if (obj is Type)
            {
                allProperties = (obj as Type).GetProperties().ToList();
                name          = (obj as Type).Name;
            }
            else
            {
                allProperties = obj.GetType().GetProperties().ToList();
                name          = obj.ToString();
            }

            var boolProperties = (from a in allProperties where a.PropertyType == typeof(bool) select a).ToList();

            //var propnames = (from a in boolProperties select a.Name).ToList();
            MetricIdentifier micount = new MetricIdentifier(name, "MetricsReportCount");
            var mcount = tc.GetMetric(micount);

            mcount.TrackValue(1);

            foreach (var prop in boolProperties)
            {
                MetricIdentifier mi = new MetricIdentifier(name, prop.Name);
                var metric          = tc.GetMetric(mi);
                var val             = prop.GetValue(obj, null);
                Console.WriteLine("{0}={1}", prop.Name, val);
                if (Boolean.TryParse(val.ToString(), out bool boolval))
                {
                    if (boolval)
                    {
                        metric.TrackValue(1);
                    }
                    else
                    {
                        metric.TrackValue(0);
                    }
                }
            }

            return(true);
        }
コード例 #18
0
        public void SendMetric(string name, double value)
        {
            if (!HasOptedIn)
            {
                return;
            }

            Debug.Write($"User opted in, sending metric {name}, value {value}");

            var mi = telemetryClient.GetMetric(name);

            mi.TrackValue(value);
            Debug.Write("Metric tracked");
        }
コード例 #19
0
        public void RunReport(MetricsData metricsData, Func <HealthStatus> healthStatus, CancellationToken token)
        {
            foreach (var gauge in metricsData.Gauges)
            {
                var metric = telemetryClient.GetMetric(gauge.Name);
                metric.TrackValue(gauge.Value);
            }


            foreach (var counter in metricsData.Counters)
            {
                var metric = telemetryClient.GetMetric(counter.Name);
                metric.TrackValue(counter.Value.Count);
            }

            foreach (var timer in metricsData.Timers)
            {
                var metric = telemetryClient.GetMetric(timer.Name + "[ActiveSessions]");
                metric.TrackValue(timer.Value.Rate.OneMinuteRate);

                metric = telemetryClient.GetMetric(timer.Name + "[Rate]");
                metric.TrackValue(timer.Value.Rate.OneMinuteRate);
            }
            telemetryClient.Flush();

            //Console.Clear();
            //var table = new ConsoleTable("Parametr", "Value", "unit");

            //foreach (var gauge in metricsData.Gauges)
            //{
            //    table.AddRow(gauge.Name, gauge.Value, gauge.Unit);
            //}


            //foreach (var counter in metricsData.Counters)
            //{
            //    table.AddRow(counter.Name, counter.Value.Count, counter.Unit);
            //}

            //foreach (var timer in metricsData.Timers)
            //{
            //    table.AddRow(timer.Name + "[ActiveSessions]", timer.Value.ActiveSessions, timer.Unit);
            //    table.AddRow(timer.Name + "[Rate]", timer.Value.Rate.OneMinuteRate, timer.Unit);

            //}

            //table.Write();
            //Console.WriteLine();
        }
コード例 #20
0
        public async Task <ActionResult <string> > Get(string traceGuid)
        {
            const string controllerName = "Scorpio";
            var          metricName     = $"{controllerName}Transactions";
            var          message        = $"{controllerName} has been invoked. TraceGuid={traceGuid}";

            _telemetryClient.TrackEvent(message);
            _telemetryClient.GetMetric(metricName).TrackValue(1);

            // call some methods that do some artificial work
            await AccessDatabase();

            DoArtificialWork(traceGuid);
            return(await WriteBlob());
        }
コード例 #21
0
 public void RegisterMetrics(TelemetryClient telemetry)
 {
     GcCollectionSeconds       = telemetry.GetMetric("dotnet_gc_collection_seconds", LabelGeneration, LabelType);
     GcPauseSeconds            = telemetry.GetMetric("dotnet_gc_pause_seconds");
     GcCollectionReasons       = telemetry.GetMetric("dotnet_gc_collection_reasons_total", LabelReason);
     GcCpuRatio                = telemetry.GetMetric("dotnet_gc_cpu_ratio");
     GcPauseRatio              = telemetry.GetMetric("dotnet_gc_pause_ratio");
     AllocatedBytes            = telemetry.GetMetric("dotnet_gc_allocated_bytes_total", LabelHeap);
     GcHeapSizeBytes           = telemetry.GetMetric("dotnet_gc_heap_size_bytes", LabelGeneration);
     GcNumPinnedObjects        = telemetry.GetMetric("dotnet_gc_pinned_objects");
     GcFinalizationQueueLength = telemetry.GetMetric("dotnet_gc_finalization_queue_length");
 }
コード例 #22
0
        public async Task <string> GetAliasAsync(string alias)
        {
            string result;

            _telemetryClient.GetMetric("MethodUsage", "Method").TrackValue(1, "GetAlias");

            _logger.LogInformation("Fetching alias");
            using (var sqlConnection = new SqlConnection(_configuration.GetString("Database.ConnectionString")))
            {
                using (var command = new SqlCommand(GetAliasQuery, sqlConnection))
                {
                    command.Parameters.AddWithValue("alias", alias);
                    await sqlConnection.OpenAsync();

                    result = (string)await command.ExecuteScalarAsync();
                }
            }

            _logger.LogDebug("Recording usage");
            var redisConnection = _redisDatabaseFactory.GetDatabase();
            await Task.WhenAll(
                redisConnection.HashIncrementAsync(alias, "requestCount"),
                redisConnection.HashSetAsync(alias, "lastRequest", DateTime.UtcNow.ToString("O")));

            return(result);
        }
コード例 #23
0
    protected DocumentExpander(bool optional, TelemetryClient telemetryClient)
    {
        Optional = optional;

        this.telemetryClient = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));
        this.expandMetric    = telemetryClient.GetMetric("DocumentExpander", "ExpanderType", "DocumentType");
    }
コード例 #24
0
        internal MetricExtractorActivityProcessor(
            string processorName,
            Func <Activity, bool> activitySelector,
            TelemetryClient applicationInsightsClient,
            string outputMetricName,
            Func <Activity, double?> measurementValueExtractor,
            IEnumerable <Tuple <Func <Activity, string>, string> > activityLabelsToMetricDimensionsMap)
        {
            _name                      = Util.SpellNull(processorName);
            _activitySelector          = Util.EnsureNotNull(activitySelector, nameof(activitySelector));
            _applicationInsightsClient = Util.EnsureNotNull(applicationInsightsClient, nameof(applicationInsightsClient));
            outputMetricName           = Util.EnsureNotNullOrEmpty(outputMetricName, nameof(outputMetricName));
            _measurementValueExtractor = Util.EnsureNotNull(measurementValueExtractor, nameof(measurementValueExtractor));

            if (activityLabelsToMetricDimensionsMap == null)
            {
                _metricId = new MetricIdentifier(MetricNamespace, outputMetricName);
                _dimensionLabelExtractors = new Func <Activity, string> [0];
            }
            else
            {
                _metricId = new MetricIdentifier(MetricNamespace, outputMetricName, activityLabelsToMetricDimensionsMap.Select((ln) => Util.SpellNull(ln.Item2)).ToList());
                _dimensionLabelExtractors = activityLabelsToMetricDimensionsMap.Select((ln) => (ln.Item1 ?? NullLabelExtractor)).ToArray();
            }

            _outputMetric = applicationInsightsClient.GetMetric(_metricId, MetricConfigurations.Common.Measurement(), MetricAggregationScope.TelemetryClient);
        }
コード例 #25
0
        public void Dispose()
        {
            var elapsed = _timer.Elapsed;

            _telemetry.TrackTrace(_metricId + ".Completed", new Dictionary <string, string> {
                { "duration", elapsed.ToString() }
            });
            if (string.IsNullOrEmpty(_dimension1Name))
            {
                _telemetry.GetMetric(_metricId).TrackValue(elapsed.TotalMilliseconds);
            }
            else
            {
                _telemetry.GetMetric(_metricId, _dimension1Name).TrackValue(elapsed.TotalMilliseconds, _dimension1Value);
            }
        }
コード例 #26
0
        public static async Task RunAsync(
            [EventHubTrigger("%EventHubName%", Connection = "EventHubConnection", ConsumerGroup = "%EventHubConsumerGroup%")] EventData[] messages,
            [Queue("deadletterqueue")] IAsyncCollector <DeadLetterMessage> deadLetterMessages,
            ILogger logger)
        {
            telemetryClient.GetMetric("EventHubMessageBatchSize").TrackValue(messages.Length);

            foreach (var message in messages)
            {
                DeviceState deviceState = null;

                try
                {
                    deviceState = telemetryProcessor.Deserialize(message.Body.Array, logger);

                    try
                    {
                        await stateChangeProcessor.UpdateState(deviceState, logger);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "Error updating status document", deviceState);
                        await deadLetterMessages.AddAsync(new DeadLetterMessage { Exception = ex, EventData = message, DeviceState = deviceState });
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "Error deserializing message", message.SystemProperties.PartitionKey, message.SystemProperties.SequenceNumber);
                    await deadLetterMessages.AddAsync(new DeadLetterMessage { Exception = ex, EventData = message });
                }
            }
        }
        public void GetMetric_RespectsClientContext()
        {
            IList <ITelemetry>     sentTelemetry;
            TelemetryConfiguration telemetryPipeline = Util.CreateAITelemetryConfig(out sentTelemetry);

            telemetryPipeline.InstrumentationKey = "754DD89F-61D6-4539-90C7-D886449E12BC";
            TelemetryClient client = new TelemetryClient(telemetryPipeline);

            Metric animalsSold = client.GetMetric("AnimalsSold", "Species", MetricConfigurations.Common.Measurement(), MetricAggregationScope.TelemetryClient);

            animalsSold.TryTrackValue(10, "Cow");
            animalsSold.TryTrackValue(20, "Cow");
            client.GetMetricManager(MetricAggregationScope.TelemetryClient).Flush();

            animalsSold.TryTrackValue(100, "Rabbit");
            animalsSold.TryTrackValue(200, "Rabbit");

            client.Context.InstrumentationKey  = "3A3C34B6-CA2D-4372-B772-3B015E1E83DC";
            client.Context.Device.Model        = "Super-Fancy";
            client.Context.Properties["MyTag"] = "MyValue";

            animalsSold.TryTrackValue(30, "Cow");
            animalsSold.TryTrackValue(40, "Cow");
            animalsSold.TryTrackValue(300, "Rabbit");
            animalsSold.TryTrackValue(400, "Rabbit");
            client.GetMetricManager(MetricAggregationScope.TelemetryClient).Flush();

            Assert.AreEqual(3, sentTelemetry.Count);

            MetricTelemetry[] orderedTelemetry = sentTelemetry
                                                 .OrderByDescending((t) => ((MetricTelemetry)t).Count * 10000 + ((MetricTelemetry)t).Sum)
                                                 .Select((t) => (MetricTelemetry)t)
                                                 .ToArray();

            Util.ValidateNumericAggregateValues(orderedTelemetry[0], "AnimalsSold", 4, 1000, 400, 100, 111.803398874989);
            Assert.AreEqual(3, orderedTelemetry[0].Context.Properties.Count);
            Assert.IsTrue(orderedTelemetry[0].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));
            Assert.AreEqual("Rabbit", orderedTelemetry[0].Context.Properties["Species"]);
            Assert.AreEqual("MyValue", orderedTelemetry[0].Context.Properties["MyTag"]);
            Assert.AreEqual("Super-Fancy", orderedTelemetry[0].Context.Device.Model);
            Assert.AreEqual("3A3C34B6-CA2D-4372-B772-3B015E1E83DC", orderedTelemetry[0].Context.InstrumentationKey);

            Util.ValidateNumericAggregateValues(orderedTelemetry[1], "AnimalsSold", 2, 70, 40, 30, 5);
            Assert.AreEqual(3, orderedTelemetry[1].Context.Properties.Count);
            Assert.IsTrue(orderedTelemetry[1].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));
            Assert.AreEqual("Cow", orderedTelemetry[1].Context.Properties["Species"]);
            Assert.AreEqual("MyValue", orderedTelemetry[1].Context.Properties["MyTag"]);
            Assert.AreEqual("Super-Fancy", orderedTelemetry[1].Context.Device.Model);
            Assert.AreEqual("3A3C34B6-CA2D-4372-B772-3B015E1E83DC", orderedTelemetry[1].Context.InstrumentationKey);

            Util.ValidateNumericAggregateValues(orderedTelemetry[2], "AnimalsSold", 2, 30, 20, 10, 5);
            Assert.AreEqual(2, orderedTelemetry[2].Context.Properties.Count);
            Assert.IsTrue(orderedTelemetry[2].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));
            Assert.AreEqual("Cow", orderedTelemetry[2].Context.Properties["Species"]);
            Assert.IsNull(orderedTelemetry[2].Context.Device.Model);
            Assert.AreEqual("754DD89F-61D6-4539-90C7-D886449E12BC", orderedTelemetry[2].Context.InstrumentationKey);

            Util.CompleteDefaultAggregationCycle(client.GetMetricManager(MetricAggregationScope.TelemetryClient));
            telemetryPipeline.Dispose();
        }
コード例 #28
0
        public override async Task <NetStreamResult> Execute(IConsumeContext <TKey, TMessage> consumeContext, CancellationToken token, NetStreamResult result = null)
        {
            var eventName      = $"Consumed from {consumeContext.TopicName}, partition {consumeContext.Partition}";
            var operationName  = $"Consume {consumeContext.TopicName}";
            var telemetryEvent = new EventTelemetry(eventName);

            telemetryEvent.Properties.Add("Topic", consumeContext.TopicName);
            telemetryEvent.Properties.Add("Offset", consumeContext.Offset.ToString());
            telemetryEvent.Properties.Add("Partition", consumeContext.Partition.ToString());

            NetStreamResult response;

            using (_client.StartOperation <RequestTelemetry>(operationName))
            {
                response = await base.Execute(consumeContext, token, result);

                _client.TrackEvent(telemetryEvent);

                _client.GetMetric(
                    $"Lag:{consumeContext.ConsumeGroup}:{consumeContext.TopicName}:{consumeContext.Partition}")
                .TrackValue(consumeContext.Lag);
            }

            return(response);
        }
コード例 #29
0
        public ActionResult Index()
        {
            //This example is trivial as ApplicationInsights already registered the
            // load of the page.
            //You can use this example for tracking different events in the
            // application.
            telemetry.TrackEvent("Loading the Index page");
            //Before you can submit a custom metric, you need to use the GetMetric
            //method.
            telemetry.GetMetric("CountOfIndexPageLoads").TrackValue(indexLoadCounter);


            //This trivial example shows how to track exceptions using Application
            //Insights.
            //You can also send trace message to Application Insights.
            try
            {
                Trace.TraceInformation("Raising a trivial exception");
                throw new System.Exception(@"Trivial Exception for testing Tracking
                Exception feature in Application Insights");
            }
            catch (System.Exception ex)
            {
                Trace.TraceError("Capturing and managing the trivial exception");
                telemetry.TrackException(ex);
            }


            //You need to instruct the TelemetryClient to send all in-memory data to
            // the ApplicationInsights.
            telemetry.Flush();
            return(View());
        }
コード例 #30
0
        public static string Compress <T>(T input)
        {
            var _telemetry = new TelemetryClient();
            var sw         = new Stopwatch();

            sw.Start();

            var jsonString = JsonConvert.SerializeObject(input, new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });

            var    buffer       = Encoding.UTF8.GetBytes(jsonString);
            string base64String = null;

            using (var outputStream = new MemoryStream())
            {
                using (var gZipStream = new GZipStream(outputStream, CompressionMode.Compress))
                    gZipStream.Write(buffer, 0, buffer.Length);

                var outputBytes = outputStream.ToArray();

                base64String = Convert.ToBase64String(outputBytes);
            }

            var elapsed = sw.ElapsedMilliseconds / 1000;

            _telemetry.GetMetric("CompressionHelper.Compress").TrackValue(elapsed);

            return(base64String);
        }