protected override void OnEventWritten(EventWrittenEventArgs eventData) { if (eventData.EventName != "EventCounters" || eventData.Payload == null || eventData.Payload.Count == 0) { return; // not a counter with readable data } if (eventData.Payload[0] == null || eventData.Payload[0] is not IDictionary <string, object> ) { return; // expecting a dictionary } var payload = (IDictionary <string, object>)eventData.Payload[0] !; if (!payload.TryGetValue("CounterType", out var counterType) || !payload.TryGetValue("Name", out var name)) { return; // payload is missing counter type and name } if (!(counterType is string counterTypeString) || string.IsNullOrWhiteSpace(counterTypeString)) { return; // invalid counter type } if (!(name is string nameString) || string.IsNullOrWhiteSpace(nameString)) { return; // invalid name } var metricName = $"{eventData.EventSource.Name}.{nameString}"; if (!_registry.TryGetMetric(new MetricName(typeof(MetricsHost), metricName), out var metric)) { throw new InvalidOperationException( $"EventSource '{eventData.EventSource.Name}' was registered for metrics, but no metric found for '{metricName}'"); } if (!(metric is CounterMetric counter)) { throw new InvalidOperationException( $"EventSource '{eventData.EventSource.Name}' was registered for metrics, but metric '{metricName}' is not a counter."); } if (counterTypeString.Equals("Sum") && payload.TryGetValue("Increment", out var increment)) { if (increment is double value) { if (value == 0d) { return; } if (value < 0d) { counter.Decrement(Convert.ToInt64(value)); } else { counter.Increment(Convert.ToInt64(value)); } } else { throw new InvalidOperationException("unexpected increment type " + increment.GetType()); } } }