in Amazon.KinesisTap.Windows/PerformanceCounterSource.cs [236:297]
public virtual void RefreshCounters()
{
var newCounters = new HashSet<MetricKey>();
foreach (var categoryInfo in _categoryInfos)
{
try
{
// add the counters available in the category to the set
AddCategoryCountersToSet(categoryInfo, newCounters);
}
catch (Exception ex)
{
_context.Logger?.LogWarning(0, ex, $"Could not add counters for category {categoryInfo.CategoryName}.");
}
}
// now we run a 'diff' between the new and the current set of counters
// first we check to see what counters are stale
var stale = new List<MetricKey>();
foreach (var counterKey in _metricCounters.Keys)
{
if (!newCounters.Contains(counterKey))
{
stale.Add(counterKey);
}
}
// remove the stale counters
foreach (var staleCounter in stale)
{
_metricCounters[staleCounter].Dispose();
_metricCounters.Remove(staleCounter);
_context.Logger?.LogInformation($"Removed performance counter: category {staleCounter.Category} instance {staleCounter.Id} counter {staleCounter.Name}.");
}
// add in the new counters
foreach (var newCounterKey in newCounters)
{
if (_metricCounters.ContainsKey(newCounterKey))
{
continue;
}
try
{
var counter = new PerformanceCounter(newCounterKey.Category, newCounterKey.Name, newCounterKey.Id);
_metricCounters[newCounterKey] = counter;
var instancePhrase = string.IsNullOrEmpty(counter.InstanceName)
? string.Empty
: $" instance {counter.InstanceName}";
_context.Logger?.LogInformation($"Added performance counter: category {counter.CategoryName}{instancePhrase} counter {counter.CounterName}.");
}
catch (Exception ex) when (ex is InvalidOperationException || ex is ArgumentNullException || ex is UnauthorizedAccessException || ex is Win32Exception)
{
// catch the exception caused by the performance counter constructor
// this should not happen, because the counter key is obtained from the system's API
// however we want to make sure that failure in creating one counter does not impact others.
_context.Logger?.LogError(0, ex,
$"Error adding counter: category {newCounterKey.Category} instance {newCounterKey.Id} counter {newCounterKey.Name}.");
}
}
}