教程:通过 IoT 中心设置和使用指标和日志Tutorial: Set up and use metrics and logs with an IoT hub

可以使用 Azure Monitor 为 IoT 中心收集指标和日志,这些指标和日志可以帮助你监视解决方案的操作,并在问题发生时进行故障排除。You can use Azure Monitor to collect metrics and logs for your IoT hub that can help you monitor the operation of your solution and troubleshoot problems when they occur. 在本文中,你将了解如何基于指标创建图表,如何创建触发指标的警报,如何将 IoT 中心操作和错误发送到 Azure Monitor 日志,以及如何检查日志以发现错误。In this article, you'll see how to create charts based on metrics, how to create alerts that trigger on metrics, how to send IoT Hub operations and errors to Azure Monitor Logs, and how to check the logs for errors.

本教程使用 .NET Send 遥测快速入门中的 Azure 示例,将消息发送到 IoT 中心。This tutorial uses the Azure sample from the .NET Send telemetry quickstart to send messages to the IoT hub. 你可以始终使用设备或其他示例来发送消息,但可能需要相应地修改一些步骤。You can always use a device or another sample to send messages, but you may have to modify a few steps accordingly.

在开始本教程之前,熟悉 Azure Monitor 概念可能会有所帮助。Some familiarity with Azure Monitor concepts might be helpful before you begin this tutorial. 有关详细信息,请参阅监视 IoT 中心To learn more, see Monitor IoT Hub. 若要了解 IoT 中心发出的指标和资源日志的详细信息,请参阅监视数据参考To learn more about the metrics and resource logs emitted by IoT Hub, see Monitoring data reference.

将在本教程中执行以下任务:In this tutorial, you perform the following tasks:

  • 使用 Azure CLI 创建 IoT 中心,注册模拟设备,并创建 Log Analytics 工作区。Use Azure CLI to create an IoT hub, register a simulated device, and create a Log Analytics workspace.
  • 将 IoT 中心连接和设备遥测资源日志发送到 Log Analytics 工作区中的 Azure Monitor 日志。Send IoT Hub connections and device telemetry resource logs to Azure Monitor Logs in the Log Analytics workspace.
  • 使用指标资源管理器根据选定的指标创建图表,并将其固定到仪表板。Use metric explorer to create a chart based on selected metrics and pin it to your dashboard.
  • 创建指标警报,使你可在重要条件满足时得到电子邮件通知。Create metric alerts so you can be notified by email when important conditions occur.
  • 下载并运行一个应用,该应用模拟 IoT 设备将消息发送到 IoT 中心的情形。Download and run an app that simulates an IoT device sending messages to the IoT hub.
  • 在你的条件满足时,查看警报。View the alerts when your conditions occur.
  • 查看仪表板上的指标图表。View the metrics chart on your dashboard.
  • 查看 Azure Monitor 日志中的 IoT 中心错误和操作。View IoT Hub errors and operations in Azure Monitor Logs.

先决条件Prerequisites

  • Azure 订阅。An Azure subscription. 如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.
  • 开发计算机上需要有 .NET Core SDK 2.1 或更高版本。You need the .NET Core SDK 2.1 or greater on your development machine. 可以从 .NET 为多个平台下载 .NET Core SDK。You can download the .NET Core SDK for multiple platforms from .NET.

    可以使用以下命令验证开发计算机上 C# 的当前版本:You can verify the current version of C# on your development machine using the following command:

    dotnet --version
    
  • 一个能够接收邮件的电子邮件帐户。An email account capable of receiving mail.

  • 确保已在防火墙中打开端口 8883。Make sure that port 8883 is open in your firewall. 本教程中的设备示例使用 MQTT 协议,该协议通过端口 8883 进行通信。The device sample in this tutorial uses MQTT protocol, which communicates over port 8883. 在某些公司和教育网络环境中,此端口可能被阻止。This port may be blocked in some corporate and educational network environments. 有关解决此问题的更多信息和方法,请参阅连接到 IoT 中心(MQTT)For more information and ways to work around this issue, see Connecting to IoT Hub (MQTT).

  • 如果需要,请安装 Azure CLI 来运行 CLI 参考命令。If you prefer, install the Azure CLI to run CLI reference commands.
    • 如果使用的是本地安装,请使用 az login 命令登录到 Azure CLI。If you're using a local installation, sign in to the Azure CLI by using the az login command. 若要完成身份验证过程,请遵循终端中显示的步骤。To finish the authentication process, follow the steps displayed in your terminal. 有关其他登录选项,请参阅登录 Azure CLIFor additional sign-in options, see Sign in with the Azure CLI.
    • 出现提示时,请在首次使用时安装 Azure CLI 扩展。When you're prompted, install Azure CLI extensions on first use. 有关扩展详细信息,请参阅使用 Azure CLI 的扩展For more information about extensions, see Use extensions with the Azure CLI.
    • 运行 az version 以查找安装的版本和依赖库。Run az version to find the version and dependent libraries that are installed. 若要升级到最新版本,请运行 az upgradeTo upgrade to the latest version, run az upgrade.

设置资源Set up resources

若要完成本教程,需要 IoT 中心、Log Analytics 工作区和模拟 IoT 设备。For this tutorial, you need an IoT hub, a Log Analytics workspace, and a simulated IoT device. 这些资源可以通过 Azure CLI 或 Azure PowerShell 创建。These resources can be created using Azure CLI or Azure PowerShell. 为所有资源使用相同的资源组和位置。Use the same resource group and location for all of the resources. 完成教程后,可以通过删除资源组一步删除所有内容。Then, when you've finished the tutorial, you can remove everything in one step by deleting the resource group.

下面是必需步骤。Here are the required steps.

  1. 创建资源组Create a resource group.

  2. 创建 IoT 中心。Create an IoT hub.

  3. 创建 Log Analytics 工作区。Create a Log Analytics workspace.

  4. 为发送消息到 IoT 中心的模拟设备注册设备标识。Register a device identity for the simulated device that sends messages to your IoT hub. 保存要用于配置模拟设备的设备连接字符串。Save the device connection string to use to configure the simulated device.

使用 Azure CLI 设置资源Set up resources using Azure CLI

复制此脚本并将其粘贴。Copy and paste this script. 在已登录的情况下,该脚本会逐行运行。Assuming you are already logged in, it runs the script one line at a time. 新资源在资源组 ContosoResources 中创建。The new resources are created in the resource group ContosoResources.

某些资源的名称在整个 Azure 中必须是唯一的。The name for some resources must be unique across Azure. 脚本使用 $RANDOM 函数生成一个随机值,并将其存储在变量中。The script generates a random value with the $RANDOM function and stores it in a variable. 对于这些资源,脚本将此随机值追加到资源的基名称,使资源名称唯一。For these resources, the script appends this random value to a base name for the resource, making the resource name unique.

每个订阅只允许有一个免费的 IoT 中心。Only one free IoT hub is permitted per subscription. 如果订阅中已经有免费的 IoT 中心,请在运行脚本之前将其删除,或者修改脚本以使用免费的 IoT 中心或一个采用标准层或基本层的 IoT 中心。If you already have a free IoT hub in your subscription, either delete it before running the script or modify the script to use your free IoT hub or an IoT Hub that uses the standard or basic tier.

该脚本打印 IoT 中心的名称、Log Analytics 工作区的名称以及它所注册的设备的连接字符串。The script prints the name of the IoT hub, the name of the Log Analytics workspace, and the connection string for the device it registers. 请务必将这些记录下来,因为在本文后面的部分中将需要使用它们。Be sure to note these down as you'll need them later in this article.


# This is the IOT Extension for Azure CLI.
# You only need to install this the first time.
# You need it to create the device identity. 
az extension add --name azure-iot

# Set the values for the resource names that don't have to be globally unique.
# The resources that have to have unique names are named in the script below
#   with a random number concatenated to the name so you can probably just
#   run this script, and it will work with no conflicts.
location=chinaeast
resourceGroup=ContosoResources
iotDeviceName=Contoso-Test-Device 
randomValue=$RANDOM

# Create the resource group to be used
#   for all the resources for this tutorial.
az group create --name $resourceGroup \
    --location $location

# The IoT hub name must be globally unique, so add a random number to the end.
iotHubName=ContosoTestHub$randomValue
echo "IoT hub name = " $iotHubName

# Create the IoT hub in the Free tier. Partition count must be 2.
az iot hub create --name $iotHubName \
    --resource-group $resourceGroup \
    --partition-count 2 \
    --sku F1 --location $location

# The Log Analytics workspace name must be globally unique, so add a random number to the end.
workspaceName=contoso-la-workspace$randomValue
echo "Log Analytics workspace name = " $workspaceName


# Create the Log Analytics workspace
az monitor log-analytics workspace create --resource-group $resourceGroup \
    --workspace-name $workspaceName --location $location

# Create the IoT device identity to be used for testing.
az iot hub device-identity create --device-id $iotDeviceName \
    --hub-name $iotHubName 

# Retrieve the primary connection string for the device identity, then copy it to
#   Notepad. You need this to run the device simulation during the testing phase.
az iot hub device-identity show-connection-string --device-id $iotDeviceName \
    --hub-name $iotHubName

备注

创建设备标识时,可能会出现以下错误:找不到 IoT 中心 ContosoTestHub 的策略 iothubowner 的密钥。 若要修正此错误,请更新 Azure CLI IoT 扩展,然后再次运行脚本中的最后两个命令。To fix this error, update the Azure CLI IoT Extension and then run the last two commands in the script again.

下面是用于更新扩展的命令。Here is the command to update the extension.

az extension update --name azure-iot

收集连接和设备遥测的日志Collect logs for connections and device telemetry

IoT 中心为几种操作类别发出资源日志;但是,若要查看这些日志,必须创建诊断设置以将其发送到目标。IoT Hub emits resource logs for several categories of operation; however, for you to view these logs you must create a diagnostic setting to send them to a destination. 其中一个目标是 Azure Monitor 日志,这些日志在 Log Analytics 工作区中收集。One such destination is Azure Monitor Logs, which are collected in a Log Analytics workspace. IoT 中心资源日志分为不同的类别。IoT Hub resource logs are grouped into different categories. 你可以在诊断设置中选择要发送到 Azure Monitor 日志的类别。You can select which categories you want sent to Azure Monitor Logs in the diagnostic setting. 在本文中,我们将收集与连接和设备遥测有关的操作和错误的日志。In this article, we'll collect logs for operations and errors that occur having to do with connections and device telemetry. 有关 IoT 中心支持的类别的完整列表,请参阅 IoT 中心资源日志For a full list of the categories supported for IoT Hub, see IoT Hub resource logs.

若要创建诊断设置以将 IoT 中心资源日志发送到 Azure Monitor 日志,请执行以下步骤:To create a diagnostic setting to send IoT Hub resource logs to Azure Monitor Logs, follow these steps:

  1. 首先,如果还没有进入门户的中心,请选择“资源组”,然后选择资源组 ContosoResources。First, if you're not already on your hub in the portal, select Resource groups and select the resource group ContosoResources. 从所显示的资源列表中选择你的 IoT 中心。Select your IoT hub from the list of resources displayed.

  2. 找到 IoT 中心边栏选项卡中的“监视”部分。 Look for the Monitoring section in the IoT Hub blade. 选择“诊断设置”。Select Diagnostic settings. 然后选择“添加诊断设置”。Then select Add diagnostic setting.

    突出显示“监视”部分的“诊断设置”的屏幕截图。

  3. 在“诊断设置”窗格中,为设置指定一个描述性名称,例如“将连接和遥测发送到日志”。On the Diagnostics setting pane, give your setting a descriptive name, such as "Send connections and telemetry to logs".

  4. 在“类别详细信息”下,选择“连接”和“设备遥测” 。Under Category details, select Connections and Device Telemetry.

  5. 在“目标详细信息”下,选择“发送到日志分析”,然后使用 Log Analytics 工作区选取器来选择之前记下的工作区 。Under Destination details, select Send to Log Analytics, then use the Log Analytics workspace picker to select the workspace you noted previously. 完成后,诊断设置应类似于以下屏幕截图:When you're finished, the diagnostic setting should look similar to the following screenshot:

    显示最终诊断日志设置的屏幕截图。

  6. 选择“保存”,保存这些设置。Select Save to save the settings. 关闭“诊断设置”窗格。Close the Diagnostics setting pane. 可以在诊断设置列表中看到你的新设置。You can see your new setting in the list of diagnostic settings.

设置指标Set up metrics

现在,我们将使用指标资源管理器创建一个图表,显示所要跟踪的指标。将此图表固定到 Azure 门户中的默认仪表板。Now we'll use metrics explorer to create a chart that displays metrics you want to track. You'll pin this chart to your default dashboard in the Azure portal.

  1. 在 IoT 中心的左窗格中,选择“监视”部分中的“指标” 。On the left pane of your IoT hub, select Metrics in the Monitoring section.

  2. 在屏幕顶部,选择“过去 24 小时(自动)”。At the top of the screen, select Last 24 hours (Automatic). 在显示的下拉列表中,选择“过去 4 小时”作为“时间范围”,并将“时间粒度”设置为“1 分钟”,然后对“时间显示形式”选择“本地” 。In the dropdown that appears, select Last 4 hours for Time range, set Time granularity to 1 minute, and select Local for Show time as. 选择“应用”,保存这些设置。Select Apply to save these settings. 设置现在应显示“本地时间:过去 4 小时(1 分钟)”。The setting should now say Local Time: Last 4 hours (1 minute).

    显示指标时间设置的屏幕截图。

  3. 在图表上,显示了一个范围为 IoT 中心的部分指标设置。On the chart, there is a partial metric setting displayed scoped to your IoT hub. 保留“范围”和“指标命名空间”值的默认值 。Leave the Scope and Metric Namespace values at their defaults. 选择“指标”设置并键入“遥测”,然后从下拉列表中选择“发送的遥测消息数” 。Select the Metric setting and type "Telemetry", then select Telemetry messages sent from the dropdown. “聚合”将自动设置为“Sum” 。Aggregation will be automatically set to Sum. 请注意,图表的标题也会更改。Notice that the title of your chart also changes.

    显示向图表添加“发送的遥测消息数”指标的屏幕截图。

  4. 现在选择“添加指标”,向图表添加另一个指标。Now select Add metric to add another metric to the chart. 在“指标”下,选择“已使用的消息总数”。 Under Metric, select Total number of messages used. “聚合”将自动设置为“Avg” 。同样,请注意,图表的标题已更改为包含此指标。Aggregation will be automatically set to Avg. Notice again that the title of the chart has changed to include this metric.

    现在,屏幕会显示针对“发送的遥测消息数”的最小化指标,以及针对“已使用的消息总数”的新指标。 Now your screen shows the minimized metric for Telemetry messages sent, plus the new metric for Total number of messages used.

    显示向图表添加“使用的消息总数”指标的屏幕截图。

  5. 在图表的右上角,选择“固定到仪表板”。In the upper right of the chart, select Pin to dashboard.

    突出显示“固定到仪表板”按钮的屏幕截图。

  6. 在“固定到仪表板”窗格中,选择“现有”选项卡 。选择“专用”,然后从仪表板下拉列表中选择“仪表板” 。On the Pin to dashboard pane, select the Existing tab. Select Private and then select Dashboard from the Dashboard dropdown. 最后,选择“固定”将图表固定到 Azure 门户中的默认仪表板。Finally, select Pin to pin the chart to your default dashboard in Azure portal. 如果你不将图表固定到仪表板,则在退出指标资源管理器时,设置不会保留。If you don't pin your chart to a dashboard, your settings are not retained when you exit metric explorer.

    显示“固定到仪表板”设置的屏幕截图。

设置指标警报Set up metric alerts

现在,我们将设置根据“发送的遥测消息数”和“使用的消息总数”这两个指标触发的警报 。Now we'll set up alerts to trigger on two metrics Telemetry messages sent and Total number of messages used.

“发送的遥测消息数”是跟踪消息吞吐量和避免受到限制的良好监视指标。Telemetry messages sent is a good metric to monitor to track message throughput and avoid being throttled. 对于免费层中的 IoT 中心,带宽限制限制为 100 条消息/秒。对于单个设备,我们无法达到这种吞吐量,因此我们将设置在 5 分钟内消息数超过 1000 条时触发的警报。For an IoT Hub in the free tier, the throttling limit is 100 messages/sec. With a single device, we won't be able to achieve that kind of throughput, so instead, we'll set up the alert to trigger if the number of messages exceeds 1000 in a 5-minute period. 在生产中,可以根据 IoT 中心的层、版本和单元数量将该信号设置为更重要的值。In production, you can set the signal to a more significant value based on the tier, edition, and number of units of your IoT hub.

“使用的消息总数”跟踪每天使用的消息数。Total number of messages used tracks the daily number of messages used. 此指标每天在 00:00 UTC 重置。This metric resets every day at 00:00 UTC. 如果你超出了每日配额,超过了某个阈值,IoT 中心将不再接受消息。If you exceed your daily quota past a certain threshold, your IoT Hub will no longer accept messages. 对于免费层中的 IoT 中心,每日消息配额为 8000。For an IoT Hub in the free tier, the daily message quota is 8000. 我们将设置警报,使它在消息总数超过 4000 条(即配额的 50%)时触发。We'll set up the alert to trigger if the total number of messages exceeds 4000, 50% of the quota. 实际上,你可能会将此百分比设置为更高的值。In practice, you'd probably set this percentage to a higher value. 每日配额值取决于 IoT 中心的层、版本和单元数。The daily quota value is dependent on the tier, edition, and number of units of your IoT hub.

有关 IoT 中心配额和限制的更多信息,请参阅配额和限制For more information about quota and throttling limits with IoT Hub, see Quotas and throttling.

设置指标警报:To set up metric alerts:

  1. 在 Azure 门户中转到 IoT 中心。Go to your IoT hub in Azure portal.

  2. 在“监视”下,选择“警报” 。Under Monitoring, select Alerts. 然后选择“新建警报规则”。Then select New alert rule. 随即打开“创建警报规则”窗格。The Create alert rule pane opens.

    显示“创建警报规则”窗格的屏幕截图。

    在“创建警报规则”窗格中,有四个部分:On the Create alert rule pane, there are four sections:

    • “范围”已经设置为 IoT 中心,因此我们将不讨论此部分。Scope is already set to your IoT hub, so we'll leave this section alone.
    • “条件”设置触发警报的信号和条件。Condition sets the signal and conditions that will trigger the alert.
    • “操作”配置警报触发时发生的情况。Actions configures what happens when the alert triggers.
    • “警报规则详细信息”用于设置警报的名称和说明。Alert rule details lets you set a name and a description for the alert.
  3. 首先,配置触发警报的条件。First configure the condition that the alert will trigger on.

    1. 在“条件”下方,选择“选择条件” 。Under Condition, select Select condition. 在“配置信号逻辑”窗格中,在搜索框中键入“遥测”,然后选择“发送的遥测消息数” 。On the Configure signal logic pane, type "telemetry" in the search box and select Telemetry messages sent.

      显示选择指标的屏幕截图。

    2. 在“配置信号逻辑”窗格中,在“警报逻辑”下设置或确认以下字段(可以忽略图表) :On the Configure signal logic pane, set or confirm the following fields under Alert logic (you can ignore the chart):

      阈值:静态。Threshold: Static.

      操作员:大于。Operator: Greater than.

      聚合类型:总计。Aggregation type: Total.

      阈值:1000。Threshold value: 1000.

      聚合粒度(时间范围) :5分钟。Aggregation granularity (Period): 5 minutes.

      评估频率:每隔 1 分钟Frequency of evaluation: Every 1 Minute

      显示警报条件设置的屏幕截图。

      这些设置将信号设置为合计 5 分钟内的消息数。These settings set the signal to total the number of messages over a period of 5 minutes. 此总数将每分钟评估一次,如果前 5 分钟的总计超过 1000 条消息,则将触发警报。This total will be evaluated every minute, and, if the total for the preceding 5 minutes exceeds 1000 messages, the alert will trigger.

      选择“完成”保存信号逻辑。Select Done to save the signal logic.

  4. 现在,配置警报的操作。Now configure the action for the alert.

    1. 返回“创建警报规则”窗格,在“操作”下,选择“选择操作组” 。Back on the Create alert rule pane, under Actions, select Select action group. 在“选择要附加到此警报规则的操作组”窗格上,选择“创建操作组” 。On the Select an action group to attach to this alert rule pane, select Create action group.

    2. 在“创建操作组”窗格上的“基本信息”选项卡下,为操作组指定一个名称和一个显示名称 。Under the Basics tab on the Create action group pane, give your action group a name and a display name.

      显示“创建操作组”窗格的“基本”选项卡的屏幕截图。

    3. 选择“通知”选项卡。对于“通知类型”,从下拉列表中选择“电子邮件/短信/推送/语音” 。Select the Notifications tab. For Notification type, select Email/SMS message/Push/Voice from the dropdown. 随即打开“电子邮件/短信/推送/语音”窗格。The Email/SMS message/Push/Voice pane opens.

    4. 在“电子邮件/短信/推送/语音”窗格中,选择电子邮件并输入你的电子邮件地址,然后选择“确定” 。On the Email/SMS message/Push/Voice pane, select email and enter your email address, then select OK.

      显示电子邮件地址设置的屏幕截图。

    5. 返回“通知”窗格,输入通知的名称。Back on the Notifications pane, enter a name for the notification.

      显示已完成的“通知”窗格的屏幕截图。

    6. (可选)如果选择“操作”选项卡,然后选择“操作类型”下拉列表,则可以看到可以通过警报触发的操作类型 。(Optional) If you select the Actions tab, and then select the Action type dropdown, you can see the kinds of actions that you can trigger with an alert. 对于本文,我们将仅使用通知,因此你可以忽略此选项卡下的设置。For this article, we'll only use notifications, so you can ignore the settings under this tab.

      显示“操作”窗格中可用操作类型的屏幕截图。

    7. 选择“查看并创建”选项卡,验证设置,然后选择“创建” 。Select the Review and Create tab, verify your settings, and select Create.

      显示“查看并创建”窗格的屏幕截图。

    8. 返回“创建警报规则”窗格,请注意,新操作组已添加到警报的操作中。Back on the Create alert rule pane, notice that your new action group has been added to the actions for the alert.

  5. 最后配置警报规则详细信息并保存警报规则。Finally configure the alert rule details and save the alert rule.

    1. 在“创建警报规则”窗格的“警报规则详细信息”下,输入警报的名称和说明;例如,“5 分钟内超过 1000 条消息时发出警报”。On the Create alert rule pane, under Alert rule details, enter a name and a description for your alert; for example, "Alert if more than 1000 messages over 5 minutes". 确保选中了“创建时启用警报规则”。Make sure that Enable alert rule upon creation is checked. 已完成的警报规则将类似于此屏幕截图。Your completed alert rule will look similar to this screenshot.

      显示已完成的“创建警报规则”窗格的屏幕截图。

    2. 选择“创建警报规则”,保存新规则。Select Create alert rule to save your new rule.

  6. 现在针对“已使用的消息总数”设置另一警报。 Now set up another alert for the Total number of messages used. 如果你希望在使用的消息数接近 IoT 中心的每日配额时(此时,IoT 中心将开始拒绝消息)发送警报,则此指标非常有用。This metric is useful if you want to send an alert when the number of messages used is approaching the daily quota for the IoT hub, at which point, the IoT hub will start rejecting messages. 按照之前所做的步骤操作,但有以下不同之处。Follow the steps you did before, with the following differences.

    • 对于“配置信号逻辑”窗格上的信号,选择“使用的消息总数” 。For the signal on the Configure signal logic pane, select Total number of messages used.

    • 在“配置信号逻辑”窗格中,设置或确认以下字段(可以忽略图表):On the Configure signal logic pane, set or confirm the following fields (you can ignore the chart):

      阈值:静态。Threshold: Static.

      操作员:大于。Operator: Greater than.

      聚合类型:最大值。Aggregation type: Maximum.

      阈值:4000。Threshold value: 4000.

      聚合粒度(时间范围) :1 分钟。Aggregation granularity (Period): 1 minute.

      评估频率:每隔 1 分钟Frequency of evaluation: Every 1 Minute

      这些设置将信号设置为当消息数量达到 4000 条时触发。These settings set the signal to fire when the number of messages reaches 4000. 该指标每分钟计算一次。The metric is evaluated every minute.

    • 为警报规则指定操作时,只需选择先前创建的操作组。When you specify the action for your alert rule, just select the action group you created previously.

    • 对于警报详细信息,请选择与以前不同的名称和描述。For the alert details, choose a different name and description than you did previously.

  7. 选择 IoT 中心左侧窗格中“监视”下的“警报” 。Select Alerts, under Monitoring on the left pane of your IoT hub. 现在,在“警报”窗格顶部的菜单上选择“管理警报规则” 。Now select Manage alert rules on the menu at the top of the Alerts pane. 此时将打开“规则”窗格。The Rules pane opens. 现在应会看到两个警报:You should now see your two alerts:

    显示包含新警报规则的“规则”窗格的屏幕截图。

  8. 关闭“规则”窗格。Close the Rules pane.

通过这些设置,当 5 分钟内发送的消息数超过 1000 条时,以及当使用的消息总数超过 4000 条(免费层中 IoT 中心每日配额的 50%)时,警报将被触发并且你会收到电子邮件通知。With these settings, an alert will trigger and you'll get an email notification when more than 1000 messages are sent within a 5-minute time span and also when the total number of messages used exceeds 4000 (50% of the daily quota for an IoT hub in the free tier).

运行模拟设备应用Run the simulated device app

设置资源部分,你注册了一个设备标识,用于模拟使用 IoT 设备。In the Set up resources section, you registered a device identity to use to simulate using an IoT device. 在本部分,下载一个 .NET 控制台应用(用于模拟向 IoT 中心发送设备到云消息的设备),将其配置为将这些消息发送到 IoT 中心,然后运行它。In this section, you download a .NET console app that simulates a device that sends device-to-cloud messages to an IoT Hub, configure it to send these messages to your IoT hub, and then run it.

重要

IoT 中心最多需要 10 分钟才能完全配置和启用警报。Alerts can take up to 10 minutes to be fully configured and enabled by IoT Hub. 在配置上一个警报和运行模拟设备应用之间,至少等待 10 分钟。Wait at least 10 minutes between the time you configure your last alert and running the simulated device app.

下载 IoT 设备模拟的解决方案。Download the solution for the IoT Device Simulation. 可通过此链接下载包含多个应用程序的存储库;要查找的内容位于 iot-hub/Quickstarts/simulated-device/ 中。This link downloads a repo with several applications in it; the one you are looking for is in iot-hub/Quickstarts/simulated-device/.

  1. 在本地终端窗口中,导航到解决方案的根文件夹。In a local terminal window, navigate to the root folder of the solution. 然后导航到 iot-hub\Quickstarts\simulated-device 文件夹。Then navigate to the iot-hub\Quickstarts\simulated-device folder.

  2. 在所选文本编辑器中打开 SimulatedDevice.cs 文件。Open the SimulatedDevice.cs file in a text editor of your choice.

    1. s_connectionString 变量的值替换为你运行脚本以设置资源时记下的设备连接字符串。Replace the value of the s_connectionString variable with the device connection string you noted when you ran the script to set up resources.

    2. SendDeviceToCloudMessagesAsync 方法中,将 Task.Delay 从 1000 更改为 1,这样就会将发送消息的间隔时间从 1 秒更改为 0.001 秒。In the SendDeviceToCloudMessagesAsync method, change the Task.Delay from 1000 to 1, which reduces the amount of time between sending messages from 1 second to 0.001 seconds. 缩短此延迟会增加发送的消息数。Shortening this delay increases the number of messages sent. (你可能不会获得每秒 100 条消息的消息速率。)(You will likely not get a message rate of 100 messages per second.)

      await Task.Delay(1);
      
    3. 将更改保存到 SimulatedDevice.cs。Save your changes to SimulatedDevice.cs.

  3. 在本地终端窗口中,运行以下命令以安装模拟设备应用程序所需的包:In the local terminal window, run the following command to install the required packages for the simulated device application:

    dotnet restore
    
  4. 在本地终端窗口中,运行以下命令,生成并运行模拟设备应用程序:In the local terminal window, run the following command to build and run the simulated device application:

    dotnet run
    

    以下屏幕截图显示了模拟设备应用程序将遥测数据发送到 IoT 中心后的输出:The following screenshot shows the output as the simulated device application sends telemetry to your IoT hub:

    显示模拟设备输出的屏幕截图。

让应用程序运行至少 10-15 分钟。Let the application run for at least 10-15 minutes. 理想情况下,让它运行到停止发送消息为止(大约 20-30 分钟)。Ideally, let it run until it stops sending messages (about 20-30 minutes). 如果你超过了 IoT 中心的每日消息配额,并且它已停止接受更多消息时,就会发生这种情况。This will happen when you've exceeded the daily message quota for your IoT hub, and it has stopped accepting any more messages.

备注

如果设备应用在停止发送消息后长时间保持运行状态,则可能会出现异常。If you leave the device app running for an extended period after it stops sending messages, you may get an exception. 你可以安全地忽略此异常并关闭应用窗口。You can safely ignore this exception and close the app window.

查看仪表板上的指标图表View metrics chart on your dashboard

  1. 在 Azure 门户的左上角,打开门户菜单,然后选择“仪表板”。In the upper-left corner of Azure portal, open the portal menu, and then select Dashboard.

    如何选择仪表板的屏幕截图。

  2. 找到先前固定的图表,然后单击图表数据外部磁贴上的任何位置以展开它。Find the chart you pinned earlier and click anywhere on the tile outside of the chart data to expand it. 图表上显示发送的遥测消息数和使用的消息总数。It shows the telemetry messages sent and the total number of messages used on the chart. 最新的数字显示在图表的底部。The most recent numbers appear at the bottom of the chart. 可以在图表中移动光标以查看特定时间的指标值。You can move the cursor in the chart to see the metric values for specific times. 你还可以在图表顶部更改时间值和粒度,将数据缩小或扩展到感兴趣的时间段。You can also change the time value and granularity at the top of the chart to narrow down or expand the data to a time period of interest.

    显示指标图表的屏幕截图。

    在此场景下,模拟设备的消息吞吐量不足以导致 IoT 中心限制其消息数。In this scenario, the simulated device's message throughput isn't large enough to cause IoT Hub to throttle its messages. 在实际涉及限制的场景中,你可能会看到发送的遥测消息数在有限的时间内超过了 IoT 中心的限制。In a scenario that actually involves throttling, you may see telemetry messages sent exceed the throttle limit for your IoT hub for a limited time. 这是为了适应突发流量。This is to accommodate burst traffic. 有关详细信息,请参阅流量调整For details, see traffic shaping.

查看警报View the alerts

如果发送的消息数超出了你在警报规则中设置的限制,你会开始收到电子邮件警报。When the number of messages sent exceeds the limits you set in your alert rules, you start getting e-mail alerts.

若要查看是否有任何活动警报,请选择 IoT 中心左侧窗格中“监视”下的“警报” 。To see if there are any active alerts, select Alerts under Monitoring on the left pane of your IoT hub. “警报”窗格显示在指定时间范围内按严重性排序的已触发警报数。The Alerts pane shows the number of alerts that have fired sorted by severity for the specified time range.

显示警报摘要的屏幕截图。

选择严重性为 Sev 3 的行。Select the row for severity Sev 3. “所有警报”窗格打开并列出已触发的 Sev 3 警报。The All Alerts pane opens and lists the Sev 3 alerts that have fired.

显示“所有警报”窗格的屏幕截图。

选择其中一个警报以查看警报详细信息。Select one of the alerts to see the alert details.

显示警报详细信息的屏幕截图。

检查收件箱中来自 Microsoft Azure 的电子邮件。Check your inbox for emails from Microsoft Azure. 主题行将描述触发的警报。The subject line will describe the alert that was triggered. 例如“Azure:已激活,严重性:3,5 分钟内超过 1000 条消息时发出警报”For example, Azure: Activated Severity: 3 Alert if more than 1000 messages over 5 minutes. 正文将与下图类似:The body will look similar to the following image:

电子邮件的屏幕截图,显示警报已触发。

查看 Azure Monitor 日志View Azure Monitor Logs

收集连接和设备遥测的日志部分中,你创建了一个诊断设置,将 IoT 中心发出的连接和设备遥测操作资源日志发送到 Azure Monitor 日志。In the Collect logs for connections and device telemetry section, you created a diagnostic setting to send resource logs emitted by your IoT hub for connection and device telemetry operations to Azure Monitor Logs. 在本部分中,针对 Azure Monitor 日志运行 Kusto 查询,观察发生的任何错误。In this section, you'll run a Kusto query against Azure Monitor Logs to observe any errors that occurred.

  1. 在 Azure 门户中 IoT 中心左窗格的“监视”下,选择“日志” 。Under Monitoring in the left pane of your IoT hub in Azure portal, select Logs. 关闭初始的“查询”窗口(如果它打开)。Close the initial Queries window if it opens.

  2. 在“新建查询”窗格中,选择“查询”选项卡,然后展开“IoT 中心”以查看默认查询的列表 。On the New Query pane, select the Queries tab and then expand IoT Hub to see the list of default queries.

    IoT 中心默认查询的屏幕截图。

  3. 选择“错误摘要”查询。Select the Error summary query. 该查询将显示在“查询编辑器”窗格中。The query appears in the Query editor pane. 在编辑器窗格中选择“运行”并观察查询结果。Select Run in the editor pane and observe the query results. 展开其中一行可查看详细信息。Expand one of the rows to see details.

    “错误摘要”查询返回的日志的屏幕截图。

    备注

    如果没有看到任何错误,请尝试运行“最近连接的设备”查询。If you don't see any errors, try running the Recently connected devices query. 这应该会针对模拟设备返回一行。This should return a row for the simulated device.

清理资源Clean up resources

若要删除在本教程中创建的所有资源,请删除资源组。To remove all of the resources you've created in this tutorial, delete the resource group. 此操作会一并删除组中包含的所有资源。This action deletes all resources contained within the group. 在此示例下,它会删除 IoT 中心、Log Analytics 工作区和资源组本身。In this case, it removes the IoT hub, the Log Analytics workspace, and the resource group itself. 如果已将指标图表固定到仪表板,则需手动删除这些图表,方法是:单击每个图表右上角的三个点,然后选择“删除”。If you have pinned metrics charts to the dashboard, you'll have to remove them manually by clicking on the three dots in the upper right-hand corner of each chart and selecting Remove. 删除图表后,请务必保存更改。Be sure to save your changes after doing deleting the charts.

若要删除资源组,请使用 az group delete 命令。To remove the resource group, use the az group delete command.

az group delete --name ContosoResources

后续步骤Next steps

本教程介绍了如何执行以下任务,以便使用 IoT 中心指标和日志:In this tutorial, you learned how to use IoT Hub metrics and logs by performing the following tasks:

  • 使用 Azure CLI 创建 IoT 中心,注册模拟设备,并创建 Log Analytics 工作区。Use Azure CLI to create an IoT hub, register a simulated device, and create a Log Analytics workspace.
  • 将 IoT 中心连接和设备遥测资源日志发送到 Log Analytics 工作区中的 Azure Monitor 日志。Send IoT Hub connections and device telemetry resource logs to Azure Monitor Logs in the Log Analytics workspace.
  • 使用指标资源管理器根据选定的指标创建图表,并将其固定到仪表板。Use metric explorer to create a chart based on selected metrics and pin it to your dashboard.
  • 创建指标警报,使你可在重要条件满足时得到电子邮件通知。Create metric alerts so you can be notified by email when important conditions occur.
  • 下载并运行一个应用,该应用模拟 IoT 设备将消息发送到 IoT 中心的情形。Download and run an app that simulates an IoT device sending messages to the IoT hub.
  • 在你的条件满足时,查看警报。View the alerts when your conditions occur.
  • 查看仪表板上的指标图表。View the metrics chart on your dashboard.
  • 查看 Azure Monitor 日志中的 IoT 中心错误和操作。View IoT Hub errors and operations in Azure Monitor Logs.

转到下一教程,了解如何管理 IoT 设备的状态。Advance to the next tutorial to learn how to manage the state of an IoT device.