Created
June 16, 2023 13:46
-
-
Save dustinsoftware/95185ba38985837e46c047c1bf5e740b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Diagnostics.Tracing; | |
namespace WebApplication1; | |
/// <summary> | |
/// Subscribes to the current request counter as it is updated, once per second. | |
/// Follows the simple event listener pattern here: | |
/// https://learn.microsoft.com/en-us/dotnet/core/diagnostics/event-counters | |
/// </summary> | |
public class HostingEventSourceListener : EventListener, IHostingEventSourceListener | |
{ | |
private int? _currentRequests; | |
public int? CurrentRequests => _currentRequests; | |
protected override void OnEventSourceCreated(EventSource source) | |
{ | |
// https://github.com/dotnet/aspnetcore/blob/be51b1aa73343e45a1d00afd436abad794f471fb/src/Hosting/Hosting/src/Internal/HostingEventSource.cs | |
if (!source.Name.Equals("Microsoft.AspNetCore.Hosting")) | |
{ | |
return; | |
} | |
EnableEvents(source, EventLevel.Verbose, EventKeywords.All, new Dictionary<string, string>() | |
{ | |
["EventCounterIntervalSec"] = "1" | |
}!); | |
} | |
protected override void OnEventWritten(EventWrittenEventArgs eventData) | |
{ | |
if (eventData.EventName != "EventCounters") | |
{ | |
return; | |
} | |
for (int i = 0; i < eventData.Payload?.Count; ++ i) | |
{ | |
if (eventData.Payload[i] is IDictionary<string, object> eventPayload) | |
{ | |
// https://learn.microsoft.com/en-us/dotnet/core/diagnostics/available-counters | |
// https://github.com/dotnet/aspnetcore/blob/be51b1aa73343e45a1d00afd436abad794f471fb/src/Hosting/Hosting/src/Internal/HostingEventSource.cs | |
if (eventPayload.TryGetValue("Name", out var parsedName) && (string) parsedName == "current-requests") | |
{ | |
// Min, Max, Mean will all have the same values for current-requests. | |
eventPayload.TryGetValue("Min", out var currentRequests); | |
_currentRequests = ((int?) ((double?) currentRequests)); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment