如何使用适用于 Azure 服务总线的 .NET SDK 在 C# 中从服务总线主题及其订阅中读取死信计数?

Sam*_*han 2 c# azure-monitoring azure-functions asp.net-core-3.1

Azure Monitor 为服务总线提供了许多指标,例如 \xe2\x80\x9c 传入、传出、活动\xe2\x80\x9d 消息\n服务总线矩阵为您提供消息总数以及何时尝试查看该指标的详细信息 \ xe2\x80\x9cDeadlettedMessages\xe2\x80\x9d,我可以通过 \xe2\x80\x9cEntityName\xe2\x80\x9d 获取计数,它是队列或主题,但不是订阅级别指标。

\n

在从主题及其订阅中获取所有死信和其他消息计数时,我遇到了挑战。\n我花了近 4-5 小时来解决上述问题。

\n

我希望,下面的答案可能对监控服务总线有所帮助

\n

Sam*_*han 6

Here is the sample code for the same.

[FunctionName("ServiceBusMonitor")]
        public async Task Run([TimerTrigger("0 */1 * * * *")] TimerInfo myTimer, ILogger log)
        {
            try
            {
                var client = new ServiceBusAdministrationClient(_configuration.GetValue<string>("ServiceBusConnectionString"));
                var topics = client.GetTopicsAsync()?.GetAsyncEnumerator();
                while (await topics.MoveNextAsync())
                {
                    TopicProperties topicProperties = topics.Current;
                    var subscriptions = client.GetSubscriptionsAsync(topicProperties.Name)?.GetAsyncEnumerator();
                    log.LogInformation($"{topicProperties.Name}");

                    var subscriptionRuntimePropertiesAsync = client.GetSubscriptionsRuntimePropertiesAsync(topicProperties.Name)?.GetAsyncEnumerator();
                    while (await subscriptionRuntimePropertiesAsync.MoveNextAsync())
                    {
                        var subscriptionRuntimeProperties = subscriptionRuntimePropertiesAsync.Current;
                        Console.WriteLine($"Topic Name {subscriptionRuntimeProperties.TopicName}, Subscription Name {subscriptionRuntimeProperties.SubscriptionName}");
                        Console.WriteLine($"DeadLetterMessageCount : {subscriptionRuntimeProperties.DeadLetterMessageCount} ActiveMessageCount : {subscriptionRuntimeProperties.ActiveMessageCount} TotalMessageCount : {subscriptionRuntimeProperties.TotalMessageCount} " );
//You can log subscriptionRuntimeProperties in Application insight and use the for the monitor
                    }
                    Console.WriteLine("-----------");
                }

                log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
            }
            catch (Exception ex)
            {
                log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now} {ex.Message}");

            }
        }
Run Code Online (Sandbox Code Playgroud)