如何访问NetCore应用程序内部的Npgsql计数器



我在Npgsql repo中偶然发现了一个问题,即可以收集计数器数据:https://github.com/npgsql/npgsql/issues/1725

有没有关于如何访问这些计数器的样本或信息?

参考以下文章https://github.com/dotnet/diagnostics/blob/master/documentation/design-docs/eventcounters.md,我尝试过以下操作,但没有运气,也没有事件计数器上的数据(如idle-connections等(仅CommandStartCommandEnd

class Program
{
static void Main(string[] args)
{
var listener = new TestEventListener();
while (true)
{
using var cn = new Npgsql.NpgsqlConnection("...");  cn.Open();
var cmd = new NpgsqlCommand("select 1", cn); cmd.ExecuteNonQuery();
}
}
}
class TestEventListener : EventListener
{
private readonly EventLevel level = EventLevel.Verbose;
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
Console.WriteLine($"{eventData.EventName}");
if (eventData.EventName.Equals("EventCounters", StringComparison.OrdinalIgnoreCase))
{
for (var i = 0; i < eventData.Payload.Count; i++)
{
if (eventData.Payload[i] is IDictionary<string, object> payload)
{
Console.WriteLine(payload);
}
}
}
}
protected override void OnEventSourceCreated(EventSource eventSource)
{
if (eventSource.Name.Equals("Npgsql"))
{
var refreshInterval = new Dictionary<string, string>()
{
{ "connection-pools", "1" },
{ "idle-connections", "1" },
{ "busy-connections", "1" }
};
EnableEvents(eventSource, level, EventKeywords.None, refreshInterval);
}
base.OnEventSourceCreated(eventSource);
}
}

我看到这些计数器通过运行dotnet counters monitor Npgsql -p <pid>来工作,但如何在代码中做到这一点?

答案是遵循documentm并提供文档中指定的实际参数:

Dictionary<string, string> refreshInterval = new Dictionary<string, string>()
{
{ "EventCounterIntervalSec", "1" }
};

相关内容

  • 没有找到相关文章

最新更新