如何在Azure Function内检索IotHub使用信息

问题描述 投票:0回答:1

是否有 API 或 SDK 允许我们检索 IoT 中心的使用信息,例如发送的消息总量、每日使用情况等。下面是我所掌握的信息图片。 Azure函数的函数工作线程运行时是:dotnet-isolated

c# azure azure-functions azure-iot-hub azure-functions-isolated
1个回答
0
投票

根据文档,我们可以通过收集和分析各种类型的日志来监控Azure IoT Hub,包括平台指标、资源日志、连接、设备遥测、C2D命令、活动日志等

  • 转到 Azure IoT 中心并在 IoT 中心设置诊断设置,以收集平台指标、资源日志和活动日志并将其路由到 Azure Monitor 日志、Azure 存储或事件中心终结点。
  • 配置诊断设置以根据您的监控要求指定要收集的日志类别。

enter image description here


using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.EventHubs;

namespace FunctionApp
{
    public static class TimerFunction
    {
        private static EventHubClient? eventHubClient; // Nullable eventHubClient
        private static readonly string connectionString = "EventHubconnectionString";
        private static readonly string eventHubName = "eventHubName";

        [Function("TimerFunction")]
        public static async Task RunAsync([TimerTrigger("0 */1 * * * *")] TimerInfo myTimer, FunctionContext context)
        {
            var logger = context.GetLogger("TimerFunction");

            logger.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            // Build the connection string with Event Hub name
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(connectionString)
            {
                EntityPath = eventHubName
            };
            string eventHubConnectionString = connectionStringBuilder.ToString();

            // Create Event Hub client
            eventHubClient = EventHubClient.CreateFromConnectionString(eventHubConnectionString);

            var runtimeInformation = await eventHubClient.GetRuntimeInformationAsync();
            var d2cPartitions = runtimeInformation.PartitionIds;
            CancellationTokenSource cts = new CancellationTokenSource();
            var tasks = new List<Task>();
            foreach (string partition in d2cPartitions)
            {
                tasks.Add(ReceiveMessagesFromDeviceAsync(partition, cts.Token, logger));
            }

            await Task.Delay(60000); // Ensure the function runs for 1 minute

            logger.LogInformation("Exiting...");
            cts.Cancel();
            await Task.WhenAll(tasks);
            await eventHubClient.CloseAsync();
        }

        private static async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct, ILogger logger)
        {
            var eventHubReceiver = eventHubClient!.CreateReceiver("$Default", partition, EventPosition.FromEnqueuedTime(DateTime.Now));
            while (!ct.IsCancellationRequested)
            {
                try
                {
                    var eventDataBatch = await eventHubReceiver.ReceiveAsync(100); // Maximum number of events to receive
                    if (eventDataBatch != null)
                    {
                        foreach (var eventData in eventDataBatch)
                        {
                            string data = Encoding.UTF8.GetString(eventData.Body.Array);
                            logger.LogInformation($"Message received. Partition: {partition} Data: '{data}'");
                            var message = Newtonsoft.Json.JsonConvert.DeserializeObject<AzureMonitorDiagnosticLog>(data);
                            // Process the message...
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError($"Error receiving message from partition {partition}: {ex.Message}");
                }
            }
            await eventHubReceiver.CloseAsync();
        }
    }

    class AzureMonitorDiagnosticLog
    {
        public string? time { get; set; }
        public string? resourceId { get; set; }
        public string? operationName { get; set; }
        public string? category { get; set; }
        public string? level { get; set; }
        public string? resultType { get; set; }
        public string? resultDescription { get; set; }
        public string? durationMs { get; set; }
        public string? callerIpAddress { get; set; }
        public string? correlationId { get; set; }
        public string? identity { get; set; }
        public string? location { get; set; }
        public Dictionary<string, string>? properties { get; set; }
    }
}

enter image description here

另一种方法是在 Azure IoT Hub 中使用 alert 规则。 enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.