IoT 中心操作监视IoT Hub operations monitoring

IoT 中心操作监视可让你实时监视其 IoT 中心上的操作状态。IoT Hub operations monitoring enables you to monitor the status of operations on your IoT hub in real time. IoT 中心可跨多个类别的操作跟踪事件。IoT Hub tracks events across several categories of operations. 可选择将一个或多个类别的事件发送到 IoT 中心终结点进行处理。You can opt into sending events from one or more categories to an endpoint of your IoT hub for processing. 可以监视数据中是否有错误,或根据数据模式设置更复杂的处理行为。You can monitor the data for errors or set up more complex processing based on data patterns.

Note

IoT 中心操作监视功能已弃用,并已于 2019 年 3 月 10 日从 IoT 中心中删除IoT Hub operations monitoring is deprecated and has been removed from IoT Hub on March 10, 2019. 若要了解如何监视 IoT 中心的操作和运行状况,请参阅监视 Azure IoT 中心运行状况并快速诊断问题For monitoring the operations and health of IoT Hub, see Monitor the health of Azure IoT Hub and diagnose problems quickly. 若要详细了解弃用日程表,请参阅利用 Azure Monitor 和 Azure 资源运行状况监视 Azure IoT 解决方案For more information about the deprecation timeline, see Monitor your Azure IoT solutions with Azure Monitor and Azure Resource Health.

IoT 中心监视 6 种类别的事件:IoT Hub monitors six categories of events:

  • 设备标识操作Device identity operations
  • 设备遥测Device telemetry
  • 云到设备的消息Cloud-to-device messages
  • 连接Connections
  • 文件上传File uploads
  • 消息路由Message routing

Important

IoT 中心操作监视不保证事件传送的可靠性和有序性。IoT Hub operations monitoring does not guarantee reliable or ordered delivery of events. 某些事件可能丢失或出现传送顺序混乱,具体取决于 IoT 中心的基础结构。Depending on IoT Hub underlying infrastructure, some events might be lost or delivered out of order. 使用操作监视基于错误信号生成警报,如连接尝试失败或与特定设备的连接频繁断开。Use operations monitoring to generate alerts based on error signals such as failed connection attempts, or high-frequency disconnections for specific devices. 不应依赖操作监视事件为设备状态创建一致存储区,例如,跟踪设备已连接或断开连接状态的存储区。You should not rely on operations monitoring events to create a consistent store for device state, e.g. a store tracking connected or disconnected state of a device.

如何启用操作监视How to enable operations monitoring

  1. 创建 IoT 中心。Create an IoT hub. 有关如何创建 IoT 中心的说明,请参阅入门指南。You can find instructions on how to create an IoT hub in the Get Started guide.

  2. 打开 IoT 中心的边栏选项卡。Open the blade of your IoT hub. 在此处单击“操作监视”。From there, click Operations monitoring.

    访问门户中的操作监视配置

  3. 选择要监视的监视类别,并单击“保存” 。Select the monitoring categories you wish to monitor, and then click Save. 可以从“监视设置”中所列的与事件中心兼容的终结点读取事件。The events are available for reading from the Event Hub-compatible endpoint listed in Monitoring settings. IoT 中心终结点称为 messages/operationsmonitoringeventsThe IoT Hub endpoint is called messages/operationsmonitoringevents.

    在 IoT 中心配置操作监视

Note

为“连接”类别选择“详细”监视会导致 IoT 中心生成额外的诊断消息。Selecting Verbose monitoring for the Connections category causes IoT Hub to generate additional diagnostics messages. 对于所有其他类别,“详细”设置会更改 IoT 中心在每个错误消息中包含的信息数量。For all other categories, the Verbose setting changes the quantity of information IoT Hub includes in each error message.

事件类别及其用法Event categories and how to use them

每种操作监视类别跟踪与 IoT 中心之间进行的不同类型的交互,每一种监视类别都有一个架构用于定义如何构建该类别的事件。Each operations monitoring category tracks a different type of interaction with IoT Hub, and each monitoring category has a schema that defines how events in that category are structured.

设备标识操作Device identity operations

设备标识操作类别跟踪你尝试在其 IoT 中心的标识注册表中创建、更新或删除条目时所发生的错误。The device identity operations category tracks errors that occur when you attempt to create, update, or delete an entry in your IoT hub's identity registry. 预配方案就很适合跟踪此类别。Tracking this category is useful for provisioning scenarios.

{
    "time": "UTC timestamp",
    "operationName": "create",
    "category": "DeviceIdentityOperations",
    "level": "Error",
    "statusCode": 4XX,
    "statusDescription": "MessageDescription",
    "deviceId": "device-ID",
    "durationMs": 1234,
    "userAgent": "userAgent",
    "sharedAccessPolicy": "accessPolicy"
}

设备遥测Device telemetry

设备遥测类别跟踪在 IoT 中心发生且与遥测管道相关的错误。The device telemetry category tracks errors that occur at the IoT hub and are related to the telemetry pipeline. 此类别包括发送遥测事件(例如限制)和接收遥测事件(例如未经授权的读取者)时发生的错误。This category includes errors that occur when sending telemetry events (such as throttling) and receiving telemetry events (such as unauthorized reader). 此类别无法捕捉设备本身运行的代码所造成的错误。This category cannot catch errors caused by code running on the device itself.

{
    "messageSizeInBytes": 1234,
    "batching": 0,
    "protocol": "Amqp",
    "authType": "{\"scope\":\"device\",\"type\":\"sas\",\"issuer\":\"iothub\"}",
    "time": "UTC timestamp",
    "operationName": "ingress",
    "category": "DeviceTelemetry",
    "level": "Error",
    "statusCode": 4XX,
    "statusType": 4XX001,
    "statusDescription": "MessageDescription",
    "deviceId": "device-ID",
    "EventProcessedUtcTime": "UTC timestamp",
    "PartitionId": 1,
    "EventEnqueuedUtcTime": "UTC timestamp"
}

云到设备的命令Cloud-to-device commands

云到设备的命令类别跟踪在 IoT 中心发生且与云到设备的消息管道相关的错误。The cloud-to-device commands category tracks errors that occur at the IoT hub and are related to the cloud-to-device message pipeline. 此类别包括下述情况下发生的错误:发送云到设备的消息(例如未经授权的发送者)、接收云到设备的消息(例如超过传递计数),以及接收云到设备的消息反馈(例如反馈已过期)。This category includes errors that occur when sending cloud-to-device messages (such as unauthorized sender), receiving cloud-to-device messages (such as delivery count exceeded), and receiving cloud-to-device message feedback (such as feedback expired). 此类别不捕捉未正确处理云到设备的消息但却将其成功传递的设备所发生的错误。This category does not catch errors from a device that improperly handles a cloud-to-device message if the cloud-to-device message was delivered successfully.

{
    "messageSizeInBytes": 1234,
    "authType": "{\"scope\":\"hub\",\"type\":\"sas\",\"issuer\":\"iothub\"}",
    "deliveryAcknowledgement": 0,
    "protocol": "Amqp",
    "time": " UTC timestamp",
    "operationName": "ingress",
    "category": "C2DCommands",
    "level": "Error",
    "statusCode": 4XX,
    "statusType": 4XX001,
    "statusDescription": "MessageDescription",
    "deviceId": "device-ID",
    "EventProcessedUtcTime": "UTC timestamp",
    "PartitionId": 1,
    "EventEnqueuedUtcTime": "UTC timestamp"
}

连接Connections

连接类别跟踪设备与 IoT 中心连接或断开连接时发生的错误。The connections category tracks errors that occur when devices connect or disconnect from an IoT hub. 若要识别未经授权的连接尝试,以及在连接质量不佳的区域中的设备断开连接时进行跟踪,就很适合跟踪此类别。Tracking this category is useful for identifying unauthorized connection attempts and for tracking when a connection is lost for devices in areas of poor connectivity.

{
    "durationMs": 1234,
    "authType": "{\"scope\":\"hub\",\"type\":\"sas\",\"issuer\":\"iothub\"}",
    "protocol": "Amqp",
    "time": " UTC timestamp",
    "operationName": "deviceConnect",
    "category": "Connections",
    "level": "Error",
    "statusCode": 4XX,
    "statusType": 4XX001,
    "statusDescription": "MessageDescription",
    "deviceId": "device-ID"
}

文件上传File uploads

文件上传类别跟踪在 IoT 中心发生且与文件上传功能相关的错误。The file upload category tracks errors that occur at the IoT hub and are related to file upload functionality. 此类别包括:This category includes:

  • SAS URI 发生的错误,例如它在设备就上传完毕通知中心之前到期。Errors that occur with the SAS URI, such as when it expires before a device notifies the hub of a completed upload.
  • 设备报告的失败上传。Failed uploads reported by the device.
  • 创建 IoT 中心通知消息期间在存储中找不到文件时发生的错误。Errors that occur when a file is not found in storage during IoT Hub notification message creation.

此类别不能捕获在设备将文件上传到存储时直接发生的错误。This category cannot catch errors that directly occur while the device is uploading a file to storage.

{
    "authType": "{\"scope\":\"hub\",\"type\":\"sas\",\"issuer\":\"iothub\"}",
    "protocol": "HTTP",
    "time": " UTC timestamp",
    "operationName": "ingress",
    "category": "fileUpload",
    "level": "Error",
    "statusCode": 4XX,
    "statusType": 4XX001,
    "statusDescription": "MessageDescription",
    "deviceId": "device-ID",
    "blobUri": "http//bloburi.com",
    "durationMs": 1234
}

消息路由Message routing

消息路由类别跟踪消息路由评估期间发生的错误以及 IoT 中心感知到的终结点运行状况。The message routing category tracks errors that occur during message route evaluation and endpoint health as perceived by IoT Hub. 此类别包括以下事件:规则评估为“未定义”、IoT 中心将终结点标记为“已停用”,以及从终结点中收到的任何其他错误。This category includes events such as when a rule evaluates to "undefined", when IoT Hub marks an endpoint as dead, and any other errors received from an endpoint. 此类别不包含有关消息本身的特定错误(如设备限制错误),这些错误在“设备遥测”类别下报告。This category does not include specific errors about the messages themselves (such as device throttling errors), which are reported under the "device telemetry" category.

{
    "messageSizeInBytes": 1234,
    "time": "UTC timestamp",
    "operationName": "ingress",
    "category": "routes",
    "level": "Error",
    "deviceId": "device-ID",
    "messageId": "ID of message",
    "routeName": "myroute",
    "endpointName": "myendpoint",
    "details": "ExternalEndpointDisabled"
}

连接到监视终结点Connect to the monitoring endpoint

IoT 中心上的监视终结点是与事件中心兼容的终结点。The monitoring endpoint on your IoT hub is an Event Hub-compatible endpoint. 可使用任何适用于事件中心的机制从此终结点读取监视消息。You can use any mechanism that works with Event Hubs to read monitoring messages from this endpoint. 以下示例创建的基本读取器不适用于高吞吐量部署。The following sample creates a basic reader that is not suitable for a high throughput deployment. 若要深入了解如何处理来自事件中心的消息,请参阅事件中心入门教程。For more information about how to process messages from Event Hubs, see the Get Started with Event Hubs tutorial.

若要连接到监视终结点,需要一个连接字符串和终结点名称。To connect to the monitoring endpoint, you need a connection string and the endpoint name. 以下步骤介绍如何在门户中查找必需的值:The following steps show you how to find the necessary values in the portal:

  1. 在门户中,导航到 IoT 中心资源边栏选项卡。In the portal, navigate to your IoT Hub resource blade.

  2. 选择“操作监视” ,记下“与事件中心兼容的名称” 和“与事件中心兼容的终结点” 值:Choose Operations monitoring, and make a note of the Event Hub-compatible name and Event Hub-compatible endpoint values:

    “与事件中心兼容的终结点”值

  3. 选择“共享访问策略” ,并选择“服务” 。Choose Shared access policies, then choose service. 记下“主密钥” 值:Make a note of the Primary key value:

    服务共享访问策略主密钥

以下 C# 代码示例取自 Visual Studio Windows 经典桌面 C# 控制台应用。The following C# code sample is taken from a Visual Studio Windows Classic Desktop C# console app. 该项目安装了 WindowsAzure.ServiceBus NuGet 包。The project has the WindowsAzure.ServiceBus NuGet package installed.

  • 如以下示例所示,将连接字符串占位符替换为使用之前记下的“与事件中心兼容的终结点” 和服务“主密钥” 值的连接字符串:Replace the connection string placeholder with a connection string that uses the Event Hub-compatible endpoint and service Primary key values you noted previously as shown in the following example:

    "Endpoint={your Event Hub-compatible endpoint};SharedAccessKeyName=service;SharedAccessKey={your service primary key value}"
    
  • 将监视终结点名称占位符替换为之前记下的“与事件中心兼容的名称” 值。Replace the monitoring endpoint name placeholder with the Event Hub-compatible name value you noted previously.

class Program
{
    static string connectionString = "{your monitoring endpoint connection string}";
    static string monitoringEndpointName = "{your monitoring endpoint name}";
    static EventHubClient eventHubClient;

    static void Main(string[] args)
    {
        Console.WriteLine("Monitoring. Press Enter key to exit.\n");

        eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, monitoringEndpointName);
        var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;
        CancellationTokenSource cts = new CancellationTokenSource();
        var tasks = new List<Task>();

        foreach (string partition in d2cPartitions)
        {
            tasks.Add(ReceiveMessagesFromDeviceAsync(partition, cts.Token));
        }

        Console.ReadLine();
        Console.WriteLine("Exiting...");
        cts.Cancel();
        Task.WaitAll(tasks.ToArray());
    }

    private static async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct)
    {
        var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);
        while (true)
        {
            if (ct.IsCancellationRequested)
            {
                await eventHubReceiver.CloseAsync();
                break;
            }

            EventData eventData = await eventHubReceiver.ReceiveAsync(new TimeSpan(0,0,10));

            if (eventData != null)
            {
                string data = Encoding.UTF8.GetString(eventData.GetBytes());
                Console.WriteLine("Message received. Partition: {0} Data: '{1}'", partition, data);
            }
        }
    }
}

后续步骤Next steps

若要进一步探索 IoT 中心的功能,请参阅:To further explore the capabilities of IoT Hub, see: