private static void Main(string[] args) { var counters = GetCounters(args[0]); Console.WriteLine("<prtg>"); foreach (var perfCounter in counters) { var split = perfCounter.Id.Split('\\'); var split2 = split[1].Split('('); var categoryName = split2[0]; var counterName = split[2]; var instanceName = split2[1].Substring(0, split2[1].Length - 1); if (PerformanceCounterCategory.InstanceExists(instanceName, categoryName)) { var myCounter = new PerformanceCounter { CategoryName = categoryName, CounterName = counterName, InstanceName = instanceName }; long raw = myCounter.RawValue; Console.WriteLine("<result>"); Console.WriteLine("<channel>" + perfCounter.Name + "</channel>"); Console.WriteLine("<value>" + raw + "</value>"); Console.WriteLine("</result>"); } } Console.WriteLine("</prtg>"); }
private static void WrappedRegister(MetricsContext context, string name, Unit unit, string category, string counter, string instance = null, Func <double, double> derivate = null, MetricTags tags = default(MetricTags)) { log.Debug(() => $"Registering performance counter [{counter}] in category [{category}] for instance [{instance ?? "none"}]"); if (PerformanceCounterCategory.Exists(category)) { if (instance == null || PerformanceCounterCategory.InstanceExists(instance, category)) { if (PerformanceCounterCategory.CounterExists(counter, category)) { var counterTags = new MetricTags(tags.Tags.Concat(new[] { "PerfCounter" })); if (derivate == null) { context.Advanced.Gauge(name, () => new PerformanceCounterGauge(category, counter, instance), unit, counterTags); } else { context.Advanced.Gauge(name, () => new DerivedGauge(new PerformanceCounterGauge(category, counter, instance), derivate), unit, counterTags); } return; } } } if (!isMono) { log.ErrorFormat("Performance counter does not exist [{0}] in category [{1}] for instance [{2}]", counter, category, instance ?? "none"); } }
public static void PerformanceCounterCategory_InstanceExists_StaticInvalid() { Assert.Throws <ArgumentNullException>(() => PerformanceCounterCategory.InstanceExists(null, "Processor", ".")); Assert.Throws <ArgumentNullException>(() => PerformanceCounterCategory.InstanceExists("", null, ".")); Assert.Throws <ArgumentException>(() => PerformanceCounterCategory.InstanceExists("", string.Empty, ".")); Assert.Throws <ArgumentException>(() => PerformanceCounterCategory.InstanceExists("", "Processor", string.Empty)); }
public static long GetPerformanceCounterValue(string categoryName, string instanceName, string counterName) { if (PerformanceCounterCategory.InstanceExists(instanceName, categoryName)) { return(GetPerformanceCounterSample(categoryName, instanceName, counterName).RawValue); } return(0); }
public static bool CanFindPerformanceCounter(PerformanceCounterMetricName name) { var hasInstance = !string.IsNullOrEmpty(name.InstanceName); return(hasInstance ? PerformanceCounterCategory.InstanceExists(name.InstanceName, name.CategoryName) : PerformanceCounterCategory.CounterExists(name.CounterName, name.CategoryName)); }
private void AssertPerformanceCounterInstanceLifetime(IConfigurationItem support, Action <IObjectContainer> action) { using (IObjectContainer db = Db4oEmbedded.OpenFile(NewEmbeddedConfiguration(support), TempFile())) { action(db); Assert.IsTrue(PerformanceCounterCategory.InstanceExists(TempFile(), Db4oPerformanceCounters.CategoryName)); } Assert.IsFalse(PerformanceCounterCategory.InstanceExists(TempFile(), Db4oPerformanceCounters.CategoryName)); }
/// <summary> Reclaim memory. </summary> public void ReclaimMemory() { long mem2 = GC.GetTotalMemory(false); Console.WriteLine(string.Intern("*** Memory at ***" + SystemClock.Instance.GetCurrentInstant().ToDateTimeUtc().ToLocalTime().ToLongDateString() + " " + SystemClock.Instance.GetCurrentInstant().ToDateTimeUtc().ToLocalTime().ToLongTimeString()), Color.Aqua); Console.WriteLine(string.Intern("\tMemory before GC: ") + ToBytes(mem2), Color.Aqua); GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; GC.Collect(); GC.WaitForPendingFinalizers(); long mem3 = GC.GetTotalMemory(false); Console.WriteLine(string.Intern("\tMemory after GC: ") + ToBytes(mem3), Color.Aqua); Console.WriteLine("\tApp memory being used: " + ToBytes(Environment.WorkingSet), Color.Aqua); int gen1 = 0; int gen2 = 0; for (int x = 0; x < GC.MaxGeneration; x++) { if (x == 0) { gen1 = GC.CollectionCount(x); } else if (x == 1) { gen2 = GC.CollectionCount(x); } Console.WriteLine("\t\tGeneration " + (x) + " Collection Count: " + GC.CollectionCount(x), Color.Aqua); } const string category = ".NET CLR Memory"; const string counter = "% Time in GC"; string instance = System.Diagnostics.Process.GetCurrentProcess().ProcessName; float percent = 0.0F; if (PerformanceCounterCategory.Exists(category) && PerformanceCounterCategory.CounterExists(counter, category) && PerformanceCounterCategory.InstanceExists(instance, category)) { var gcPerf = new PerformanceCounter(category, counter, instance); percent = gcPerf.NextValue(); string suffix = "%"; if (percent > 50.0) { suffix += " <- High Watermark Warning"; } Console.WriteLine("\t\tTime Spent in GC: " + $"{percent:00.##}" + suffix, Color.Aqua); } PublishMemoryUpdateMessage(gen1, gen2, percent, ToBytes(mem2), ToBytes(mem3)); Console.WriteLine(string.Intern("*** Memory ***"), Color.Aqua); }
public static void PerformanceCounterCategory_InstanceExists_Static() { PerformanceCounterCategory pcc = Helpers.RetryOnAllPlatforms(() => new PerformanceCounterCategory("Processor")); string[] instances = pcc.GetInstanceNames(); Assert.True(instances.Length > 0); foreach (string instance in instances) { Assert.True(PerformanceCounterCategory.InstanceExists(instance, "Processor")); } }
//<Snippet10> public static void Main(string[] args) { string categoryName = ""; string instanceName = ""; string machineName = ""; bool objectExists = false; const string SINGLE_INSTANCE_NAME = "systemdiagnosticsperfcounterlibsingleinstance"; // Copy the supplied arguments into the local variables. try { categoryName = args[0]; instanceName = args[1]; machineName = args[2] == "."? "": args[2]; } catch (Exception ex) { // Ignore the exception from non-supplied arguments. } // Use the given instance name or use the default single-instance name. if (instanceName.Length == 0) { instanceName = SINGLE_INSTANCE_NAME; } try { // Check whether the specified instance exists. // Use the static forms of the InstanceExists method. if (machineName.Length == 0) { objectExists = PerformanceCounterCategory.InstanceExists(instanceName, categoryName); } else { objectExists = PerformanceCounterCategory.InstanceExists(instanceName, categoryName, machineName); } } catch (Exception ex) { Console.WriteLine("Unable to check for the existence of " + "instance \"{0}\" in category \"{1}\" on " + (machineName.Length > 0? "computer \"{2}\":": "this computer:") + "\n" + ex.Message, instanceName, categoryName, machineName); return; } // Tell the user whether the instance exists. Console.WriteLine("Instance \"{0}\" " + (objectExists? "exists": "does not exist") + " in category \"{1}\" on " + (machineName.Length > 0? "computer \"{2}\".": "this computer."), instanceName, categoryName, machineName); }
/// <summary> /// This method returns true if the given PerformanceCounterSpec <paramref name="pcs"/> refers to a counter instance that exists in the indicated category /// </summary> public bool IsValid(PerformanceCounterSpec pcs) { if (pcs == null || pcs.CategoryName.IsNullOrEmpty() || pcs.CounterName.IsNullOrEmpty()) { return(false); } lock (mutex) { InitializeIfNeeded(); try { PerformanceCounterCategory pcc = null; if (!pccDictionary.TryGetValue(pcs.CategoryName, out pcc) || pcc == null) { return(false); } PerformanceCounter [] perfCtrArray = null; if (pcs.InstanceName.IsNullOrEmpty()) { perfCtrArray = pcc.GetCounters(); } else { if (!pcc.InstanceExists(pcs.InstanceName)) { return(false); } perfCtrArray = pcc.GetCounters(pcs.InstanceName); } if (perfCtrArray.Any(pc => pc.CounterName == pcs.CounterName)) { return(true); } else { return(false); } } catch (System.Exception ex) { Logger.Debug.Emit("IsValid on point '{0}' failed: {1}", pcs.PointName, ex.ToString(ExceptionFormat.TypeAndMessage)); return(false); } } }
public bool InstanceExists(string instanceName, string categoryName, object machineName) { string strMachineName = null; if (machineName != Undefined.Value && machineName != Null.Value) { strMachineName = TypeConverter.ToString(machineName); } return(String.IsNullOrEmpty(strMachineName) ? PerformanceCounterCategory.InstanceExists(instanceName, categoryName) : PerformanceCounterCategory.InstanceExists(instanceName, categoryName, strMachineName)); }
private int GetCounterValue(string counterName) { string categoryName = "Enterprise Library Logging Counters"; string instanceName = new AppDomainNameFormatter().CreateName("Total"); if (PerformanceCounterCategory.InstanceExists(instanceName, categoryName)) { using (PerformanceCounter counter = new PerformanceCounter()) { counter.CategoryName = categoryName; counter.CounterName = counterName; counter.InstanceName = instanceName; return((int)counter.RawValue); } } return(0); }
PerformanceCounter GetCounter(string category, string counter, PerformanceCounterType type = PerformanceCounterType.AverageCount64, string machine = ".", string instance = "_Total") { if (!PerformanceCounterCategory.Exists(category)) { // create category var counterInfos = new CounterCreationDataCollection(); var counterInfo = new CounterCreationData() { CounterType = type, CounterName = counter, }; counterInfos.Add(counterInfo); PerformanceCounterCategory .Create(category, category, counterInfos); // check creation var counters = new PerformanceCounterCategory(category, machine); if (!counters.CounterExists(counter)) { Debug.Fail("Counter was not created"); } if (!counters.InstanceExists(instance)) { Debug.Fail("Instance not found"); } } // get counter var perfCounter = new PerformanceCounter { CategoryName = category, CounterName = counter, MachineName = machine, ReadOnly = false, }; perfCounter.IncrementBy(10); return(perfCounter); }
public void TestNetworkingCounters() { IServerConfiguration config = Db4oClientServer.NewServerConfiguration(); config.Common.Add(new NetworkingMonitoringSupport()); using (IObjectServer server = Db4oClientServer.OpenServer(config, TempFile(), Db4oClientServer.ArbitraryPort)) { const string userName = "******"; const string password = userName; server.GrantAccess(userName, password); IObjectContainer client = Db4oClientServer.OpenClient("localhost", server.Ext().Port(), userName, password); client.Close(); Assert.IsTrue(PerformanceCounterCategory.InstanceExists(TempFile(), Db4oPerformanceCounters.CategoryName)); } Assert.IsFalse(PerformanceCounterCategory.InstanceExists(TempFile(), Db4oPerformanceCounters.CategoryName)); }
public CategoryDetails(PerformanceCounterCategory cat) { instances = cat.GetInstanceNames(); if (instances.Any()) { foreach (string instanceName in instances) { if (cat.InstanceExists(instanceName)) { counters = cat.GetCounters(instanceName).Select(c => new PCCounter(c.CounterName, c.CounterHelp)).ToArray(); break; } } } else { counters = cat.GetCounters().Select(c => new PCCounter(c.CounterName, c.CounterHelp)).ToArray(); } }
protected override void DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { log.Debug("CountWorker is working."); var counters = context.Counters; lock (context.key) { log.Debug("CountWorker aquired counter lock."); int counterCount = 0; Stopwatch timer = new Stopwatch(); timer.Start(); foreach (var c in counters.Keys) { counterCount++; if (worker.CancellationPending) { e.Cancel = true; break; } var counter = counters[c]; var performanceCounter = counter.PerformanceCounter; if (string.IsNullOrEmpty(performanceCounter.InstanceName) || PerformanceCounterCategory.InstanceExists(performanceCounter.InstanceName, performanceCounter.CategoryName)) { counter.Sample(); // Rate limit to prevent spiking the CPU. Thread.Sleep(this.rateLimit); } } timer.Stop(); log.Debug("{0} counters in {1} seconds.", counterCount, timer.Elapsed.TotalSeconds); log.Debug("{0} counters per second.", counterCount / timer.Elapsed.TotalSeconds); } log.Debug("CountWorker finished."); }
public frmAVDevices(RegistryKey cxpclientkey) { InitializeComponent(); cxpclientRegKey = cxpclientkey; if (PerformanceCounterCategory.Exists("Processor") && PerformanceCounterCategory.CounterExists("% Processor Time", "Processor") && PerformanceCounterCategory.InstanceExists("_Total", "Processor")) { pcCPU = new PerformanceCounter("Processor", "% Processor Time", "_Total"); } if (PerformanceCounterCategory.Exists("Process") && PerformanceCounterCategory.CounterExists("Working Set", "Process") && PerformanceCounterCategory.InstanceExists( System.Reflection.Assembly.GetEntryAssembly().GetName(false).Name, "Process")) { pcMem = new PerformanceCounter("Process", "Working Set", System.Reflection.Assembly.GetEntryAssembly().GetName(false).Name); } }
/// <summary> /// Initializes the counter. /// </summary> private void InitializeCounter() { if (category != null) { CounterExists = category.CounterExists(Name); if (CounterExists) { if (IsSingleInstance) { counter = new PerformanceCounter(CategoryName, Name, true); } else { InstanceExists = category.InstanceExists(InstanceName); if (InstanceExists) { counter = new PerformanceCounter(CategoryName, Name, InstanceName, true); } } } } }
public static float ProcessCPU_Usage(string name, bool asPercentage = true) { try { if (counterList.ContainsKey(name)) { float result0 = counterList[name].NextValue(); if (asPercentage) { result0 = result0 / Environment.ProcessorCount; } return(result0); } if (!PerformanceCounterCategory.InstanceExists(name, "Process")) { return(-1); } PerformanceCounter cpuCounterX = new PerformanceCounter("Process", "% Processor Time", name); counterList.Add(name, cpuCounterX); decimal result = cpuCounterX.NextValue().ToDecimal(); if (asPercentage) { result = (result / Environment.ProcessorCount); } return(result.ToFloat()); } catch { return(-1); } }
/// <summary> Reclaim memory. </summary> public static void ReclaimMemory() { long mem2 = GC.GetTotalMemory(false); Debug.Print(string.Intern("*** Memory ***")); Debug.Print(string.Intern("\tMemory before GC: ") + ToBytes(mem2)); GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; GC.Collect(); GC.WaitForPendingFinalizers(); long mem3 = GC.GetTotalMemory(false); Debug.Print(string.Intern("\tMemory after GC: ") + ToBytes(mem3)); Debug.Print("\tApp memory being used: " + ToBytes(Environment.WorkingSet)); for (int x = 0; x < GC.MaxGeneration; x++) { Debug.Print("\t\tGeneration " + (x) + " Collection Count: " + GC.CollectionCount(x)); } const string category = ".NET CLR Memory"; const string counter = "% Time in GC"; string instance = Process.GetCurrentProcess().ProcessName; if (PerformanceCounterCategory.Exists(category) && PerformanceCounterCategory.CounterExists(counter, category) && PerformanceCounterCategory.InstanceExists(instance, category)) { var gcPerf = new PerformanceCounter(category, counter, instance); float percent = gcPerf.NextValue(); string suffix = "%"; if (percent > 50.0) { suffix += " <- High Watermark Warning"; } Debug.Print("\t\tTime Spent in GC: " + $"{percent:00.##}" + suffix); } Debug.Print(string.Intern("*** Memory ***")); }
/// <summary> /// List the counters available for a given category name /// </summary> /// <param name="categoryName">Category name (string)</param> static void ListCategoryAvailableCounters(string categoryName) { //Get all performance categories PerformanceCounterCategory[] perfCats = PerformanceCounterCategory.GetCategories(); //Get single category by category name. PerformanceCounterCategory cat = perfCats.Where(c => c.CategoryName == categoryName).FirstOrDefault(); Console.WriteLine("Category Name: {0}", cat.CategoryName); //Get all instances available for category string[] instances = cat.GetInstanceNames(); if (instances.Length == 0) { //This block will execute when category has no instance. //loop all the counters available withing category foreach (PerformanceCounter counter in cat.GetCounters()) { Console.WriteLine(" Counter Name: {0}", counter.CounterName); } } else { //This block will execute when category has one or more instances. foreach (string instance in instances) { Console.WriteLine(" Instance Name: {0}", instance); if (cat.InstanceExists(instance)) { //loop all the counters available withing category foreach (PerformanceCounter counter in cat.GetCounters(instance)) { Console.WriteLine(" Counter Name: {0}", counter.CounterName); } } } } }
public void CanCreate_MultiInstanceCounters(int numOfCounters) { // Arrange & Act var helpers = new List <CounterHelper <MultiInstanceCategory> >(); for (int i = 0; i < numOfCounters; i++) { var instanceName = GetInstanceName(i); helpers.Add(PerformanceHelper.CreateCounterHelper <MultiInstanceCategory>(instanceName)); } // Assert for (int i = 0; i < numOfCounters; i++) { Assert.IsTrue(PerformanceCounterCategory.CounterExists(AvgCounterName, CategoryName)); Assert.IsTrue(PerformanceCounterCategory.CounterExists(NumCounterName, CategoryName)); Assert.IsTrue(PerformanceCounterCategory.InstanceExists(GetInstanceName(i), CategoryName)); var category = PerformanceCounterCategory.GetCategories().First(cat => cat.CategoryName == CategoryName); var instanceNames = category.GetInstanceNames().OrderBy(name => name).ToArray(); Assert.AreEqual(GetInstanceName(i), instanceNames[i]); } }
private void InitializeCounters() { _log.InfoFormat("Verifying performance counter installation for category '{0}'...", _category); try { if (!PerformanceCounterCategory.Exists(_category)) { _log.WarnFormat("Performance counters in category '{0}' are not installed.", _category); return; } // Zero all counters in the current category. _log.InfoFormat("Zeroing all performance counters in category/instance '{0}'/'{1}' ", _category, _instanceName); var cat = new PerformanceCounterCategory(_category); if (cat.InstanceExists(_instanceName)) { foreach (PerformanceCounter counter in cat.GetCounters(_instanceName)) { try { counter.ReadOnly = false; counter.RawValue = 0; } finally { counter.Dispose(); } } } } catch (Exception x) { _log.Error(String.Format("Initializing perf counter category/instance {0}/{1} failed.", _category, _instanceName), x); } }
private static void ListCounters(string categoryName) { PerformanceCounterCategory category = PerformanceCounterCategory.GetCategories().First(c => c.CategoryName == categoryName); Console.WriteLine("{0} [{1}]", category.CategoryName, category.CategoryType); string[] instanceNames = category.GetInstanceNames(); Array.Sort(instanceNames); if (instanceNames.Any()) { foreach (string instanceName in instanceNames) { if (category.InstanceExists(instanceName)) { ListInstances(category, instanceName); } } } else { ListInstances(category, string.Empty); } }
//<snippet28> //<snippet4> public static void Main(string[] args) { string categoryName = ""; //</snippet4> string counterName = ""; //</snippet28> //<snippet6> string instanceName = ""; //<snippet5> string machineName = ""; //</snippet5> //</snippet6> //<snippet3> string categoryHelp = ""; string counterHelp = ""; //</snippet3> //<snippet7> //<snippet8> bool objectExists = false; //</snippet8> PerformanceCounterCategory pcc; //</snippet7> bool createCategory = false; //<snippet9> //<Snippet10> // Copy the supplied arguments into the local variables. try { categoryName = args[0]; //</Snippet10> counterName = args[1]; //</snippet9> //<Snippet11> instanceName = args[2]; //<Snippet12> machineName = args[3] == "."? "": args[3]; //</Snippet12> //</Snippet11> //<Snippet13> categoryHelp = args[4]; counterHelp = args[5]; //<Snippet14> //<Snippet15> //<Snippet16> } catch (Exception ex) { // Ignore the exception from non-supplied arguments. } // Verify that the category name is not blank. if (categoryName.Length == 0) { Console.WriteLine("Category name cannot be blank."); return; } //</Snippet13> // Check whether the specified category exists. //</Snippet16> if (machineName.Length == 0) //<Snippet17> { objectExists = PerformanceCounterCategory.Exists(categoryName); //</Snippet17> } else { // Handle the exception that is thrown if the computer // cannot be found. try { objectExists = PerformanceCounterCategory.Exists(categoryName, machineName); } catch (Exception ex) { Console.WriteLine("Error checking for existence of " + "category \"{0}\" on computer \"{1}\":" + "\n" + ex.Message, categoryName, machineName); return; } } //</Snippet15> // Tell the user whether the specified category exists. Console.WriteLine("Category \"{0}\" " + (objectExists? "exists on ": "does not exist on ") + (machineName.Length > 0? "computer \"{1}\".": "this computer."), categoryName, machineName); //</Snippet14> // If no counter name is given, the program cannot continue. if (counterName.Length == 0) { return; } // A category can only be created on the local computer. //<Snippet18> if (!objectExists) //</Snippet18> { if (machineName.Length > 0) //<Snippet19> { return; //</Snippet19> } else { createCategory = true; } //<Snippet20> //<Snippet21> } else { //</Snippet21> // Check whether the specified counter exists. if (machineName.Length == 0) { objectExists = PerformanceCounterCategory.CounterExists(counterName, categoryName); } else { objectExists = PerformanceCounterCategory.CounterExists(counterName, categoryName, machineName); } // Tell the user whether the counter exists. Console.WriteLine("Counter \"{0}\" " + (objectExists? "exists": "does not exist") + " in category \"{1}\" on " + (machineName.Length > 0? "computer \"{2}\".": "this computer."), counterName, categoryName, machineName); //</Snippet20> // If the counter does not exist, consider creating it. if (!objectExists) // If this is a remote computer, // exit because the category cannot be created. { if (machineName.Length > 0) { return; } else { // Ask whether the user wants to recreate the category. Console.Write("Do you want to delete and recreate " + "category \"{0}\" with your new counter? [Y/N]: ", categoryName); string userReply = Console.ReadLine(); // If yes, delete the category so it can be recreated later. if (userReply.Trim().ToUpper() == "Y") //<Snippet22> { PerformanceCounterCategory.Delete(categoryName); //</Snippet22> createCategory = true; } else { return; } } } } // Create the category if it was deleted or it never existed. if (createCategory) //<Snippet23> { pcc = PerformanceCounterCategory.Create(categoryName, categoryHelp, counterName, counterHelp); Console.WriteLine("Category \"{0}\" with counter \"{1}\" created.", pcc.CategoryName, counterName); //</Snippet23> } else if (instanceName.Length > 0) { if (machineName.Length == 0) { objectExists = PerformanceCounterCategory.InstanceExists(instanceName, categoryName); } else { objectExists = PerformanceCounterCategory.InstanceExists(instanceName, categoryName, machineName); } // Tell the user whether the instance exists. Console.WriteLine("Instance \"{0}\" " + (objectExists? "exists": "does not exist") + " in category \"{1}\" on " + (machineName.Length > 0? "computer \"{2}\".": "this computer."), instanceName, categoryName, machineName); //<Snippet25> } //<Snippet26> }
/// <summary> /// Initializes the counter instances and category. /// </summary> public void InitializePerfCounters(bool inproc) { try { if (!UserHasAccessRights) { return; } lock (this) { int ncounter = 1; string instname = _instanceName; if (inproc) { int processid = Process.GetCurrentProcess().Id; while (PerformanceCounterCategory.InstanceExists(instname, PC_CATEGORY)) { instname = _instanceName + ":" + ncounter.ToString() + " - " + processid.ToString() + _port; ncounter++; } _instanceName = instname; } _pcCount = new PerformanceCounter(PC_CATEGORY, "Count", _instanceName, false); _pcCachelastAccessCount = new PerformanceCounter(PC_CATEGORY, "CacheLastAccessCount", _instanceName, false); _pcGetPerSec = new PerformanceCounter(PC_CATEGORY, "Fetches/sec", _instanceName, false); _pcAddPerSec = new PerformanceCounter(PC_CATEGORY, "Additions/sec", _instanceName, false); _pcUpdPerSec = new PerformanceCounter(PC_CATEGORY, "Updates/sec", _instanceName, false); _pcDelPerSec = new PerformanceCounter(PC_CATEGORY, "Deletes/sec", _instanceName, false); _pcMsecPerGetAvg = new PerformanceCounter(PC_CATEGORY, "Average us/fetch", _instanceName, false); _pcMsecPerGetBase = new PerformanceCounter(PC_CATEGORY, "Average us/fetch base", _instanceName, false); _usMsecPerGet = new UsageStats(); _pcMsecPerAddAvg = new PerformanceCounter(PC_CATEGORY, "Average us/add", _instanceName, false); _pcMsecPerAddBase = new PerformanceCounter(PC_CATEGORY, "Average us/add base", _instanceName, false); _usMsecPerAdd = new UsageStats(); _pcMsecPerUpdAvg = new PerformanceCounter(PC_CATEGORY, "Average us/insert", _instanceName, false); _pcMsecPerUpdBase = new PerformanceCounter(PC_CATEGORY, "Average us/insert base", _instanceName, false); _usMsecPerUpd = new UsageStats(); _pcMsecPerDelAvg = new PerformanceCounter(PC_CATEGORY, "Average us/remove", _instanceName, false); _pcMsecPerDelBase = new PerformanceCounter(PC_CATEGORY, "Average us/remove base", _instanceName, false); _usMsecPerDel = new UsageStats(); _pcExpiryPerSec = new PerformanceCounter(PC_CATEGORY, "Expirations/sec", _instanceName, false); _pcEvictPerSec = new PerformanceCounter(PC_CATEGORY, "Evictions/sec", _instanceName, false); _pcHitsPerSec = new PerformanceCounter(PC_CATEGORY, "Hits/sec", _instanceName, false); _pcHitsRatioSec = new PerformanceCounter(PC_CATEGORY, "Hits ratio/sec (%)", _instanceName, false); _pcHitsRatioSecBase = new PerformanceCounter(PC_CATEGORY, "Hits ratio/sec base", _instanceName, false); _pcMissPerSec = new PerformanceCounter(PC_CATEGORY, "Misses/sec", _instanceName, false); _pcStateTxfrPerSec = new PerformanceCounter(PC_CATEGORY, "State transfer/sec", _instanceName, false); _pcMirrorQueueSize = new PerformanceCounter(PC_CATEGORY, "Mirror queue size", _instanceName, false); _pcSlidingIndexQueueSize = new PerformanceCounter(PC_CATEGORY, "Sliding Index queue size", _instanceName, false); _pcDataBalPerSec = new PerformanceCounter(PC_CATEGORY, "Data balance/sec", _instanceName, false); _pcCacheSize = new PerformanceCounter(PC_CATEGORY, "Cache Size", _instanceName, false); _pcQueryIndexSize = new PerformanceCounter(PC_CATEGORY, "Query Index Size", _instanceName, false); _pcEvictionIndexSize = new PerformanceCounter(PC_CATEGORY, "Eviction Index Size", _instanceName, false); _pcExpirationIndexSize = new PerformanceCounter(PC_CATEGORY, "Expiration Index Size", _instanceName, false); _pcQueryPerSec = new PerformanceCounter(PC_CATEGORY, "Queries/sec", _instanceName, false); _pcAvgQueryExecutionTime = new PerformanceCounter(PC_CATEGORY, "Average us/Query Execution", _instanceName, false); _pcAvgQueryExecutionTimeBase = new PerformanceCounter(PC_CATEGORY, "Average us/Query Execution base", _instanceName, false); _usMsecPerQueryExecution = new UsageStats(); _pcAvgQuerySize = new PerformanceCounter(PC_CATEGORY, "Average Query Size", _instanceName, false); _pcAvgQuerySizeBase = new PerformanceCounter(PC_CATEGORY, "Average Query Size base", _instanceName, false); _usMsecPerDel = new UsageStats(); } } catch (Exception e) { NCacheLog.Error("PerfStatsCollector.PerfStatsCollector()", e.Message); } }
/// <summary> /// Initialize perf counter instance based on shard map name /// </summary> /// <param name="shardMapName"></param> public PerfCounterInstance(string shardMapName) { #if NETFRAMEWORK _initialized = false; _instanceName = string.Concat(Process.GetCurrentProcess().Id.ToString(), "-", shardMapName); try { // check if caller has permissions to create performance counters. if (!PerfCounterInstance.HasCreatePerformanceCounterPermissions()) { // Trace out warning and continue Tracer.TraceWarning(TraceSourceConstants.ComponentNames.PerfCounter, "create", "User does not have permissions to create performance counters, no performance data will be collected."); } else { // check if PerformanceCounterCategory exists if (!PerformanceCounterCategory.Exists(PerformanceCounters.ShardManagementPerformanceCounterCategory)) { // We are not creating performance counter category here as per recommendation in documentation, copying note from // https://msdn.microsoft.com/en-us/library/sb32hxtc(v=vs.110).aspx // It is strongly recommended that new performance counter categories be created // during the installation of the application, not during the execution of the application. // This allows time for the operating system to refresh its list of registered performance counter categories. // If the list has not been refreshed, the attempt to use the category will fail. // Trace out warning and continue Tracer.TraceWarning(TraceSourceConstants.ComponentNames.PerfCounter, "create", "Performance counter category {0} does not exist, no performance data will be collected.", PerformanceCounters.ShardManagementPerformanceCounterCategory); } else { // Check if specific instance exists if (PerformanceCounterCategory.InstanceExists(_instanceName, PerformanceCounters.ShardManagementPerformanceCounterCategory)) { // As performance counters are created with Process lifetime and instance name is unique (PID + shard map name), // this should never happen. Trace out error and silently continue. Tracer.TraceWarning(TraceSourceConstants.ComponentNames.PerfCounter, "create", "Performance counter instance {0} already exists, no performance data will be collected.", _instanceName); } else { // now initialize all counters for this instance _counters = new Dictionary <PerformanceCounterName, PerformanceCounterWrapper>(); foreach (PerfCounterCreationData d in PerfCounterInstance.counterList) { _counters.Add(d.CounterName, new PerformanceCounterWrapper( PerformanceCounters.ShardManagementPerformanceCounterCategory, _instanceName, d.CounterDisplayName)); } // check that atleast one performance counter was created, so that we can remove instance as part of Dispose() _initialized = _counters.Any(c => c.Value._isValid = true); } } } } catch (Exception e) { // Note: If any of the initialization calls throws, log the exception and silently continue. // No perf data will be collected in this case. // All other non-static code paths access PerformanceCounter and PerformanceCounterCategory // objects only if _initialized is set to true. Tracer.TraceWarning(TraceSourceConstants.ComponentNames.PerfCounter, "PerfCounterInstance..ctor", "Exception caught while creating performance counter instance, no performance data will be collected. Exception: {0}", e.ToString()); } #endif }
public bool InstanceExists(string instanceName) { return(m_performanceCounterCategory.InstanceExists(instanceName)); }
public string pc() { Dictionary<string, List<PerformanceCounter>> counters = new Dictionary<string, List<PerformanceCounter>>(); List<PerformanceCounter> cpuList = new List<PerformanceCounter>(); List<PerformanceCounter> procList = new List<PerformanceCounter>(); List<PerformanceCounter> memList = new List<PerformanceCounter>(); PerformanceCounterCategory perfCat = new PerformanceCounterCategory(); foreach (Process process in Process.GetProcesses()) { PerformanceCounter procProcesTimeCounter = new PerformanceCounter( "Process", "% Processor Time", process.ProcessName); var proc = procProcesTimeCounter; procList.Add(proc); procProcesTimeCounter.NextValue(); PerformanceCounter procCPUTimeCounter = new PerformanceCounter( "Processor", "% Processor Time", process.ProcessName); //procCPUTimeCounter.CategoryName= "Processor"; perfCat.CategoryName = procCPUTimeCounter.CategoryName; var ex = PerformanceCounterCategory.Exists("Processor"); if (ex) { cpuList.Add(procCPUTimeCounter); //if(procCPUTimeCounter.InstanceName //if(procCPUTimeCounter.InstanceName == process.ProcessName) procCPUTimeCounter.NextValue(); } PerformanceCounter procMemTimeCounter = new PerformanceCounter( "Memory", "Available MBytes", process.ProcessName); ex = perfCat.InstanceExists(process.ProcessName); if (ex) { var mem = procMemTimeCounter; memList.Add(mem); procMemTimeCounter.NextValue(); } /* var oktoplot = Convert.ToUInt32(v) != 0; if (oktoplot) counters.Add(procProcesTimeCounter); */ } counters.Add("CPUs", cpuList); counters.Add("PROCs", procList); counters.Add("MEMs", memList); System.Threading.Thread.Sleep(2250); // 1 second wait ("Memory", "Available MBytes") StringBuilder SbRw = new StringBuilder(); SbRw.Append("<table id = 'tblMainCounters'>"); List<string> couterNames = new List<string>(); foreach (string cName in counters.Keys) { couterNames.Add(cName); } foreach (string cNameStr in couterNames) { SbRw.Append("\r\n\t<tr>\r\n\t\t<td>\r\n\t\t\t<table id='tbl" + cNameStr + "'>\r\n\t\t\t\t"); for (int i = 0; i < counters[cNameStr].Count; i++) { //string ToPRint = counters[cNameStr].ElementAt(i).NextValue().ToString(); //bool OkToprint = string.IsNullOrEmpty(ToPRint) == false && ToPRint != (0.0).ToString() && ToPRint != (0).ToString(); //if (OkToprint) SbRw.Append(string.Format("\r\n\t\t\t\t\t<tr id='{0}List{1}'>\r\n\t\t\t\t\t\t<td>Category : </td><td>{2}</td><td> Process : </td><td>{3}</td><td> CounterName : </td><td>{4}</td><td> CPU Usage : </td><td><b> {5}%</b></td>\r\n\t\t\t\t\t</tr>", cNameStr, i.ToString(), counters[cNameStr].ElementAt(i).CategoryName, counters[cNameStr].ElementAt(i).InstanceName, counters[cNameStr].ElementAt(i).CounterName, counters[cNameStr].ElementAt(i).NextValue())); } SbRw.Append("</table><!-- Closing table_" + cNameStr + " -->\r\n\t\t\t</td>\r\n\t\t</tr>"); } SbRw.Append("</table><!-- Closing tableMainCounters --><br /><br />"); return(SbRw.ToString()); }
public static void Print(string[] path) { string[] filteredPath = path == null ? new string[0] : path.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => UnQuote(s)).ToArray(); if (filteredPath.Length == 0) { Console.WriteLine("Categories:"); var categories = PerformanceCounterCategory.GetCategories().OrderBy(c => c.CategoryName); string intend = new string(' ', 4); foreach (var category in categories) { Console.WriteLine(intend + category.CategoryName); } } else { PerformanceCounterCategory category = FindCategory(filteredPath[0]); if (category == null) { Console.WriteLine("Unkown category: " + filteredPath[0]); } else { Console.WriteLine("Category: " + category.CategoryName); if (filteredPath.Length == 1) { var instances = category.GetInstanceNames(); if (instances.Any()) { Console.WriteLine(); Console.WriteLine("Instances:"); string intend = new string(' ', 4); foreach (var instance in instances) { Console.WriteLine(intend + instance); } } else { Console.WriteLine("Instance: [None]"); Console.WriteLine(); Console.WriteLine("Counters:"); string intend = new string(' ', 4); foreach (var counter in category.GetCounters()) { Console.WriteLine(intend + counter.CounterName + " (" + counter.CounterType + ")"); } } } else { if (!category.InstanceExists(filteredPath[1])) { Console.WriteLine("Unkown instance: " + filteredPath[1]); } else { Console.WriteLine("Instance: " + filteredPath[1]); Console.WriteLine(); Console.WriteLine("Counters:"); string intend = new string(' ', 4); string instanceName = filteredPath[1]; foreach (var counter in category.GetCounters(instanceName)) { Console.WriteLine(intend + counter.CounterName + " (" + counter.CounterType + ")"); } } } } } }