public void PerformanceCollectorModuleDefaultContainsExpectedCountersWebApps()
        {
            PerformanceCounterUtility.isAzureWebApp = null;
            Environment.SetEnvironmentVariable("WEBSITE_SITE_NAME", "something");
            var module = new PerformanceCollectorModule();

            try
            {
                module.Initialize(new TelemetryConfiguration());

                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\Process(??APP_WIN32_PROC??)\% Processor Time"));
                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\Process(??APP_WIN32_PROC??)\% Processor Time Normalized"));
                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\Process(??APP_WIN32_PROC??)\Private Bytes"));

                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\Memory\Available Bytes"));
                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\Process(??APP_WIN32_PROC??)\IO Data Bytes/sec"));

#if NET45
                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests/Sec"));
                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\.NET CLR Exceptions(??APP_CLR_PROC??)\# of Exceps Thrown / sec"));
                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Request Execution Time"));
                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests In Application Queue"));
                Assert.AreEqual(9, module.DefaultCounters.Count);
#else
                Assert.AreEqual(5, module.DefaultCounters.Count);
#endif
            }
            finally
            {
                PerformanceCounterUtility.isAzureWebApp = null;
                module.Dispose();
                Environment.SetEnvironmentVariable("WEBSITE_SITE_NAME", string.Empty);
                Task.Delay(1000).Wait();
            }
        }
        public PerformanceCounters(string instance)
        {
            try
            {
                var perfCollectorModule = new PerformanceCollectorModule();
                foreach (var p in typeof(PerformanceCounters).GetProperties())
                {
                    var counter = new PerformanceCounter(category, p.Name, instance, false);
                    p.SetValue(this, counter);
                    counter.RawValue = 0;

                    if (!p.Name.EndsWith("Base", StringComparison.Ordinal))
                    {
                        var perfCounterSpec = $"\\{category}({instance})\\{p.Name}";
                        var reportAs        = p.Name
                                              .Replace('_', ' ')
                                              .Replace("Per", "/");

                        perfCollectorModule.Counters.Add(new PerformanceCounterCollectionRequest(perfCounterSpec, reportAs));
                    }
                }

                perfCollectorModule.Initialize(TelemetryConfiguration.Active);
            }
            catch (Exception e)
            {
                new TelemetryClient().TrackException(e);
            }
        }
        private static PerformanceCollectorModule CreatePerformanceCollectionModule(IPerformanceCollector collector, List <PerformanceCounterCollectionRequest> customCounterList = null)
        {
            var module = new PerformanceCollectorModule(collector);

            if (customCounterList != null)
            {
                customCounterList.ForEach(module.Counters.Add);
            }

            // set test-friendly timings
            var privateObject = new PrivateObject(module);

            privateObject.SetField("collectionPeriod", TimeSpan.FromMilliseconds(10));

            // build agent is unable to handle performance collection, so don't put any placeholders here for unit testing
            privateObject.SetField(
                "defaultCounters",
                new List <string>()
            {
                @"\DefaultCategory1\DefaultCounter1",
                @"\DefaultCategory2(Instance2)\DefaultCounter2"
            });

            return(module);
        }
Exemple #4
0
        private static PerformanceCollectorModule InitializePerformanceCollectionModule()
        {
            var module = new PerformanceCollectorModule();

            // we're running under IIS Express, so override the default behavior designed to prevent a deadlock
            module.EnableIISExpressPerformanceCounters = true;

            // set test-friendly timings
            module.CollectionPeriod = TimeSpan.FromMilliseconds(10);

            module.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Memory\Available Bytes", @"\Memory\Available Bytes"));
            module.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"Will not parse;\Does\NotExist", @"Will not parse;\Does\NotExist"));

            module.Counters.Add(new PerformanceCounterCollectionRequest(@"Will not parse", "Custom counter - will not parse"));

            module.Counters.Add(new PerformanceCounterCollectionRequest(@"\Does\NotExist", "Custom counter - does not exist"));

            module.Counters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\Handle Count", "Custom counter one"));

            module.Counters.Add(
                new PerformanceCounterCollectionRequest(@"\ASP.NET Applications(??APP_W3SVC_PROC??)\Anonymous Requests/Sec", "Custom counter two"));

            module.Initialize(TelemetryConfiguration.Active);

            return(module);
        }
        public static void AddModules()
        {
            var perfCollectorModule = new PerformanceCollectorModule();

            perfCollectorModule.Counters.Add(new PerformanceCounterCollectionRequest(
                                                 string.Format(@"\.NET CLR Memory({0})\# GC Handles", System.AppDomain.CurrentDomain.FriendlyName), "GC Handles"));
            perfCollectorModule.Initialize(TelemetryConfiguration.Active);
        }
        public ApplicationInsightsWriter(string instrumentationKey, WriterOptions options)
        {
            TelemetryConfiguration.Active.InstrumentationKey = instrumentationKey;

            TelemetryProcessorChainBuilder builder             = TelemetryConfiguration.Active.TelemetryProcessorChainBuilder;
            QuickPulseTelemetryProcessor   quickPulseProcessor = null;

            // add our own telemetry processor that can override session based variables
            //builder.Use(next => new LogMagicTelemetryProcessor(next));

            // optionally enable QuickPulse

            /*
             * - Free and is not counted towards the bill.
             * - The latency is 1 second compared to a few minutes.
             * - Retention is while the data is on the chart, not 90 days.
             * - Data is only streamed while you are in Live Metrics view.
             */
            if (options.EnableQuickPulse)
            {
                builder.Use((next) =>
                {
                    quickPulseProcessor = new QuickPulseTelemetryProcessor(next);
                    return(quickPulseProcessor);
                });
            }

            builder.Build();

            _telemetryClient = new TelemetryClient(TelemetryConfiguration.Active);
            _telemetryClient.InstrumentationKey = instrumentationKey;
            _context = new InsightsContext(_telemetryClient, options);

            if (options.EnableQuickPulse)
            {
                var quickPulse = new QuickPulseTelemetryModule();
                quickPulse.Initialize(TelemetryConfiguration.Active);
                quickPulse.RegisterTelemetryProcessor(quickPulseProcessor);
            }

#if NETFULL
            // see https://github.com/Microsoft/ApplicationInsights-dotnet-server/blob/develop/Src/PerformanceCollector/Perf.Shared/PerformanceCollectorModule.cs
            if (options.CollectPerformanceCounters)
            {
                //optionally enable performance counters collection
                var pcm = new PerformanceCollectorModule();
                //custom counters can be easily added here if required

                pcm.Counters.Add(new PerformanceCounterCollectionRequest(@"\.NET CLR Memory(LogMagic.Console)\# GC Handles", "GC Handles"));

                pcm.Initialize(TelemetryConfiguration.Active);
            }
#endif

            TelemetryConfiguration.Active.TelemetryInitializers.Add(new OperationTelemetryInitialiser());

            _options = options;
        }
        private static void ConfigureApplicationInsights(IServiceCollection services)
        {
            ApplicationInsightsServiceOptions aiOptions = new ApplicationInsightsServiceOptions();

            // Disable dependency tracking
            aiOptions.EnableDependencyTrackingTelemetryModule = false;

            services.AddApplicationInsightsTelemetry(aiOptions);
            services.Configure <LoggerFilterOptions>(o =>
            {
                // This handler is added by 'AddApplicationInsightsTelemetry' above and hard limits
                // and reporting below "warning", which basically kills all logging
                // Remove it, we already configured the filters in Program.cs
                o.Rules.Remove(o.Rules.FirstOrDefault(r =>
                                                      r.ProviderName ==
                                                      "Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider"));

                // These two categories log a lot of noise at "Information", let's raise them to warning
                o.Rules.Add(new LoggerFilterRule(null, "Microsoft.AspNetCore.Mvc.ViewFeatures.Filters.ValidateAntiforgeryTokenAuthorizationFilter", LogLevel.Warning, null));
                o.Rules.Add(new LoggerFilterRule(null, "Microsoft.AspNetCore.Mvc.ViewFeatures.Filters.AutoValidateAntiforgeryTokenAuthorizationFilter", LogLevel.Warning, null));
            });
            RemoveImplementations(services, typeof(PerformanceCollectorModule));
            services.AddSingleton <ITelemetryModule>(
                provider =>
            {
                var collector = new PerformanceCollectorModule();
                collector.DefaultCounters.Add(
                    new PerformanceCounterCollectionRequest(
                        "\\Process(??APP_WIN32_PROC??)\\% Processor Time",
                        "\\Process(??APP_WIN32_PROC??)\\% Processor Time"));
                collector.DefaultCounters.Add(
                    new PerformanceCounterCollectionRequest(
                        "\\Process(??APP_WIN32_PROC??)\\% Processor Time Normalized",
                        "\\Process(??APP_WIN32_PROC??)\\% Processor Time Normalized"));
                collector.DefaultCounters.Add(
                    new PerformanceCounterCollectionRequest(
                        "\\Memory\\Available Bytes",
                        "\\Memory\\Available Bytes"));
                collector.DefaultCounters.Add(
                    new PerformanceCounterCollectionRequest(
                        "\\Process(??APP_WIN32_PROC??)\\Private Bytes",
                        "\\Process(??APP_WIN32_PROC??)\\Private Bytes"));
                collector.DefaultCounters.Add(
                    new PerformanceCounterCollectionRequest(
                        "\\Process(??APP_WIN32_PROC??)\\IO Data Bytes/sec",
                        "\\Process(??APP_WIN32_PROC??)\\IO Data Bytes/sec"));
                collector.DefaultCounters.Add(
                    new PerformanceCounterCollectionRequest(
                        "\\Processor(_Total)\\% Processor Time",
                        "\\Processor(_Total)\\% Processor Time"));
                return(collector);
            });

            services.AddSingleton <ITelemetryInitializer>(ConfigureFabricTelemetryInitializer);
            services.AddSingleton <ITelemetryInitializer>(new RichExceptionTelemetryInitializer());
            services.Configure <ApplicationInsightsServiceOptions>(ConfigureApplicationInsightsOptions);
        }
Exemple #8
0
        private void UsePerformanceCounters()
        {
            var perfCollectorModule = new PerformanceCollectorModule();

            foreach (var counter in PerformanceCounters)
            {
                perfCollectorModule.Counters.Add(new PerformanceCounterCollectionRequest(counter, counter.Split('\\')[1]));
            }
            perfCollectorModule.Initialize(TelemetryConfiguration.Active);
        }
        public void TelemetryModuleIsNotInitializedTwiceToPreventTimerBeingRecreated()
        {
            var           module        = new PerformanceCollectorModule();
            PrivateObject privateObject = new PrivateObject(module);

            module.Initialize(TelemetryConfiguration.CreateDefault());
            object config1 = privateObject.GetField("telemetryConfiguration");

            module.Initialize(TelemetryConfiguration.CreateDefault());
            object config2 = privateObject.GetField("telemetryConfiguration");

            Assert.AreSame(config1, config2);
        }
        internal TelemetryConfiguration InitializeConfiguration()
        {
            TelemetryConfiguration config = new TelemetryConfiguration()
            {
                InstrumentationKey = _instrumentationKey
            };

            AddInitializers(config);

            // Plug in Live stream and adaptive sampling
            QuickPulseTelemetryProcessor   processor = null;
            TelemetryProcessorChainBuilder builder   = config.TelemetryProcessorChainBuilder
                                                       .Use((next) =>
            {
                processor = new QuickPulseTelemetryProcessor(next);
                return(processor);
            });

            if (_samplingSettings != null)
            {
                builder.Use((next) =>
                {
                    return(new AdaptiveSamplingTelemetryProcessor(_samplingSettings, null, next));
                });
            }

            builder.Build();

            _quickPulseModule = new QuickPulseTelemetryModule();
            _quickPulseModule.Initialize(config);
            _quickPulseModule.RegisterTelemetryProcessor(processor);

            // Plug in perf counters
            _perfModule = new PerformanceCollectorModule();
            _perfModule.Initialize(config);

            // Configure the TelemetryChannel
            ITelemetryChannel channel = CreateTelemetryChannel();

            // call Initialize if available
            ITelemetryModule module = channel as ITelemetryModule;

            if (module != null)
            {
                module.Initialize(config);
            }

            config.TelemetryChannel = channel;

            return(config);
        }
        protected void Application_Start()
        {
            var setting = ConfigurationManager.AppSettings["TestApp.SendTelemetyIntemOnAppStart"];

            if (false == string.IsNullOrWhiteSpace(setting) && true == bool.Parse(setting))
            {
                new TelemetryClient().TrackTrace("Application_Start");
            }

            GlobalConfiguration.Configure(WebApiConfig.Register);

            var module = new PerformanceCollectorModule();

            // we're running under IIS Express, so override the default behavior designed to prevent a deadlock
            module.EnableIISExpressPerformanceCounters = true;

            // set test-friendly timings
            var privateObject = new PrivateObject(module);

            privateObject.SetField("collectionPeriod", TimeSpan.FromMilliseconds(10));
            privateObject.SetField(
                "defaultCounters",
                new List <string>()
            {
                @"\Memory\Available Bytes", @"Will not parse;\Does\NotExist"
            });

            module.Counters.Add(
                new PerformanceCounterCollectionRequest(@"Will not parse", "Custom counter - will not parse"));

            module.Counters.Add(
                new PerformanceCounterCollectionRequest(@"\Does\NotExist", "Custom counter - does not exist"));

            module.Counters.Add(
                new PerformanceCounterCollectionRequest(
                    @"\Process(??APP_WIN32_PROC??)\Handle Count",
                    "Custom counter one"));

            module.Counters.Add(
                new PerformanceCounterCollectionRequest(
                    @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Anonymous Requests/Sec",
                    "Custom counter two"));

            // necessary for .NET CLR Memory counters to start reporting process ID
            GC.Collect();

            module.Initialize(TelemetryConfiguration.Active);

            TelemetryModules.Instance.Modules.Add(module);
        }
Exemple #12
0
        public ActionResult Index()
        {
            var perfCollectorModule = new PerformanceCollectorModule();

            perfCollectorModule.Counters.Add(new PerformanceCounterCollectionRequest(
                                                 @"\Process([replace-with-application-process-name])\Page Faults/sec", "PageFaultsPerfSec"));
            perfCollectorModule.Initialize(TelemetryConfiguration.Active);

            log4net.Config.XmlConfigurator.Configure();
            var logger = LogManager.GetLogger(typeof(ActionResult));

            logger.Info("Index info");
            return(View());
        }
Exemple #13
0
        public static void SendProcessInfo()
        {
            if (telemetryClient == null)
            {
                return;
            }

            var perfCollectorModule = new PerformanceCollectorModule();

            perfCollectorModule.Counters.Add(new PerformanceCounterCollectionRequest(
                                                 @"\Process(ProjectBook.exe)\Page Faults/sec", "PageFaultsPerfSec"));

            perfCollectorModule.Initialize(telemetryConfiguration);
        }
Exemple #14
0
        public static void ConfigureTelemetryModules(this TelemetryConfiguration configuration)
        {
            var performanceCounters = new PerformanceCollectorModule();

            performanceCounters.Counters.Add(new PerformanceCounterCollectionRequest(@"\Process\ID", "ID"));
            performanceCounters.Initialize(configuration);

            telemetryModules.Add(performanceCounters);

            var dependencies = new DependencyTrackingTelemetryModule();

            dependencies.Initialize(configuration);

            telemetryModules.Add(dependencies);
        }
        private static void ConfigureApplicationInsights(IServiceCollection services)
        {
            services.AddApplicationInsightsTelemetry();
            services.Configure <LoggerFilterOptions>(o =>
            {
                // This handler is added by 'AddApplicationInsightsTelemetry' above and hard limits
                // and reporting below "warning", which basically kills all logging
                // Remove it, we already configured the filters in Program.cs
                o.Rules.Remove(o.Rules.FirstOrDefault(r =>
                                                      r.ProviderName ==
                                                      "Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider"));
            });
            RemoveImplementations(services, typeof(PerformanceCollectorModule));
            services.AddSingleton <ITelemetryModule>(
                provider =>
            {
                var collector = new PerformanceCollectorModule();
                collector.DefaultCounters.Add(
                    new PerformanceCounterCollectionRequest(
                        "\\Process(??APP_WIN32_PROC??)\\% Processor Time",
                        "\\Process(??APP_WIN32_PROC??)\\% Processor Time"));
                collector.DefaultCounters.Add(
                    new PerformanceCounterCollectionRequest(
                        "\\Process(??APP_WIN32_PROC??)\\% Processor Time Normalized",
                        "\\Process(??APP_WIN32_PROC??)\\% Processor Time Normalized"));
                collector.DefaultCounters.Add(
                    new PerformanceCounterCollectionRequest(
                        "\\Memory\\Available Bytes",
                        "\\Memory\\Available Bytes"));
                collector.DefaultCounters.Add(
                    new PerformanceCounterCollectionRequest(
                        "\\Process(??APP_WIN32_PROC??)\\Private Bytes",
                        "\\Process(??APP_WIN32_PROC??)\\Private Bytes"));
                collector.DefaultCounters.Add(
                    new PerformanceCounterCollectionRequest(
                        "\\Process(??APP_WIN32_PROC??)\\IO Data Bytes/sec",
                        "\\Process(??APP_WIN32_PROC??)\\IO Data Bytes/sec"));
                collector.DefaultCounters.Add(
                    new PerformanceCounterCollectionRequest(
                        "\\Processor(_Total)\\% Processor Time",
                        "\\Processor(_Total)\\% Processor Time"));
                return(collector);
            });

            services.AddSingleton <ITelemetryInitializer>(ConfigureFabricTelemetryInitializer);
            services.AddSingleton <ITelemetryInitializer>(new RichExceptionTelemetryInitializer());
            services.Configure <ApplicationInsightsServiceOptions>(ConfigureApplicationInsightsOptions);
        }
        private static PerformanceCollectorModule CreatePerformanceCollectionModule(IPerformanceCollector collector, List <PerformanceCounterCollectionRequest> customCounterList = null)
        {
            var module = new PerformanceCollectorModule(collector);

            if (customCounterList != null)
            {
                customCounterList.ForEach(module.Counters.Add);
            }

            module.CollectionPeriod = TimeSpan.FromMilliseconds(10);

            module.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\DefaultCategory1\DefaultCounter1", @"\DefaultCategory1\DefaultCounter1"));
            module.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\DefaultCategory2(Instance2)\DefaultCounter2", @"\DefaultCategory2(Instance2)\DefaultCounter2"));

            return(module);
        }
Exemple #17
0
        public void ValidatePerformanceCountersAreCollected(string assemblyName)
        {
            using (var server = new InProcessServer(assemblyName, this.output))
            {
                // Reconfigure the PerformanceCollectorModule timer.
                Type perfModuleType = typeof(PerformanceCollectorModule);
                PerformanceCollectorModule perfModule = (PerformanceCollectorModule)server.ApplicationServices.GetServices <ITelemetryModule>().FirstOrDefault(m => m.GetType() == perfModuleType);
                FieldInfo timerField = perfModuleType.GetField("timer", BindingFlags.NonPublic | BindingFlags.Instance);
                var       timer      = timerField.GetValue(perfModule);
                timerField.FieldType.InvokeMember("ScheduleNextTick", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, timer, new object[] { TimeSpan.FromMilliseconds(10) });

                var actual = server.Listener.ReceiveItems(TestListenerTimeoutInMs);
                this.DebugTelemetryItems(actual);
                Assert.True(actual.Length > 0);
            }
        }
Exemple #18
0
        /// <summary>
        /// Initializes a new <see cref="PerformanceCounters"/> instance.
        /// </summary>
        public PerformanceCounters(string instance)
        {
            try
            {
                var perfCollectorModule = new PerformanceCollectorModule();
                var props = typeof(PerformanceCounters)
                            .GetProperties()
                            .Where(p => p.PropertyType == typeof(PerformanceCounter));

                var all = new List <PerformanceCounter>();
                foreach (var p in props)
                {
                    var counter = new PerformanceCounter(category, p.Name, instance, false);
                    p.SetValue(this, counter);
                    counter.RawValue = 0;
                    all.Add(counter);

                    if (!p.Name.EndsWith("Base", StringComparison.Ordinal))
                    {
                        var perfCounterSpec = $"\\{category}({instance})\\{p.Name}";
                        var reportAs        = p.Name
                                              .Replace('_', ' ')
                                              .Replace("Per", "/");

                        // http://i1.blogs.msdn.com/b/visualstudioalm/archive/2015/04/01/application-insights-choose-your-own-performance-counters.aspx
                        // Currently, metric names may only contain letters, round brackets, forward slashes, hyphens, underscores, spaces and dots.
                        var reportAsStringBuilder = new StringBuilder(reportAs);
                        foreach (Match match in Regex.Matches(reportAs, "[0-9]"))
                        {
                            reportAsStringBuilder[match.Index] = (char)('A' + (match.Groups[0].Value[0] - '0'));
                        }

                        perfCollectorModule.Counters.Add(new PerformanceCounterCollectionRequest(perfCounterSpec, reportAsStringBuilder.ToString()));
                    }
                }

                perfCollectorModule.Initialize(TelemetryConfiguration.Active);

                this.All = all.ToArray();
            }
            catch (Exception e)
            {
                new TelemetryClient().TrackException(e);
            }
        }
 protected static TelemetryClient GetTelemiteryClient()
 {
     if (_TelemetryClient is null)
     {
         var telemetryConfiguration = TelemetryConfiguration.CreateDefault();
         telemetryConfiguration.InstrumentationKey = "4b9bb17b-c7ee-43e5-b220-ec6db2c33373";
         var tc = new TelemetryClient(telemetryConfiguration);
         tc.Context.User.Id                = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
         tc.Context.Session.Id             = Guid.NewGuid().ToString();
         tc.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
         tc.Context.Component.Version      = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
         var perfCollectorModule = new PerformanceCollectorModule();
         perfCollectorModule.Counters.Add(new PerformanceCounterCollectionRequest(
                                              string.Format(@"\.NET CLR Memory({0})\# GC Handles", System.AppDomain.CurrentDomain.FriendlyName), "GC Handles"));
         perfCollectorModule.Initialize(telemetryConfiguration);
         _TelemetryClient = tc;
     }
     return(_TelemetryClient);
 }
Exemple #20
0
        protected void Application_Start(object sender, EventArgs e)
        {
            // necessary for .NET CLR Memory counters to start reporting process ID
            GC.Collect();

            var setting = ConfigurationManager.AppSettings["TestApp.SendTelemetyIntemOnAppStart"];

            if (false == string.IsNullOrWhiteSpace(setting) && true == bool.Parse(setting))
            {
                new TelemetryClient().TrackTrace("Application_Start");
            }

            PerformanceCollectorModule perfModule = InitializePerformanceCollectionModule();

            QuickPulseTelemetryModule quickPulseModule = InitializeQuickPulseModule();

            TelemetryModules.Instance.Modules.Add(perfModule);
            TelemetryModules.Instance.Modules.Add(quickPulseModule);
        }
        public void PerformanceCollectorModuleDefaultContainsExpectedCountersWindows()
        {
            PerformanceCounterUtility.isAzureWebApp = null;
            var module = new PerformanceCollectorModule();

#if NETCOREAPP2_0
            var original = PerformanceCounterUtility.IsWindows;
            PerformanceCounterUtility.IsWindows = true;
#endif
            try
            {
                module.Initialize(new TelemetryConfiguration());
#if !NETCOREAPP1_0
                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\Process(??APP_WIN32_PROC??)\% Processor Time"));
                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\Process(??APP_WIN32_PROC??)\% Processor Time Normalized"));
                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\Process(??APP_WIN32_PROC??)\Private Bytes"));

                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\Memory\Available Bytes"));
                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\Process(??APP_WIN32_PROC??)\IO Data Bytes/sec"));

#if NET45
                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests/Sec"));
                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\.NET CLR Exceptions(??APP_CLR_PROC??)\# of Exceps Thrown / sec"));
                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Request Execution Time"));
                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests In Application Queue"));
#endif

                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\Processor(_Total)\% Processor Time"));
#if NET45
                Assert.AreEqual(10, module.DefaultCounters.Count);
#else
                Assert.AreEqual(6, module.DefaultCounters.Count);
#endif
#endif
            }
            finally
            {
                module.Dispose();
#if NETCOREAPP2_0
                PerformanceCounterUtility.IsWindows = original;
#endif
            }
        }
Exemple #22
0
        private static void ConfigureApplicationInsights(IServiceCollection services)
        {
            services.AddApplicationInsightsTelemetry();
#if NET461
            RemoveImplementations(services, typeof(PerformanceCollectorModule));
            services.AddSingleton <ITelemetryModule>(
                provider =>
            {
                var collector = new PerformanceCollectorModule();
                collector.DefaultCounters.Add(
                    new PerformanceCounterCollectionRequest(
                        "\\Process(??APP_WIN32_PROC??)\\% Processor Time",
                        "\\Process(??APP_WIN32_PROC??)\\% Processor Time"));
                collector.DefaultCounters.Add(
                    new PerformanceCounterCollectionRequest(
                        "\\Process(??APP_WIN32_PROC??)\\% Processor Time Normalized",
                        "\\Process(??APP_WIN32_PROC??)\\% Processor Time Normalized"));
                collector.DefaultCounters.Add(
                    new PerformanceCounterCollectionRequest(
                        "\\Memory\\Available Bytes",
                        "\\Memory\\Available Bytes"));
                collector.DefaultCounters.Add(
                    new PerformanceCounterCollectionRequest(
                        "\\Process(??APP_WIN32_PROC??)\\Private Bytes",
                        "\\Process(??APP_WIN32_PROC??)\\Private Bytes"));
                collector.DefaultCounters.Add(
                    new PerformanceCounterCollectionRequest(
                        "\\Process(??APP_WIN32_PROC??)\\IO Data Bytes/sec",
                        "\\Process(??APP_WIN32_PROC??)\\IO Data Bytes/sec"));
                collector.DefaultCounters.Add(
                    new PerformanceCounterCollectionRequest(
                        "\\Processor(_Total)\\% Processor Time",
                        "\\Processor(_Total)\\% Processor Time"));
                return(collector);
            });
#endif


            services.AddSingleton <ITelemetryInitializer>(ConfigureFabricTelemetryInitializer);
            services.AddSingleton <ITelemetryInitializer>(new RichExceptionTelemetryInitializer());
            services.Configure <ApplicationInsightsServiceOptions>(ConfigureApplicationInsightsOptions);
        }
Exemple #23
0
        public void ValidatePerformanceCountersAreCollected(string assemblyName, Func <IWebHostBuilder, IWebHostBuilder> configureHost = null)
        {
            using (var server = new InProcessServer(assemblyName, configureHost))
            {
                // Reconfigure the PerformanceCollectorModule timer.
                Type perfModuleType = typeof(PerformanceCollectorModule);
                PerformanceCollectorModule perfModule = (PerformanceCollectorModule)server.ApplicationServices.GetServices <ITelemetryModule>().FirstOrDefault(m => m.GetType() == perfModuleType);
                FieldInfo timerField = perfModuleType.GetField("timer", BindingFlags.NonPublic | BindingFlags.Instance);
                var       timer      = timerField.GetValue(perfModule);
                timerField.FieldType.InvokeMember("ScheduleNextTick", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, timer, new object[] { TimeSpan.FromMilliseconds(10) });

                DateTime timeout = DateTime.UtcNow.AddMilliseconds(TestTimeoutMs);
                int      numberOfCountersSent = 0;
                do
                {
                    Thread.Sleep(1000);
                    numberOfCountersSent += server.BackChannel.Buffer.OfType <MetricTelemetry>().Distinct().Count();
                } while (numberOfCountersSent == 0 && DateTime.UtcNow < timeout);

                Assert.True(numberOfCountersSent > 0);
            }
        }
        private void Setup()
        {
            try
            {
                TelemetryConfiguration telemetryconfiguration = new TelemetryConfiguration();
                telemetryconfiguration.InstrumentationKey = InstrumentationKey;

                PerformanceCollectorModule perfCollectorModule = new PerformanceCollectorModule();
                perfCollectorModule.Counters.Add(new PerformanceCounterCollectionRequest(@"\Memory\Committed Bytes", "used memory"));
                perfCollectorModule.Counters.Add(new PerformanceCounterCollectionRequest(@"\Cpu\% Processor Time", "used cpu"));
                perfCollectorModule.Initialize(telemetryconfiguration);
                telemetry = new TelemetryClient(telemetryconfiguration);

                //telemetry = new TelemetryClient();

                telemetry.Context.InstrumentationKey = InstrumentationKey;
                telemetry.TrackEvent("This node started");
            }
            catch (Exception e)
            {
                string sSource;
                string sLog;
                string sEvent;

                sSource = "Timothy";
                sLog    = "Application";
                sEvent  = Bubble(e);

                if (!EventLog.SourceExists(sSource))
                {
                    EventLog.CreateEventSource(sSource, sLog);
                }

                EventLog.WriteEntry(sSource, sEvent);
                EventLog.WriteEntry(sSource, sEvent,
                                    EventLogEntryType.Error, 234);
            }
        }
Exemple #25
0
        public PerformanceCounters(string instance)
        {
            try
            {
                var perfCollectorModule = new PerformanceCollectorModule();
                var props = typeof(PerformanceCounters)
                            .GetProperties()
                            .Where(p => p.PropertyType == typeof(PerformanceCounter));

                var all = new List <PerformanceCounter>();
                foreach (var p in props)
                {
                    var counter = new PerformanceCounter(category, p.Name, instance, false);
                    p.SetValue(this, counter);
                    counter.RawValue = 0;
                    all.Add(counter);

                    if (!p.Name.EndsWith("Base", StringComparison.Ordinal))
                    {
                        var perfCounterSpec = string.Format(CultureInfo.InvariantCulture, "\\{0}({1})\\{2}", category, instance, p.Name);
                        var reportAs        = p.Name
                                              .Replace('_', ' ')
                                              .Replace("Per", "/");

                        perfCollectorModule.Counters.Add(new PerformanceCounterCollectionRequest(perfCounterSpec, reportAs));
                    }
                }

                perfCollectorModule.Initialize(TelemetryConfiguration.Active);
            }
            catch (Exception e)
            {
                this.initialized = false;
                new TelemetryClient().TrackException(e);
            }

            this.initialized = true;
        }
        public AppInsightsTelemetry(Guid session)
        {
            TelemetryConfiguration.Active.InstrumentationKey = "a11b9e48-55fe-4efa-aec7-44e7a8905577";
            var performanceModule = new PerformanceCollectorModule();

            performanceModule.Initialize(TelemetryConfiguration.Active);


            var quickPulseModule = new QuickPulseTelemetryModule();

            quickPulseModule.Initialize(TelemetryConfiguration.Active);


            var webModule = new RequestTrackingTelemetryModule();

            webModule.Initialize(TelemetryConfiguration.Active);

            var exceptionModule = new UnhandledExceptionTelemetryModule();

            exceptionModule.Initialize(TelemetryConfiguration.Active);

            _client = new TelemetryClient(TelemetryConfiguration.Active);
        }
        public void PerformanceCollectorModuleDefaultContainsExpectedCountersNonWindows()
        {
#if NETCOREAPP2_0
            PerformanceCounterUtility.isAzureWebApp = null;
            var original = PerformanceCounterUtility.IsWindows;
            PerformanceCounterUtility.IsWindows = false;
            var module = new PerformanceCollectorModule();

            try
            {
                module.Initialize(new TelemetryConfiguration());

                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\Process(??APP_WIN32_PROC??)\% Processor Time"));
                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\Process(??APP_WIN32_PROC??)\% Processor Time Normalized"));
                Assert.IsTrue(ContainsPerfCounter(module.DefaultCounters, @"\Process(??APP_WIN32_PROC??)\Private Bytes"));
                Assert.AreEqual(3, module.DefaultCounters.Count);
            }
            finally
            {
                PerformanceCounterUtility.IsWindows = original;
                module.Dispose();
            }
#endif
        }