private static CounterCreationDataCollection GetCounterCreationDataCollectionForApmContextUsage(MethodInfo[] apmContextUsages)
        {
            var counterCreationDataCollection = new CounterCreationDataCollection();

            Trace.TraceInformation("Number of get context uses actions: {0}", apmContextUsages.Length);

            foreach (var apmContextUsage in apmContextUsages)
            {
                var methodIdentifier = ApmContext.GetMethodIdentifier(apmContextUsage);
                var eventName        = ApmContext.GetEventName(apmContextUsage);

                Trace.TraceInformation("Setting up get context uses '{0}' for event '{1}'", methodIdentifier, eventName);

                //Setup action performance counters
                foreach (var counterHandler in PerformanceCounterApmHttpClientDelegatingHandler.CounterHandlers)
                {
                    if (counterCreationDataCollection.Cast <CounterCreationData>().Any(x => x.CounterName == methodIdentifier))
                    {
                        Trace.TraceInformation("Counter for method '{0}' was duplicate", methodIdentifier);
                    }
                    else
                    {
                        var countersToCreate = counterHandler.GetCreationData(methodIdentifier);
                        foreach (var counterToCreate in countersToCreate)
                        {
                            Trace.TraceInformation("Added counter for method '{0}'", counterToCreate.CounterName);
                        }

                        counterCreationDataCollection.AddRange(countersToCreate);
                    }
                }
            }

            return(counterCreationDataCollection);
        }
    public static void Main()
    {
        try
        {
            // <Snippet1>
            // <Snippet2>
            string myCategoryName;
            int    numberOfCounters;
            Console.Write("Enter the category Name :");
            myCategoryName = Console.ReadLine();
            // Check if the category already exists or not.
            if (!PerformanceCounterCategory.Exists(myCategoryName))
            {
                Console.Write("Enter the number of counters : ");
                numberOfCounters = int.Parse(Console.ReadLine());
                CounterCreationData[] myCounterCreationData =
                    new CounterCreationData[numberOfCounters];
                for (int i = 0; i < numberOfCounters; i++)
                {
                    Console.Write("Enter the counter name for {0} counter : ", i);
                    myCounterCreationData[i]             = new CounterCreationData();
                    myCounterCreationData[i].CounterName = Console.ReadLine();
                }
                CounterCreationDataCollection myCounterCollection =
                    new CounterCreationDataCollection();
                // Add the 'CounterCreationData[]' to 'CounterCollection'.
                myCounterCollection.AddRange(myCounterCreationData);

                PerformanceCounterCategory.Create(myCategoryName,
                                                  "Sample Category",
                                                  PerformanceCounterCategoryType.SingleInstance, myCounterCollection);

                if (myCounterCreationData.Length > 0)
                {
                    if (myCounterCollection.Contains(myCounterCreationData[0]))
                    {
                        myCounterCollection.Remove(myCounterCreationData[0]);
                        Console.WriteLine("'{0}' counter is removed from the " +
                                          "CounterCreationDataCollection", myCounterCreationData[0].CounterName);
                    }
                }
                else
                {
                    Console.WriteLine("The counters does not exist");
                }
            }
            else
            {
                Console.WriteLine("The category already exists");
            }
            // </Snippet2>
            // </Snippet1>
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: {0}.", e.Message);
            return;
        }
    }
Exemplo n.º 3
0
        public void ProfileActivated()
        {
            Logger.Debug("Starting installation of  monitoring");

            if (PerformanceCounterCategory.Exists(CategoryName))
            {
                Logger.Warn(String.Format("Category {0} already exists, going to delete it first", CategoryName));
                PerformanceCounterCategory.Delete(CategoryName);
            }

            CounterCreationDataCollection counterData = new CounterCreationDataCollection();

            counterData.AddRange(this.InstallAverageMessageProcessTimeCounter());
            counterData.AddRange(this.InstalledFailedMessageProcessingCounter());

            PerformanceCounterCategory.Create(CategoryName, "NServiceBus Monitoring", PerformanceCounterCategoryType.MultiInstance, counterData);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Installs performance counters in the assembly
        /// </summary>
        /// <param name="installerAssembly"></param>
        /// <param name="discoverer">object that can discover aspects inside and assembly</param>
        /// <param name="categoryName">category name for the metrics. If not provided, it will use the assembly name</param>
        public static void Install(Assembly installerAssembly, IInstrumentationDiscoverer discoverer, string categoryName = null)
        {
            Uninstall(installerAssembly, discoverer, categoryName);

            if (string.IsNullOrEmpty(categoryName))
            {
                categoryName = installerAssembly.GetName().Name;
            }

            var instrumentationInfos = discoverer.Discover(installerAssembly).ToArray();

            if (instrumentationInfos.Length == 0)
            {
                throw new InvalidOperationException("There are no instrumentationInfos found by the discoverer!");
            }

            var counterCreationDataCollection = new CounterCreationDataCollection();

            Trace.TraceInformation("Number of filters: {0}", instrumentationInfos.Length);

            foreach (var group in instrumentationInfos.GroupBy(x => x.CategoryName))
            {
                foreach (var instrumentationInfo in group)
                {
                    Trace.TraceInformation("Setting up filters '{0}'", instrumentationInfo.Description);

                    foreach (var counterType in instrumentationInfo.Counters)
                    {
                        if (!HandlerFactories.ContainsKey(counterType))
                        {
                            throw new ArgumentException("Counter type not defined: " + counterType);
                        }

                        // if already exists in the set then ignore
                        if (counterCreationDataCollection.Cast <CounterCreationData>().Any(x => x.CounterName == counterType))
                        {
                            Trace.TraceInformation("Counter type '{0}' was duplicate", counterType);
                            continue;
                        }

                        using (var counterHandler = HandlerFactories[counterType](categoryName, instrumentationInfo.InstanceName))
                        {
                            counterCreationDataCollection.AddRange(counterHandler.BuildCreationData().ToArray());
                            Trace.TraceInformation("Added counter type '{0}'", counterType);
                        }
                    }
                }

                var catName = string.IsNullOrEmpty(group.Key) ? categoryName : group.Key;

                PerformanceCounterCategory.Create(catName, "PerfIt category for " + catName,
                                                  PerformanceCounterCategoryType.MultiInstance, counterCreationDataCollection);
            }

            Trace.TraceInformation("Built category '{0}' with {1} items", categoryName, counterCreationDataCollection.Count);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Registers the performance counters with the operating system.
        /// </summary>
        private void CreatePerformanceCounters()
        {
            CounterCreationDataCollection ccdc = new CounterCreationDataCollection();

            ccdc.AddRange(TaskManagerInstaller.COUNTERS);

            if (!PerformanceCounterCategory.Exists(TaskManagerInstaller.PERFORMANCE_COUNTER_CATEGORY))
            {
                _performanceCounterCategory = PerformanceCounterCategory.Create(TaskManagerInstaller.PERFORMANCE_COUNTER_CATEGORY, TaskManagerInstaller.PERFORMANCE_COUNTER_DESCRIPTION, PerformanceCounterCategoryType.SingleInstance, ccdc);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Register Orleans perf counters with Windows
        /// </summary>
        /// <remarks>Note: Program needs to be running as Administrator to be able to delete Windows perf counters.</remarks>
        public static void InstallCounters()
        {
            var collection = new CounterCreationDataCollection();

            collection.AddRange(GetCounterCreationData());

            PerformanceCounterCategory.Create(
                CATEGORY_NAME,
                CATEGORY_DESCRIPTION,
                PerformanceCounterCategoryType.SingleInstance,
                collection);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Creates a performance counter category for holding all the configured performance counters.
        /// </summary>
        /// <param name="counters"></param>
        private static void CreatePerformanceCounterCategory(CounterCreationData[] counters)
        {
            var counterData = new CounterCreationDataCollection();

            counterData.AddRange(counters);

            if (PerformanceCounterCategory.Exists(CategoryName))
            {
                PerformanceCounterCategory.Delete(CategoryName);
            }

            PerformanceCounterCategory.Create(CategoryName, "Performance counters defined for Logictracker.", PerformanceCounterCategoryType.SingleInstance, counterData);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Add an average 32-bit timer performance counter to the list that will be created.
        /// </summary>
        /// <param name="name">
        /// The name of the performance counter. This cannot be null, empty or whitespace.
        /// </param>
        /// <param name="help">
        /// The description or help for the performance counter. This cannot be null, empty
        /// or whitespace.
        /// </param>
        /// <returns>
        /// A <seealso cref="PerformanceCounterCategory"/> used for creating additional
        /// performance counters.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// No argument can be null, empty or whitespace.
        /// </exception>
        /// <seealso cref="CreateCategory"/>
        public IPerformanceCounterCategoryFactory AddAverageTimer32(string name, string help)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException(nameof(name));
            }
            if (string.IsNullOrWhiteSpace(help))
            {
                throw new ArgumentNullException(nameof(help));
            }

            // Note: the base must immediately follow the non-base in the list.
            counterCreationDataCollection.AddRange(new []
            {
                new CounterCreationData(name, help,
                                        PerformanceCounterType.AverageTimer32),
                new CounterCreationData(name + PerformanceCounterConstants.BaseSuffix, help,
                                        PerformanceCounterType.AverageBase)
            });

            return(this);
        }
    public static void Main()
    {
        try
        {
            string myCategoryName;
            int    numberOfCounters;
            Console.Write("Enter the number of counters : ");
            numberOfCounters = int.Parse(Console.ReadLine());
            CounterCreationData[] myCounterCreationData =
                new CounterCreationData[numberOfCounters];
            for (int i = 0; i < numberOfCounters; i++)
            {
                Console.Write("Enter the counter name for {0} counter : ", i);
                myCounterCreationData[i]             = new CounterCreationData();
                myCounterCreationData[i].CounterName = Console.ReadLine();
            }
            CounterCreationDataCollection myCounterCollection =
                new CounterCreationDataCollection(myCounterCreationData);
            Console.Write("Enter the category Name : ");
            myCategoryName = Console.ReadLine();
            // Check if the category already exists or not.
            if (!PerformanceCounterCategory.Exists(myCategoryName))
            {
                CounterCreationDataCollection myNewCounterCollection =
                    new CounterCreationDataCollection();
                // Add the 'CounterCreationDataCollection' to 'CounterCreationDataCollection' object.
                myNewCounterCollection.AddRange(myCounterCollection);

                PerformanceCounterCategory.Create(myCategoryName, "Sample Category",
                                                  PerformanceCounterCategoryType.SingleInstance, myNewCounterCollection);

                Console.WriteLine("The list of counters in CounterCollection are: ");
                for (int i = 0; i < myNewCounterCollection.Count; i++)
                {
                    Console.WriteLine("Counter {0} is '{1}'", i + 1, myNewCounterCollection[i].CounterName);
                }
            }
            else
            {
                Console.WriteLine("The category already exists");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: {0}.", e.Message);
            return;
        }
    }
Exemplo n.º 10
0
        /// <summary>
        ///  installs 4 standard counters for the category provided
        /// </summary>
        /// <param name="categoryName"></param>

        public static void InstallStandardCounters(string categoryName)
        {
            var creationDatas = new CounterHandlerBase[]
            {
                new AverageTimeHandler(categoryName, string.Empty),
                new LastOperationExecutionTimeHandler(categoryName, string.Empty),
                new TotalCountHandler(categoryName, string.Empty),
                new NumberOfOperationsPerSecondHandler(categoryName, string.Empty)
            }.SelectMany(x => x.BuildCreationData());

            var counterCreationDataCollection = new CounterCreationDataCollection();

            counterCreationDataCollection.AddRange(creationDatas.ToArray());
            PerformanceCounterCategory.Create(categoryName, "PerfIt category for " + categoryName,
                                              PerformanceCounterCategoryType.MultiInstance, counterCreationDataCollection);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Installs performance counters in the current assembly using PerfItFilterAttribute.
        /// </summary>
        ///
        /// <param name="categoryName">category name for the metrics. If not provided, it will use the assembly name</param>
        public static void Install(Assembly installerAssembly, string categoryName = null)
        {
            Uninstall(installerAssembly, categoryName);

            if (string.IsNullOrEmpty(categoryName))
            {
                categoryName = installerAssembly.GetName().Name;
            }

            var perfItFilterAttributes = FindAllFilters(installerAssembly).ToArray();

            var counterCreationDataCollection = new CounterCreationDataCollection();

            Trace.TraceInformation("Number of filters: {0}", perfItFilterAttributes.Length);

            foreach (var filter in perfItFilterAttributes)
            {
                Trace.TraceInformation("Setting up filters '{0}'", filter.Description);

                foreach (var counterType in filter.Counters)
                {
                    if (!HandlerFactories.ContainsKey(counterType))
                    {
                        throw new ArgumentException("Counter type not defined: " + counterType);
                    }

                    // if already exists in the set then ignore
                    if (counterCreationDataCollection.Cast <CounterCreationData>().Any(x => x.CounterName == counterType))
                    {
                        Trace.TraceInformation("Counter type '{0}' was duplicate", counterType);
                        continue;
                    }

                    using (var counterHandler = HandlerFactories[counterType](categoryName, filter.InstanceName))
                    {
                        counterCreationDataCollection.AddRange(counterHandler.BuildCreationData());
                        Trace.TraceInformation("Added counter type '{0}'", counterType);
                    }
                }
            }


            PerformanceCounterCategory.Create(categoryName, "PerfIt category for " + categoryName,
                                              PerformanceCounterCategoryType.MultiInstance, counterCreationDataCollection);

            Trace.TraceInformation("Built category '{0}' with {1} items", categoryName, counterCreationDataCollection.Count);
        }
Exemplo n.º 12
0
        public static void RegisterContract(Type contractType)
        {
            var categoryAttr = contractType.GetCustomAttribute <PerfCounterCategoryAttribute>();

            if (null == categoryAttr)
            {
                throw new InvalidContractException($"Expected class with a {typeof(PerfCounterCategoryAttribute)} attribute");
            }


            if (PerformanceCounterCategory.Exists(categoryAttr.Name))
            {
                return;
                //throw new CategoryAlreadyExistsException($"Category {categoryAttr.Name} already exists");
            }

            var counterCreationDataCollection = new CounterCreationDataCollection();

            foreach (var prop in contractType.GetProperties())
            {
                var attr = prop.GetCustomAttribute <PerfCounterAttribute>();
                if (null == attr)
                {
                    continue;
                }

                if (prop.GetGetMethod() == null)
                {
                    throw new InvalidContractException($"Property {prop.Name} must have a getter and a setter to be valid.");
                }

                if (prop.PropertyType.BaseType.FullName != typeof(PerformanceCounterBase).FullName)
                {
                    throw new InvalidContractException($"Property {prop.Name} must be of {typeof(PerformanceCounterBase).FullName} type.");
                }

                if (prop.PropertyType.CustomAttributes == null || !prop.PropertyType.CustomAttributes.Any(x => x.AttributeType.FullName == typeof(CounterTypeAttribute).FullName))
                {
                    throw new InvalidContractException($"Property {prop.Name} must have a {typeof(CounterTypeAttribute).FullName} attribute.");
                }

                var counterList = GetCounterCreationData(prop.PropertyType, attr);
                counterCreationDataCollection.AddRange(counterList.ToArray());
            }

            PerformanceCounterCategory.Create(categoryAttr.Name, categoryAttr.Help, PerformanceCounterCategoryType.MultiInstance, counterCreationDataCollection);
        }
        private static CounterCreationDataCollection GetCounterCreationDataCollectionForHttpActionDescriptors(ReflectedHttpActionDescriptor[] httpActionDescriptors)
        {
            var counterCreationDataCollection = new CounterCreationDataCollection();

            Trace.TraceInformation("Number of controller actions: {0}", httpActionDescriptors.Length);

            foreach (var httpActionDescriptor in httpActionDescriptors)
            {
                var methodType = httpActionDescriptor.SupportedHttpMethods.First();

                var controllerName = httpActionDescriptor.ControllerDescriptor.ControllerName;
                var actionName     = httpActionDescriptor.ActionName;

                var param = httpActionDescriptor.MethodInfo.GetParameters()
                            .Select(parameter => string.Format("{0} {1}", parameter.ParameterType.Name, parameter.Name))
                            .ToArray();

                var arguments = string.Join(", ", param);

                var methodIdentifier = ApmWebApiFilterAttributeBase.GetMethodIdentifier(methodType, controllerName, actionName, arguments);
                var eventName        = ApmWebApiFilterAttributeBase.GetEventName(methodType, actionName, controllerName);

                Trace.TraceInformation("Setting up controller action '{0}' for event '{1}'", methodIdentifier, eventName);

                //Setup action performance counters
                foreach (var counterHandler in PerformanceCounterApmApiFilterAttribute.CounterHandlers)
                {
                    if (counterCreationDataCollection.Cast <CounterCreationData>().Any(x => x.CounterName == methodIdentifier))
                    {
                        Trace.TraceInformation("Counter for method '{0}' was duplicate", methodIdentifier);
                    }
                    else
                    {
                        var countersToCreate = counterHandler.GetCreationData(methodIdentifier);
                        foreach (var counterToCreate in countersToCreate)
                        {
                            Trace.TraceInformation("Added counter for method '{0}'", counterToCreate.CounterName);
                        }

                        counterCreationDataCollection.AddRange(countersToCreate);
                    }
                }
            }
            return(counterCreationDataCollection);
        }
        private static void SetupCounters(IEnumerable <ICounterExample> counterWorkers)
        {
            if (PerformanceCounterCategory.Exists(CounterCategory))
            {
                Console.WriteLine("Deleting Performance Category {0}", CounterCategory);
                PerformanceCounterCategory.Delete(CounterCategory);
            }

            var counterCreationDatas = counterWorkers.SelectMany(counterWorker => counterWorker.GetCounterCreationData()).ToArray();

            var counterDataCollection = new CounterCreationDataCollection();

            counterDataCollection.AddRange(counterCreationDatas);

            Console.WriteLine("Creating Performance Category {0}", CounterCategory);
            PerformanceCounterCategory.Create(
                CounterCategory,
                "Demonstrates usage of various performance counter types.",
                PerformanceCounterCategoryType.SingleInstance,
                counterDataCollection);
        }
Exemplo n.º 15
0
        private static CounterCreationDataCollection GetCounterData(string category)
        {
            switch (category)
            {
            case KINESISTAP_PERFORMANCE_COUNTER_CATEGORY:
                return(new CounterCreationDataCollection()
                {
                    CreateCounterCreationData(string.Empty, MetricsConstants.KINESISTAP_BUILD_NUMBER, PerformanceCounterType.NumberOfItems32),
                    CreateCounterCreationData(string.Empty, MetricsConstants.SOURCE_FACTORIES_LOADED, PerformanceCounterType.NumberOfItems32),
                    CreateCounterCreationData(string.Empty, MetricsConstants.SOURCE_FACTORIES_FAILED_TO_LOAD, PerformanceCounterType.NumberOfItems32),
                    CreateCounterCreationData(string.Empty, MetricsConstants.SINK_FACTORIES_LOADED, PerformanceCounterType.NumberOfItems32),
                    CreateCounterCreationData(string.Empty, MetricsConstants.SINK_FACTORIES_FAILED_TO_LOAD, PerformanceCounterType.NumberOfItems32),
                    CreateCounterCreationData(string.Empty, MetricsConstants.SINKS_STARTED, PerformanceCounterType.NumberOfItems32),
                    CreateCounterCreationData(string.Empty, MetricsConstants.SINKS_FAILED_TO_START, PerformanceCounterType.NumberOfItems32),
                    CreateCounterCreationData(string.Empty, MetricsConstants.SOURCES_STARTED, PerformanceCounterType.NumberOfItems32),
                    CreateCounterCreationData(string.Empty, MetricsConstants.SOURCES_FAILED_TO_START, PerformanceCounterType.NumberOfItems32),
                    CreateCounterCreationData(string.Empty, MetricsConstants.PIPES_CONNECTED, PerformanceCounterType.NumberOfItems32),
                    CreateCounterCreationData(string.Empty, MetricsConstants.PIPES_FAILED_TO_CONNECT, PerformanceCounterType.NumberOfItems32),
                    CreateCounterCreationData(string.Empty, MetricsConstants.SELF_UPDATE_FREQUENCY, PerformanceCounterType.NumberOfItems32),
                    CreateCounterCreationData(string.Empty, MetricsConstants.CONFIG_RELOAD_COUNT, PerformanceCounterType.NumberOfItems32),
                    CreateCounterCreationData(string.Empty, MetricsConstants.CONFIG_RELOAD_FAILED_COUNT, PerformanceCounterType.NumberOfItems32)
                });

            case KINESISTAP_PERFORMANCE_COUNTER_SOURCES_CATEGORY:
                return(new CounterCreationDataCollection()
                {
                    CreateCounterCreationData(string.Empty, MetricsConstants.DIRECTORY_SOURCE_BYTES_TO_READ, PerformanceCounterType.NumberOfItems32),
                    CreateCounterCreationData(string.Empty, MetricsConstants.DIRECTORY_SOURCE_FILES_TO_PROCESS, PerformanceCounterType.NumberOfItems32),
                    CreateCounterCreationData(string.Empty, MetricsConstants.DIRECTORY_SOURCE_BYTES_READ, PerformanceCounterType.NumberOfItems32),
                    CreateCounterCreationData(string.Empty, MetricsConstants.DIRECTORY_SOURCE_RECORDS_READ, PerformanceCounterType.NumberOfItems32),
                    CreateCounterCreationData(string.Empty, MetricsConstants.EVENTLOG_SOURCE_EVENTS_READ, PerformanceCounterType.NumberOfItems32),
                    CreateCounterCreationData(string.Empty, MetricsConstants.EVENTLOG_SOURCE_EVENTS_ERROR, PerformanceCounterType.NumberOfItems32),
                });

            case KINESISTAP_PERFORMANCE_COUNTER_SINKS_CATEGORY:
                CounterCreationDataCollection counterData = new CounterCreationDataCollection();
                string[] prefixes = new string[]
                {
                    MetricsConstants.CLOUDWATCHLOG_PREFIX,
                    MetricsConstants.KINESIS_FIREHOSE_PREFIX,
                    MetricsConstants.KINESIS_STREAM_PREFIX
                };

                foreach (string prefix in prefixes)
                {
                    CounterCreationDataCollection sinkCounterData = new CounterCreationDataCollection()
                    {
                        CreateCounterCreationData(prefix, MetricsConstants.RECOVERABLE_SERVICE_ERRORS, PerformanceCounterType.NumberOfItems32),
                        CreateCounterCreationData(prefix, MetricsConstants.NONRECOVERABLE_SERVICE_ERRORS, PerformanceCounterType.NumberOfItems32),
                        CreateCounterCreationData(prefix, MetricsConstants.RECORDS_ATTEMPTED, PerformanceCounterType.NumberOfItems32),
                        CreateCounterCreationData(prefix, MetricsConstants.BYTES_ATTEMPTED, PerformanceCounterType.NumberOfItems32),
                        CreateCounterCreationData(prefix, MetricsConstants.RECORDS_SUCCESS, PerformanceCounterType.NumberOfItems32),
                        CreateCounterCreationData(prefix, MetricsConstants.RECORDS_FAILED_RECOVERABLE, PerformanceCounterType.NumberOfItems32),
                        CreateCounterCreationData(prefix, MetricsConstants.RECORDS_FAILED_NONRECOVERABLE, PerformanceCounterType.NumberOfItems32),
                        CreateCounterCreationData(prefix, MetricsConstants.LATENCY, PerformanceCounterType.NumberOfItems32),
                    };
                    counterData.AddRange(sinkCounterData);
                }
                return(counterData);

            default:
                throw new NotImplementedException($"Category {category} not implemented");
            }
        }