public IHttpActionResult Metric([FromBody] SampledMetricMetadata metricMetadata)
        {
            if (metricMetadata == null)
            {
                return(BadRequest("No metadata about the metric was specified"));
            }
            if (string.IsNullOrWhiteSpace(metricMetadata.Name))
            {
                return(BadRequest("No metric name was specified"));
            }
            if (metricMetadata.Sum == null)
            {
                return(BadRequest("No sum was specified"));
            }

            try
            {
                var applicationInsightsTelemetry = new ApplicationInsightsTelemetry(metricMetadata.InstrumentationKey);
                applicationInsightsTelemetry.TrackSampledMetric(metricMetadata.Name, metricMetadata.Sum.Value, metricMetadata.Count, metricMetadata.Max, metricMetadata.Min, metricMetadata.StandardDeviation, metricMetadata.CustomProperties);

                return(StatusCode(HttpStatusCode.NoContent));
            }
            catch (InstrumentationKeyNotSpecifiedException)
            {
                return(Content(HttpStatusCode.InternalServerError, Constants.Errors.MissingInstrumentationKey));
            }
        }
        public override Task Execute()
        {
            _process.Refresh();

            // A very simple and not that accruate evaluation of how much CPU the process is take out of a core.
            double cpuPercentage = (_process.TotalProcessorTime - _startCpuTime).TotalMilliseconds / _cpuWatch.ElapsedMilliseconds;

            ApplicationInsightsTelemetry.TrackMetric(CpuMetric, cpuPercentage);

            if (_cpuThreshold.HasValue && _cpuThreshold.Value <= cpuPercentage)
            {
                _log.WriteMonitor(nameof(ResourcesMonitor), "", $"CPU usage is {cpuPercentage:0.##}");
            }

            double memoryInMBytes = _process.WorkingSet64 / Mb;

            ApplicationInsightsTelemetry.TrackMetric(RamMetric, memoryInMBytes);

            if (_ramMbThreshold.HasValue && _ramMbThreshold.Value <= memoryInMBytes)
            {
                _log.WriteMonitor(nameof(ResourcesMonitor), "", $"RAM usage is {memoryInMBytes:0.##}");
            }

            return(Task.CompletedTask);
        }
Esempio n. 3
0
        public void DefaultAppInsightsTest()
        {
            var config = new TelemetryConfiguration {
                InstrumentationKey = "test"
            };
            var telemetry = new ApplicationInsightsTelemetry(config);

            var snippet = telemetry.GetCodeSnippet();

            Assert.Contains(config.InstrumentationKey, snippet);
        }
Esempio n. 4
0
        /// <summary>
        /// Process the array of enabled feature names retrieved from configuration.
        /// Ignore invalid feature names and unavailable engine feature names, and
        /// return an ReadOnlyBag of the valid enabled feature names.
        /// </summary>
        private static ReadOnlyBag <string> ProcessEnabledFeatures(string[] enabledFeatures)
        {
            if (enabledFeatures.Length == 0)
            {
                return(ReadOnlyBag <string> .Empty);
            }

            var list = new List <string>(enabledFeatures.Length);

            foreach (string name in enabledFeatures)
            {
                if (IsModuleFeatureName(name))
                {
                    list.Add(name);
                    ApplicationInsightsTelemetry.SendTelemetryMetric(TelemetryType.ExperimentalModuleFeatureActivation, name);
                }
                else if (IsEngineFeatureName(name))
                {
                    if (EngineExperimentalFeatureMap.TryGetValue(name, out ExperimentalFeature feature))
                    {
                        feature.Enabled = true;
                        list.Add(name);
                        ApplicationInsightsTelemetry.SendTelemetryMetric(TelemetryType.ExperimentalEngineFeatureActivation, name);
                    }
                    else
                    {
                        string message = StringUtil.Format(Logging.EngineExperimentalFeatureNotFound, name);
                        LogError(PSEventId.ExperimentalFeature_InvalidName, name, message);
                    }
                }
                else
                {
                    string message = StringUtil.Format(Logging.InvalidExperimentalFeatureName, name);
                    LogError(PSEventId.ExperimentalFeature_InvalidName, name, message);
                }
            }

            return(new ReadOnlyBag <string>(new HashSet <string>(list, StringComparer.OrdinalIgnoreCase)));
        }
        public IHttpActionResult Event([FromBody] Contracts.v1.EventMetadata eventMetadata)
        {
            if (eventMetadata == null)
            {
                return(BadRequest("No metadata about the event was specified"));
            }
            if (string.IsNullOrWhiteSpace(eventMetadata.Name))
            {
                return(BadRequest("No event name was specified"));
            }

            try
            {
                var applicationInsightsTelemetry = new ApplicationInsightsTelemetry(eventMetadata.InstrumentationKey);
                applicationInsightsTelemetry.TrackEvent(eventMetadata.Name, eventMetadata.CustomProperties);

                return(StatusCode(HttpStatusCode.NoContent));
            }
            catch (InstrumentationKeyNotSpecifiedException)
            {
                return(Content(HttpStatusCode.InternalServerError, Constants.Errors.MissingInstrumentationKey));
            }
        }
Esempio n. 6
0
        public IHttpActionResult Trace([FromBody] TraceMetadata traceMetadata)
        {
            if (traceMetadata == null)
            {
                return(BadRequest("No trace metadata was specified"));
            }
            if (string.IsNullOrWhiteSpace(traceMetadata.Message))
            {
                return(BadRequest("No message was specified"));
            }

            try
            {
                var applicationInsightsTelemetry = new ApplicationInsightsTelemetry(traceMetadata.InstrumentationKey);
                applicationInsightsTelemetry.TrackTrace(traceMetadata.Message, traceMetadata.SeverityLevel, traceMetadata.CustomProperties);

                return(StatusCode(HttpStatusCode.NoContent));
            }
            catch (InstrumentationKeyNotSpecifiedException)
            {
                return(Content(HttpStatusCode.InternalServerError, Constants.Errors.MissingInstrumentationKey));
            }
        }
Esempio n. 7
0
        public override Task RunAsync(CancellationToken cancellationToken)
        {
            return(Task.Factory.StartNew(async() =>
            {
                Exception globalEx = null;
                try
                {
                    while (!cancellationToken.IsCancellationRequested)
                    {
                        IQueueMessage message = null;
                        bool executionSucceeded = false;
                        try
                        {
                            do
                            {
                                message = await _queueReader.GetMessageAsync();
                                if (message == null)
                                {
                                    break;
                                }

                                var context = new QueueTriggeringContext(message.InsertionTime);

                                var p = new List <object>()
                                {
                                    message.Value(_parameterType)
                                };

                                if (_hasSecondParameter)
                                {
                                    p.Add(_useTriggeringContext ? context : (object)message.InsertionTime);
                                }

                                var telemtryOperation = ApplicationInsightsTelemetry.StartRequestOperation($"{nameof(QueueTriggerBinding)} from {_queueName}");
                                try
                                {
                                    await Invoke(_serviceProvider, _method, p.ToArray());
                                }
                                catch (Exception ex)
                                {
                                    ApplicationInsightsTelemetry.MarkFailedOperation(telemtryOperation);
                                    ApplicationInsightsTelemetry.TrackException(ex);
                                    throw;
                                }
                                finally
                                {
                                    ApplicationInsightsTelemetry.StopOperation(telemtryOperation);
                                }
                                await ProcessCompletedMessage(message, context);
                                executionSucceeded = true;
                            } while (!cancellationToken.IsCancellationRequested);
                        }
                        catch (Exception ex)
                        {
                            await LogError("QueueTriggerBinding", "RunAsync", ex);
                            await ProcessFailedMessage(message);
                            executionSucceeded = false;
                        }
                        finally
                        {
                            await Task.Delay(_delayStrategy.GetNextDelay(executionSucceeded), cancellationToken);
                        }
                    }
                }
                catch (Exception ex)
                {
                    globalEx = ex;
                }
                finally
                {
                    var msg =
                        $"Process ended. Exception={globalEx?.Message + globalEx?.StackTrace}. Token.IsCancellationRequested={cancellationToken.IsCancellationRequested}";
                    await _log.WriteInfoAsync("QueueTriggerBinding", "RunAsync", _queueName, msg);
                }
            }, cancellationToken, TaskCreationOptions.LongRunning | TaskCreationOptions.DenyChildAttach, TaskScheduler.Default).Unwrap());
        }
        public ApplicationInsightsExceptionLogger()
        {
            string instrumentationKey = ConfigurationProvider.GetSetting(Constants.Configuration.Telemetry.RuntimeInstrumentationKeySettingName);

            applicationInsightsTelemetry = new ApplicationInsightsTelemetry(instrumentationKey);
        }