private DataPoint AssembleDataPoint(CounterConfig counter, ManagementObject result) { var instance = counter.Instance; var counterName = counter.Counter; string applicationPoolName = string.Empty; var friendlyName = counter.Name; var resultName = GetPropertyString(result, "Name"); var value = Convert.ToSingle(result[counterName]); var processId = GetPropertyInt(result, "IDProcess"); if (processId.HasValue) { applicationPoolName = GetAppPoolByProcessId(processId); } // Prefer in order of ApplicationName, ResultName, Instance or just use empty string. var instanceName = !string.IsNullOrWhiteSpace(applicationPoolName) ? applicationPoolName : !string.IsNullOrWhiteSpace(resultName) ? resultName : !string.IsNullOrWhiteSpace(instance) ? instance : string.Empty; Log.DebugFormat("{0}/{1} ({2}): {3}", friendlyName, instanceName, applicationPoolName, value); if (!string.IsNullOrWhiteSpace(instanceName)) { friendlyName = string.Concat(friendlyName, " - ", instanceName); } return new DataPoint(friendlyName, value, DateTime.UtcNow, _instanceId); }
private static string BuildQueryString(CounterConfig counter) { var providerName = counter.Provider; var categoryName = counter.Category; var instance = counter.Instance; var counterName = counter.Counter; if (string.IsNullOrWhiteSpace(providerName) || string.IsNullOrWhiteSpace(categoryName) || string.IsNullOrWhiteSpace(counterName)) { Log.ErrorFormat("Invalid Counter. Provider={0}, Category={1}, Name={2}", providerName, categoryName, counterName); return null; } var whereClause = string.Empty; if (!string.IsNullOrWhiteSpace(counter.Instance)) { whereClause = string.Format(" Where Name Like '{0}'", instance); } var queryString = string.Format("Select * from Win32_PerfFormattedData_{0}_{1}{2}", providerName, categoryName, whereClause); return queryString; }
private List<DataPoint> GetDataPoints(CounterConfig counter) { if (counter == null) return null; var queryString = BuildQueryString(counter); if (queryString == null) return null; var search = new ManagementObjectSearcher(Scope, new ObjectQuery(queryString)); var dataPoints = new List<DataPoint>(); try { var queryResults = search.Get(); var results = queryResults.Cast<ManagementObject>(); try { // ReSharper disable once PossibleMultipleEnumeration Log.DebugFormat("Retrieved {0} results from '{1}'", results.Count(), queryString); } catch (ManagementException ex) { Log.Warn(string.Format("Unable to read results of '{0}'", queryString), ex); return null; } // ReSharper disable once PossibleMultipleEnumeration foreach (var result in results) { try { dataPoints.Add(AssembleDataPoint(counter, result)); } catch (Exception ex) { Log.Error(string.Format("Exception while retrieving metric results. Query: {0}", queryString), ex); } } } catch (Exception ex) { Log.Error(string.Format("Exception while polling metrics. Query: {0}", queryString), ex); } return dataPoints; }