public static void PerformanceCounterCategory_CounterExists_Invalid() { PerformanceCounterCategory pcc = new PerformanceCounterCategory(); Assert.Throws <ArgumentNullException>(() => pcc.CounterExists(null)); Assert.Throws <InvalidOperationException>(() => pcc.CounterExists("Interrupts/sec")); }
public bool RemovePerformanceCounter(string counterName) { if (!_category.CounterExists(counterName)) { return(false); } if (!_counters.ContainsKey(counterName)) { return(true); } _counters[counterName].Dispose(); _counters.Remove(counterName); _beanInfoDirty = true; return(true); }
private static Dictionary <string, PerformanceCounter> GetCounters(string processName) { var perfCounters = new Dictionary <string, PerformanceCounter>(); if (PerformanceCounterCategory.Exists("Process")) { if (PerformanceCounterCategory.CounterExists("Working Set", "Process")) { perfCounters.Add("Working Set", new PerformanceCounter("Process", "Working Set", processName, true)); } if (PerformanceCounterCategory.CounterExists("% Processor Time", "Process")) { perfCounters.Add("CPU", new PerformanceCounter("Process", "% Processor Time", processName, true)); } } if (PerformanceCounterCategory.Exists("Memory")) { if (PerformanceCounterCategory.CounterExists("Available Mbytes", "Memory")) { perfCounters.Add("Available Memory", new PerformanceCounter("Memory", "Available Mbytes", true)); } } return(perfCounters); }
private static IPerformanceCounter GetInstance(PerformanceCounterCategoryAttribute categoryAttribute, PerformanceCounterAttribute counterAttribute, bool readOnly) { var categoryName = categoryAttribute.CategoryName; var categoryType = categoryAttribute.CategoryType; var counterName = counterAttribute.CounterName; var counterType = counterAttribute.CounterType; try { if (PerformanceCounterCategory.Exists(categoryName) && PerformanceCounterCategory.CounterExists(counterName, categoryName)) { var instanceName = categoryType == PerformanceCounterCategoryType.SingleInstance ? string.Empty : Process.GetCurrentProcess().ProcessName; var counter = new PerformanceCounter(categoryName, counterName, instanceName, readOnly); return(new PerformanceCounterProxy(counter)); } } catch { } return(new NullPerformanceCounter(counterName, counterType)); }
public static string GetInstanceName(Process process) { var counterName = ToString(CounterName.ProcessID); var categoryName = ToString(CategoryName.Process); if (PerformanceCounterCategory.CounterExists(counterName, categoryName)) { Process[] processes = Process.GetProcessesByName(process.ProcessName); if (processes.Length > 0) { for (var i = processes.Length - 1; i >= 0; i--) { var instanceName = i == 0 ? process.ProcessName : process.ProcessName + "#" + i; try { using (var counter = new PerformanceCounter(categoryName, counterName, instanceName)) { if (process.Id == counter.RawValue) { return(instanceName); } } } catch (Exception ex) { Util.Logging.Log(ex); } } } } return(null); }
static void Monitor(string category, string counter, string instance, EventWaitHandle stopper) { if (!PerformanceCounterCategory.Exists(category)) { throw new InvalidOperationException("Kategoria nie istnieje"); } if (!PerformanceCounterCategory.CounterExists(counter, category)) { throw new InvalidOperationException("Licznik nie istnieje"); } if (instance == null) { instance = ""; } if (instance != "" && !PerformanceCounterCategory.InstanceExists(instance, category)) { throw new InvalidOperationException("Egzemplarz nie istnieje."); } float lastValue = 0f; using (PerformanceCounter pc = new PerformanceCounter(category, counter, instance)) { while (!stopper.WaitOne(200, false)) { float value = pc.NextValue(); if (!value.Equals(lastValue)) { Console.WriteLine(category + ": " + value); lastValue = value; } } } }
private string GetInstanceName(Process process) { if (PerformanceCounterCategory.CounterExists("ID Process", "Process")) { Process[] processes = Process.GetProcessesByName(process.ProcessName); if (processes.Length > 0) { for (var i = processes.Length - 1; i >= 0; i--) { string name = i == 0 ? process.ProcessName : process.ProcessName + "#" + i; try { using (var counter = new PerformanceCounter("Process", "ID Process", name)) { if (process.Id == counter.RawValue) { return(name); } } } catch (Exception ex) { Util.Logging.Log(ex); } } } } return(null); }
private string getProcessNameById(int processId) { Process process = Process.GetProcessById(processId); string processName = process.ProcessName; if (!string.IsNullOrEmpty(processName)) { Process[] processes = Process.GetProcessesByName(processName); if (processes.Length > 0) { for (int i = 0; i < processes.Length; i++) { string tempProcessName = i == 0 ? processName : processName + "#" + i.ToString(); if (PerformanceCounterCategory.CounterExists("ID Process", "Process", this.machineName)) { PerformanceCounter idCounter = new PerformanceCounter("Process", "ID Process", tempProcessName, this.machineName); if (processId == idCounter.RawValue) { return(tempProcessName); } } } } } return(string.Empty); }
private static void LazyCreatePerformanceCounter(PerformanceCounterHolder holder, TelemetryData data) { if (holder.Counter != null) { return; } // If counter does not exist then it's probably an installation problem: // * counters have not been created and TelemetrySession.Start did it but OS didn't refresh them yet; // * category already existed but a new version added more counters and old category has not been properly uninstalled. if (!PerformanceCounterCategory.CounterExists(data.Name, data.Category)) { holder.IsDisabled = true; return; } holder.Counter = new PerformanceCounter(data.Category, data.Name, false); if (data.CounterType == TelemetryDataType.AverageCount) { // Base PC name convention: keep in sync with code in WpcTelemetrySessionInstaller holder.Base = new PerformanceCounter(data.Category, data.Name + "Base", false); holder.Counter.RawValue = 0; holder.Base.RawValue = 0; } }
/// <summary> /// The get performance counter value. /// </summary> /// <param name="counterCategory"> /// The counter category. /// </param> /// <param name="counterName"> /// The counter name. /// </param> /// <param name="instanceName"> /// The instance name. /// </param> /// <param name="logger"> /// The logger. /// </param> /// <returns> /// The <see cref="float?"/>. /// </returns> public float?GetPerfCounterValue(PerformanceCounterCategory counterCategory, string counterName, string instanceName, ILog logger) { try { if (counterCategory == null) { logger.ErrorFormat("Performance counter category: '{0}' is not exist.", counterCategory); return(null); } if (counterCategory.CounterExists(counterName)) { var performanceCounter = new PerformanceCounter(counterCategory.CategoryName, counterName, instanceName); using (performanceCounter) { return(performanceCounter.NextValue()); } } else { logger.ErrorFormat("Performance counter {0} {1} is missing on server", counterCategory.CategoryName, counterName); } } catch (Exception exception) { logger.ErrorFormat("Error occurred while getting counter {0} for category {1}. {2}", counterName, counterCategory.CategoryName, exception); } return(null); }
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 void RemoveInstancesAndDispose_MultiInstanceCounters_Works(int numOfCounters) { // Arrange var helpers = new List <CounterHelper <MultiInstanceCategory> >(); for (int i = 0; i < numOfCounters; i++) { var instanceName = GetInstanceName(i); helpers.Add(PerformanceHelper.CreateCounterHelper <MultiInstanceCategory>(instanceName)); } //Act helpers.ForEach(helper => helper.RemoveInstancesAndDispose()); // Assert for (int i = 0; i < numOfCounters; i++) { // The counters still exist Assert.IsTrue(PerformanceCounterCategory.CounterExists(AvgCounterName, CategoryName)); Assert.IsTrue(PerformanceCounterCategory.CounterExists(NumCounterName, CategoryName)); // The instances should NOT Assert.IsFalse( PerformanceCounterCategory.InstanceExists(GetInstanceName(i), CategoryName), string.Format("{0} should not exist anymore", GetInstanceName(i))); var category = PerformanceCounterCategory.GetCategories().First(cat => cat.CategoryName == CategoryName); var instanceNames = category.GetInstanceNames().OrderBy(name => name).ToArray(); Assert.AreEqual(0, instanceNames.Count(), "There should be no instances left"); } }
void InitiatizeCategory() { try { var counters = new[] { ConsumerThreadCount, ReceiveThreadCount, ReceiveRate, PublishRate, SendRate, ReceiveCount, PublishCount, SentCount, ConsumerDuration, ConsumerDurationBase, ReceiveDuration, ReceiveDurationBase, PublishDuration, PublishDurationBase, }; if (!PerformanceCounterCategory.Exists(CategoryName)) { PerformanceCounterCategory.Create( CategoryName, CategoryHelp, PerformanceCounterCategoryType.MultiInstance, new CounterCreationDataCollection(counters.Select(x => (CounterCreationData)x).ToArray())); return; } int missing = counters .Where(counter => !PerformanceCounterCategory.CounterExists(counter.Name, CategoryName)) .Count(); if (missing > 0) { PerformanceCounterCategory.Delete(CategoryName); PerformanceCounterCategory.Create( CategoryName, CategoryHelp, PerformanceCounterCategoryType.MultiInstance, new CounterCreationDataCollection(counters.Select(x => (CounterCreationData)x).ToArray())); } } catch (SecurityException) { //swallow the exception because having these is NOT critical var msg = "Unable to create performance counter category (Category: {0})" + "\nTry running the program in the Administrator role to set these up." + "\n**Hey, this just means you aren't admin or don't have/want perf counter support**" .FormatWith(CategoryName); _log.Warn(msg); } }
void Initialize() { #if !NETCORE try { var counters = Data.Select(x => x.ToCounterCreationData()); if (!PerformanceCounterCategory.Exists(_categoryName)) { CreateCategory(counters); return; } IEnumerable <CounterCreationData> missing = counters.Where(counter => !PerformanceCounterCategory.CounterExists(counter.CounterName, _categoryName)); if (missing.Any()) { PerformanceCounterCategory.Delete(_categoryName); CreateCategory(counters); } } catch (SecurityException exception) { LogContext.Warning?.Log(exception, "Unable to create performance counter category (Category: {Category})" + "\nTry running the program in the Administrator role to set these up." + "\n**Hey, this just means you aren't admin or don't have/want perf counter support**", _categoryName); } #endif }
protected void CreateCounters() { var categoryExists = false; // check if all the perf counters exist - this is the best that can be done with the current API if ((categoryExists = PerformanceCounterCategory.Exists(_categoryName)) && _counterDefinitions.Cast <CounterCreationData>().All(ccd => PerformanceCounterCategory.CounterExists(ccd.CounterName, _categoryName))) { return; } try { if (categoryExists) { PerformanceCounterCategory.Delete(_categoryName); } PerformanceCounterCategory.Create(_categoryName, _categoryHelp, _categoryType, _counterDefinitions); } catch (UnauthorizedAccessException e) { DerivedLogger.Error(e, "Error creating the performance counter category named '{0}'. Ensure the process is running with the necessary privileges.", _categoryName); } catch (SecurityException e) { DerivedLogger.Error(e, "Error creating the performance counter category named '{0}'. Ensure the process is running with the necessary privileges.", _categoryName); } catch (Exception e) { DerivedLogger.Error(e, "Unexpected error creating the performance counter category named '{0}': {1}", _categoryName, e.Message); } }
protected static PerformanceCounter GetPerformanceCounter(string categoryName, string counterName, string instanceName) { const string runCommandMessage = "Run the following command to create it:" + " LinkMe.Framework.Environment.Util.exe /createPerf /i" + @" Tools\Performance\Config\LinkMe.Framework.Tools.Performance.Counters.config"; try { return(new PerformanceCounter(categoryName, counterName, instanceName, false)); } catch (Exception ex) { if (!PerformanceCounterCategory.Exists(categoryName)) { throw new ApplicationException("Performance counter category '" + categoryName + "' does not exist. " + runCommandMessage, ex); } if (!PerformanceCounterCategory.CounterExists(counterName, categoryName)) { throw new ApplicationException("Performance counter '" + counterName + "' in category '" + categoryName + "' does not exist ." + runCommandMessage, ex); } throw new ApplicationException("Failed to get performance counter '" + counterName + "' in category '" + categoryName + "'.", ex); } }
public long GetDatabaseTransactionVersionSizeInBytes() { try { const string categoryName = "Database ==> Instances"; if (PerformanceCounterCategory.Exists(categoryName) == false) { return(-1); } var category = new PerformanceCounterCategory(categoryName); var instances = category.GetInstanceNames(); var ravenInstance = instances.FirstOrDefault(x => x.StartsWith(uniqueRrefix)); const string counterName = "Version Buckets Allocated"; if (ravenInstance == null || !category.CounterExists(counterName)) { return(-2); } using (var counter = new PerformanceCounter(categoryName, counterName, ravenInstance, readOnly: true)) { var value = counter.NextValue(); return((long)(value * TransactionalStorageConfigurator.GetVersionPageSize())); } } catch (Exception e) { if (reportedGetDatabaseTransactionCacheSizeInBytesError == false) { reportedGetDatabaseTransactionCacheSizeInBytesError = true; log.WarnException("Failed to get Version Buckets Allocated value, this error will only be reported once.", e); } return(-3); } }
public static void PerformanceCounterCategory_CounterExists_StaticInvalid() { Assert.Throws <ArgumentNullException>(() => PerformanceCounterCategory.CounterExists(null, "Processor")); Assert.Throws <ArgumentNullException>(() => PerformanceCounterCategory.CounterExists("Interrupts/sec", null)); Assert.Throws <ArgumentException>(() => PerformanceCounterCategory.CounterExists("Interrupts/sec", string.Empty)); Assert.Throws <ArgumentException>(() => PerformanceCounterCategory.CounterExists("Interrupts/sec", "Processor", string.Empty)); }
void Initialize() { try { CounterCreationData[] counters = Data; if (!PerformanceCounterCategory.Exists(_categoryName)) { CreateCategory(counters); return; } IEnumerable <CounterCreationData> missing = counters.Where(counter => !PerformanceCounterCategory.CounterExists(counter.CounterName, _categoryName)); if (missing.Any()) { PerformanceCounterCategory.Delete(_categoryName); CreateCategory(counters); } } catch (SecurityException) { _log.WarnFormat( "Unable to create performance counter category (Category: {0})" + "\nTry running the program in the Administrator role to set these up." + "\n**Hey, this just means you aren't admin or don't have/want perf counter support**", _categoryName); } }
public static long?SafelyGetPerformanceCounter(string categoryName, string counterName, string processName) { try { if (PerformanceCounterCategory.Exists(categoryName) == false) { return(null); } var category = new PerformanceCounterCategory(categoryName); var instances = category.GetInstanceNames(); var ravenInstance = instances.FirstOrDefault(x => x == processName); if (ravenInstance == null || !category.CounterExists(counterName)) { return(null); } using (var counter = new PerformanceCounter(categoryName, counterName, ravenInstance, readOnly: true)) { return(counter.NextSample().RawValue); } } catch (Exception) { //Don't log anything here, it's up to the calling code to decide what to do return(null); } }
public static void Monitor(string categroy, string counter, string instance, EventWaitHandle stopper) { if (!PerformanceCounterCategory.Exists(categroy)) { throw new InvalidOperationException("Categroy does not exist"); } if (!PerformanceCounterCategory.CounterExists(counter, categroy)) { throw new InvalidOperationException("Counter does not exist"); } instance ??= ""; if (instance != "" && !PerformanceCounterCategory.InstanceExists(instance, categroy)) { throw new InvalidOperationException("Instance does not exist"); } var lastValue = 0f; using (var pc = new PerformanceCounter(categroy, counter, instance)) { //每200毫秒轮询一次 while (!stopper.WaitOne(200, false)) { var value = pc.NextValue(); if (System.Math.Abs(value - lastValue) > 0) { Console.WriteLine(value); lastValue = value; } } } }
public PerfCounter(string category, string name) { Category = category; Name = name; bool catExists = PerformanceCounterCategory.Exists(Category); bool exists = catExists && PerformanceCounterCategory.CounterExists(name, Category); if (!exists) { #if DEBUG if (!catExists) { MessageBox.Show($"Failed to find Category {Category}"); } else { MessageBox.Show($"Failed to find Counter {name}"); } #endif return; } PerformanceCounterCategory counterCategory = new PerformanceCounterCategory(Category); string[] names = counterCategory.GetInstanceNames(); m_counter = new PerformanceCounter[names.Length]; for (int i = 0; i < names.Length; i++) { m_counter[i] = new PerformanceCounter(Category, Name, names[i], true); } }
private static void CheckCounters() { try { if (!PerformanceCounterCategory.Exists(PERFORMANCE_COUNTER_CATEGORY_NAME)) { CreateCategory(); } else { foreach (var counter in m_counterNames) { if (!PerformanceCounterCategory.CounterExists(counter.Key, PERFORMANCE_COUNTER_CATEGORY_NAME)) { CreateCategory(); break; } } } m_sipsorceryCategoryReady = true; } catch (Exception excp) { logger.Error("Exception SIPSorceryPerformanceMonitor CheckCounters. " + excp.Message); } }
public static void EnsureCategory(IICPerformanceCountersAttribute categoryAttr, IEnumerable <IICPerformanceCounter> counters) { bool needCreate; if (!PerformanceCounterCategory.Exists(categoryAttr.CategoryName)) { needCreate = true; } else { needCreate = false; foreach (IICPerformanceCounter counter in counters) { if (!PerformanceCounterCategory.CounterExists(counter._rawAttr.CounterName, categoryAttr.CategoryName)) { needCreate = true; break; } } if (needCreate) { PerformanceCounterCategory.Delete(categoryAttr.CategoryName); } } if (needCreate) { CreateCategory(categoryAttr, counters); } }
private static bool PerformanceCounterExistsAndHasAllCounters(string instanceName) { if (PerformanceCounterCategory.Exists(CategoryName) == false) { return(false); } foreach (var counter in CounterProperties) { if (PerformanceCounterCategory.CounterExists(counter.Name, CategoryName) == false) { PerformanceCounterCategory.Delete(CategoryName); return(false); } try { new PerformanceCounter(CategoryName, counter.Name, instanceName, readOnly: true).Close(); } catch (InvalidOperationException) { PerformanceCounterCategory.Delete(CategoryName); return(false); } } return(true); }
private void CreateIfNotExists(IEnumerable <CounterCreationData> totalCounterCreationDatas) { // размножаем счетчики по именам операций var multipliedBtOperations = operations .SelectMany(op => totalCounterCreationDatas.Select(ccd => new CounterCreationData() { CounterHelp = ccd.CounterHelp, CounterName = PerOperationCounter.CounterNameForOperation(ccd.CounterName, op), CounterType = ccd.CounterType })).Union(totalCounterCreationDatas).ToArray(); // если ес ть хотя бы один не зарегистрированный счетчик if (!PerformanceCounterCategory.Exists(MidwayClientCategoryName) || multipliedBtOperations.Any( d => !PerformanceCounterCategory.CounterExists(d.CounterName, MidwayClientCategoryName))) { // удаляем категорию и регистрируем сноваt if (PerformanceCounterCategory.Exists(MidwayClientCategoryName)) { PerformanceCounterCategory.Delete(MidwayClientCategoryName); } var counterCreationDataCollection = new CounterCreationDataCollection(multipliedBtOperations.ToArray()); PerformanceCounterCategory.Create(MidwayClientCategoryName, "Счетчики производительности веб-сервиса обмена", PerformanceCounterCategoryType.SingleInstance, counterCreationDataCollection); } }
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)); }
public static PerformanceCounter GetCounter(string category, string counter, string name) { if (PerformanceCounterCategory.Exists(category) && PerformanceCounterCategory.CounterExists(counter, category)) { return(new PerformanceCounter(category, counter, name, true)); } return(null); }
/// <summary> /// Determines whether the item is installed. /// </summary> /// <param name="installationContext">The installation context.</param> /// <returns> /// Value indicating whether the item is installed or null if it is not possible to determine. /// </returns> public bool?IsInstalled(InstallationContext installationContext) { if (!PerformanceCounterCategory.Exists(CategoryName)) { return(false); } return(PerformanceCounterCategory.CounterExists(CounterName, CategoryName)); }
private PerformanceSampler(string instanceName) { if (_disablePerformanceSampling) { return; } if (PerformanceCounterCategory.CounterExists(PerformanceCounters.TotalMessagesReceived, PerformanceCounters.CategoryName) && PerformanceCounterCategory.CounterExists(PerformanceCounters.MessagesReceivedRate, PerformanceCounters.CategoryName)) { this.totalMessagesReceived = new PerformanceCounter(PerformanceCounters.CategoryName, PerformanceCounters.TotalMessagesReceived, instanceName, true); this.messagesReceivedRate = new PerformanceCounter(PerformanceCounters.CategoryName, PerformanceCounters.MessagesReceivedRate, instanceName, true); } else { logger.WarnFormat("The Performance Counters {0} and {1} are not installed. This sampler will be disabled.", PerformanceCounters.TotalMessagesReceived, PerformanceCounters.MessagesReceivedRate); _disableMessagesReceived = true; } if (PerformanceCounterCategory.CounterExists(PerformanceCounters.TotalMessagesSent, PerformanceCounters.CategoryName) && PerformanceCounterCategory.CounterExists(PerformanceCounters.MessagesSentRate, PerformanceCounters.CategoryName)) { this.totalMessagesSent = new PerformanceCounter(PerformanceCounters.CategoryName, PerformanceCounters.TotalMessagesSent, instanceName, true); this.messagesSentRate = new PerformanceCounter(PerformanceCounters.CategoryName, PerformanceCounters.MessagesSentRate, instanceName, true); } else { logger.WarnFormat("The Performance Counters {0} and {1} are not installed. This sampler will be disabled.", PerformanceCounters.TotalMessagesSent, PerformanceCounters.MessagesSentRate); _disableMessagesSent = true; } if (PerformanceCounterCategory.CounterExists(PerformanceCounters.TotalMessageFailures, PerformanceCounters.CategoryName) && PerformanceCounterCategory.CounterExists(PerformanceCounters.MessageFailureRate, PerformanceCounters.CategoryName)) { this.totalMessageFailures = new PerformanceCounter(PerformanceCounters.CategoryName, PerformanceCounters.TotalMessageFailures, instanceName, true); this.messageFailureRate = new PerformanceCounter(PerformanceCounters.CategoryName, PerformanceCounters.MessageFailureRate, instanceName, true); } else { logger.WarnFormat("The Performance Counters {0} and {1} are not installed. This sampler will be disabled.", PerformanceCounters.TotalMessageFailures, PerformanceCounters.MessageFailureRate); _disableMessageFailure = true; } if (PerformanceCounterCategory.CounterExists(PerformanceCounters.AvgMessageHandlingDuration, PerformanceCounters.CategoryName) && PerformanceCounterCategory.CounterExists(PerformanceCounters.AvgMessageHandlingDurationBase, PerformanceCounters.CategoryName)) { this.avgMessageHandlingDuration = new PerformanceCounter(PerformanceCounters.CategoryName, PerformanceCounters.AvgMessageHandlingDuration, instanceName, true); this.avgMessageHandlingDurationBase = new PerformanceCounter(PerformanceCounters.CategoryName, PerformanceCounters.AvgMessageHandlingDurationBase, instanceName, true); } else { logger.WarnFormat("The Performance Counters {0} and {1} are not installed. This sampler will be disabled.", PerformanceCounters.AvgMessageHandlingDuration, PerformanceCounters.AvgMessageHandlingDurationBase); _disableAvgMessageHandling = true; } }