您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

使用 Azure Monitor 创建、查看和管理日志警报Create, view, and manage log alerts using Azure Monitor

概述Overview

本文展示了如何使用 Azure 门户中的警报界面设置日志警报。This article shows you how to set up log alerts using the alerts interface inside Azure portal. 警报规则的定义分为三个部分:Definition of an alert rule is in three parts:

  • 目标:要监视的特定 Azure 资源Target: Specific Azure resource, which is to be monitored
  • 条件:特定的条件或逻辑,出现在“信号”中时,应触发操作Criteria: Specific condition or logic that when seen in Signal, should trigger action
  • 操作:发送到通知接收方 - 电子邮件、短信、Webhook 等的特定调用。Action: Specific call sent to a receiver of a notification - email, SMS, webhook etc.

术语日志警报用来描述警报,其中的信号是 Log Analytics 工作区Application Insights 中的日志查询。The term Log Alerts to describe alerts where signal is log query in a Log Analytics workspace or Application Insights. 日志警报 - 概述中详细了解功能、术语和类型。Learn more about functionality, terminology, and types from Log alerts - Overview.

备注

Log Analytics 工作区中的常见日志数据现在也可以在 Azure Monitor 中的指标平台上查看。Popular log data from a Log Analytics workspace is now also available on the metric platform in Azure Monitor. 有关详细信息,请查看日志的指标警报For details view, Metric Alert for Logs

从 Azure 门户中管理日志警报Managing log alerts from the Azure portal

接下来的详细信息是通过 Azure 门户界面使用日志警报的分步指南。Detailed next is step-by-step guide to using log alerts using the Azure portal interface.

使用 Azure 门户创建日志警报规则Create a log alert rule with the Azure portal

  1. 门户中选择“监视器”,然后在“监视器”部分下选择“警报”。In the portal, select Monitor and under the MONITOR section - choose Alerts.

    监视

  2. 选择“新建警报规则”按钮,在 Azure 中创建新警报。Select the New Alert Rule button to create a new alert in Azure.

    添加警报

  3. 将显示“创建警报”部分,其中包含以下三个部分:定义警报条件、定义警报详细信息和定义操作组。The Create Alert section is shown with the three parts consisting of: Define alert condition, Define alert details, and Define action group.

    创建规则

  4. 定义警报条件:使用“选择资源”链接,然后通过选择资源来指定目标。Define the alert condition by using the Select Resource link and specifying the target by selecting a resource. 进行筛选:选择“订阅”和“资源类型”,以及所需的资源。Filter by choosing the Subscription, Resource Type, and required Resource.

    备注

    创建日志警报 - 在继续操作之前,请验证日志信号是否可用于所选资源。For creating a log alert - verify the log signal is available for the selected resource before you proceed. 选择资源Select resource

  5. 日志警报:确保“资源类型”是分析源(例如 Log Analytics 或 Application Insights),且信号类型为“日志”,并选择相应的“资源”,然后单击“完成”。Log Alerts: Ensure Resource Type is an analytics source like Log Analytics or Application Insights and signal type as Log, then once appropriate resource is chosen, click Done. 接下来,使用“添加条件”按钮查看适用于该资源的信号选项列表,并针对所选日志监视服务(如 Log AnalyticsApplication Insights)从信号列表中选择“自定义日志搜索”选项。Next use the Add criteria button to view list of signal options available for the resource and from the signal list Custom log search option for chosen log monitor service like Log Analytics or Application Insights.

    选择资源 - 自定义日志搜索

    备注

    警报列表可以导入分析查询作为信号类型 - 日志(已保存查询) ,如上图所示。Alerts lists can import analytics query as signal type - Log (Saved Query), as seen in above illustration. 这样用户便能够在 Analytics 中完善查询,然后保存这些查询供将来在警报中使用 - 有关使用保存的查询的详细信息,请参阅在 Azure Monitor中使用日志查询Application Insights Analytics 中的共享查询So users can perfect your query in Analytics and then save them for future use in alerts - more details on using saving query available at using log query in Azure Monitor or shared query in application insights analytics.

  6. 日志警报:选择后,可以在“搜索查询”字段中指定警报查询;如果查询语法不正确,该字段将以红色显示错误。Log Alerts: Once selected, query for alerting can be stated in Search Query field; if the query syntax is incorrect the field displays error in RED. 如果查询语法正确 - 将以图表形式显示指定查询的历史数据供参考,同时显示用于调整时间范围(过去六个小时到过去一周)的选项。If the query syntax is correct - For reference historic data of the stated query is shown as a graph with option to tweak the time window from last six hours to last week.

    配置警报规则

    备注

    仅当查询结果包含时间详细信息时,才能显示历史数据可视化效果。Historical data visualization can only be shown if the query results have time details. 如果查询生成了汇总数据或特定列值 - 则以单一绘图的形式显示相同的数据。If your query results in summarized data or specific column values - same is shown as a singular plot. 对于使用 Application insights 或切换到新的 API 的指标度量类型的日志警报,可以使用“聚合基于”选项指定要使用哪个特定变量对数据进行分组,如下面所示:For Metric Measurement type of Log Alerts using Application Insights or switched to new API, you can specify which specific variable to group the data by using the Aggregate on option; as illustrated in below:

    “聚合基于”选项

  7. 日志警报:打开可视化效果后,可以从显示的“条件”、“聚合”和“阈值”选项中选择“警报逻辑”。Log Alerts: With the visualization in place, Alert Logic can be selected from shown options of Condition, Aggregation and finally Threshold. 最后,使用“时间段”选项在逻辑中指定评估指定条件的时间。Finally specify in the logic, the time to assess for the specified condition, using Period option. 此外,通过选择“频率”来指定运行警报服务的频率。Along with how often Alert should run by selecting Frequency. 日志警报可以基于:Log Alerts can be based on:

    • 记录数目:如果查询返回的记录计数大于或小于提供的值,则创建警报。Number of Records: An alert is created if the count of records returned by the query is either greater than or less than the value provided.
    • 指标度量:如果结果中的每个聚合值超过提供的阈值并且是“分组依据”选定值,则创建警报。Metric Measurement: An alert is created if each aggregate value in the results exceeds the threshold value provided and it is grouped by chosen value. 警报违规数是在选定时间段内超过阈值的次数。The number of breaches for an alert is the number of times the threshold is exceeded in the chosen time period. 可以为结果集中的任何违规组合指定总违规数,或指定连续违规数以要求违规必须在连续采样时发生。You can specify Total breaches for any combination of breaches across the results set or Consecutive breaches to require that the breaches must occur in consecutive samples.
  8. 第二个步骤是在“警报规则名称”字段中定义警报的名称,提供说明用于详细描述该警报的具体信息,并从提供的选项中指定“严重性”值。As the second step, define a name for your alert in the Alert rule name field along with a Description detailing specifics for the alert and Severity value from the options provided. 在 Azure Monitor 发送的所有警报电子邮件、通知或推送内容中,将重用这些详细信息。These details are reused in all alert emails, notifications, or push done by Azure Monitor. 此外,用户可以通过相应地切换“创建后启用规则”选项,选择在创建后立即激活该警报规则。Additionally, user can choose to immediately activate the alert rule on creation by appropriately toggling Enable rule upon creation option.

    在警报详细信息中可以使用一些附加的功能(仅适用于日志警报):For Log Alerts only, some additional functionality is available in Alert details:

    • 抑制警报:如果打开警报规则的阻止功能,则新建警报之后会在定义的时间段内禁用该规则的操作。Suppress Alerts: When you turn on suppression for the alert rule, actions for the rule are disabled for a defined length of time after creating a new alert. 此规则仍在运行中,并且会在满足条件的情况下创建警报记录。The rule is still running and creates alert records provided the criteria is met. 这是为了让你有时间更正问题,而无需运行重复操作。Allowing you time to correct the problem without running duplicate actions.

      对日志警报禁止显示警报

      提示

      指定的禁止显示警报值应大于警报的频率,以确保在没有重叠的情况下停止通知Specify an suppress alert value greater than frequency of alert to ensure notifications are stopped without overlap

  9. 第三个步骤(也是最后一个步骤)是指定在满足警报条件的情况下,是否需要对警报规则触发任何操作组As the third and final step, specify if any Action Group needs to be triggered for the alert rule when alert condition is met. 可以选择包含警报的任何现有操作组,也可以创建新的操作组。You can choose any existing Action Group with alert or create a new Action Group. 根据选定的操作组,触发警报时,Azure 将会:发送电子邮件、发送短信、调用 Webhook、使用 Azure Runbook 进行补救、推送到 ITSM 工具,等等。According to selected Action Group, when alert is trigger Azure will: send email(s), send SMS(s), call Webhook(s), remediate using Azure Runbooks, push to your ITSM tool, etc. 详细了解操作组Learn more about Action Groups.

    备注

    有关通过 Azure 操作组为日志警报触发的 Runbook 有效负载的限制,请参考 Azure 订阅服务限制Refer to the Azure subscription service limits for limits on Runbook payloads triggered for log alerts via Azure action groups

    对于日志警报,提供了一些附加功能用于替代默认操作:For Log Alerts some additional functionality is available to override the default Actions:

    • 电子邮件通知:如果所述操作组中存在一个或多个电子邮件操作,替代通过操作组发送的电子邮件中的电子邮件主题。Email Notification: Overrides e-mail subject in the email, sent via Action Group; if one or more email actions exist in the said Action Group. 无法修改邮件正文,并且该字段不能用于电子邮件地址。You cannot modify the body of the mail and this field is not for email address.

    • 包含自定义 JSON 有效负载:如果所述操作组中存在一个或多个 Webhook 操作,请替代操作组所使用 Webhook JSON。Include custom Json payload: Overrides the webhook JSON used by Action Groups; if one or more webhook actions exist in the said Action Group. 用户可以指定所有在关联的操作组中配置的 Webhook 所使用的 JSON 格式;有关 Webhook 格式的详细信息,请参阅针对日志警报的 Webhook 操作User can specify format of JSON to be used for all webhooks configured in associated Action Group; for more information on webhook formats, see webhook action for Log Alerts. 提供了“查看 Webhook”选项来使用示例 JSON 数据检查格式。View Webhook option is provided to check format using sample JSON data.

      日志警报的操作替代

  10. 如果所有字段有效并且附带绿色的勾选标记,则可以单击“创建警报规则”按钮,在“Azure Monitor - 警报”中创建警报。If all fields are valid and with green tick the create alert rule button can be clicked and an alert is created in Azure Monitor - Alerts. 可以从警报仪表板查看所有警报。All alerts can be viewed from the alerts Dashboard.

    创建规则

    几分钟后,警报将处于活动状态,并按前面所述进行触发。Within a few minutes, the alert is active and triggers as previously described.

用户还可以在 Log Analytics 中完成其分析查询,然后通过“设置警报”按钮推送它来创建警报 - 然后遵循以上教程中从步骤 6 开始的说明。Users can also finalized their analytics query in log analytics and then push it to create an alert via 'Set Alert' button - then following instructions from Step 6 onwards in the above tutorial.

Log Analytics - 设置警报

在 Azure 门户中查看和管理日志警报View & manage log alerts in Azure portal

  1. 门户中选择“监视器”,然后在“监视器”部分下选择“警报”。In the portal, select Monitor and under the MONITOR section - choose Alerts.

  2. 此时将显示警报仪表板 - 其中,所有 Azure 警报(包括日志警报)都显示在单个面板中;包括你的日志警报规则触发时间的每个实例。The Alerts Dashboard is displayed - wherein all Azure Alerts (including log alerts) are displayed in a singular board; including every instance of when your log alert rule has fired. 若要了解详细信息,请参阅警报管理To learn more, see Alert Management.

    备注

    日志警报规则包括由用户提供的基于自定义查询的逻辑,因此不存在已解决状态。Log alert rules comprise of custom query-based logic provided by users and hence without a resolved state. 因此,每当满足日志警报规则中指定的条件时,它都会触发。Due to which every time the conditions specified in the log alert rule are met, it is fired.

  3. 在顶部栏中选择“管理规则”按钮,导航到规则管理部分 - 其中列出了创建的所有警报规则,包括已禁用的警报。Select the Manage rules button on the top bar, to navigate to the rule management section - where all alert rules created are listed; including alerts that have been disabled. 管理警报规则 manage alert rules

使用 Azure 资源模板管理日志警报Managing log alerts using Azure Resource Template

Azure Monitor 中的日志警报与资源类型 Microsoft.Insights/scheduledQueryRules/ 相关联。Log alerts in Azure Monitor are associated with resource type Microsoft.Insights/scheduledQueryRules/. 有关此资源类型的详细信息,请参阅 Azure Monitor - 计划查询规则 API 参考For more information on this resource type, see Azure Monitor - Scheduled Query Rules API reference. 可以使用计划查询规则 API 为 Application Insights 或 Log Analytics 创建日志警报。Log alerts for Application Insights or Log Analytics, can be created using Scheduled Query Rules API.

备注

还可以使用旧式 Log Analytics 警报 API 以及 Log Analytics 保存的搜索和警报的旧式模板管理 Log Analytics 的日志警报。Log alerts for Log Analytics can also be managed using legacy Log Analytics Alert API and legacy templates of Log Analytics saved searches and alerts as well. 有关默认使用此处详述的新 ScheduledQueryRules API 的详细信息,请参阅切换到 Log Analytics 警报的新 APIFor more information on using the new ScheduledQueryRules API detailed here by default, see Switch to new API for Log Analytics Alerts.

使用 Azure 资源模板创建日志警报示例Sample Log alert creation using Azure Resource Template

以下是基于资源模板的计划查询规则创建结构,它使用结果类型日志警报的数量的标准日志搜索查询,其中示例数据集作为变量。The following is the structure for Scheduled Query Rules creation based resource template using standard log search query of number of results type log alert, with sample data set as variables.

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
    },
    "variables": {
        "alertLocation": "southcentralus",
        "alertName": "samplelogalert",
        "alertDescription": "Sample log search alert",
        "alertStatus": "true",
        "alertSource":{
            "Query":"requests",
            "SourceId": "/subscriptions/a123d7efg-123c-1234-5678-a12bc3defgh4/resourceGroups/myRG/providers/microsoft.insights/components/sampleAIapplication",
            "Type":"ResultCount"
        },
        "alertSchedule":{
            "Frequency": 15,
            "Time": 60
        },
        "alertActions":{
            "SeverityLevel": "4"
        },
        "alertTrigger":{
            "Operator":"GreaterThan",
            "Threshold":"1"
        },
        "actionGrp":{
            "ActionGroup": "/subscriptions/a123d7efg-123c-1234-5678-a12bc3defgh4/resourceGroups/myRG/providers/microsoft.insights/actiongroups/sampleAG",
            "Subject": "Customized Email Header",
            "Webhook": "{ \"alertname\":\"#alertrulename\", \"IncludeSearchResults\":true }"
        }
    },
    "resources":[ {
        "name":"[variables('alertName')]",
        "type":"Microsoft.Insights/scheduledQueryRules",
        "apiVersion": "2018-04-16",
        "location": "[variables('alertLocation')]",
        "properties":{
            "description": "[variables('alertDescription')]",
            "enabled": "[variables('alertStatus')]",
            "source": {
                "query": "[variables('alertSource').Query]",
                "dataSourceId": "[variables('alertSource').SourceId]",
                "queryType":"[variables('alertSource').Type]"
            },
            "schedule":{
                "frequencyInMinutes": "[variables('alertSchedule').Frequency]",
                "timeWindowInMinutes": "[variables('alertSchedule').Time]"
            },
            "action":{
                "odata.type": "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.AlertingAction",
                "severity":"[variables('alertActions').SeverityLevel]",
                "aznsAction":{
                    "actionGroup":"[array(variables('actionGrp').ActionGroup)]",
                    "emailSubject":"[variables('actionGrp').Subject]",
                    "customWebhookPayload":"[variables('actionGrp').Webhook]"
                },
                "trigger":{
                    "thresholdOperator":"[variables('alertTrigger').Operator]",
                    "threshold":"[variables('alertTrigger').Threshold]"
                }
            }
        }
    } ]
}

针对此演练,上面的示例 json 可以保存为(例如)sampleScheduledQueryRule.json,并且可以使用 Azure 门户中的 Azure 资源管理器进行部署。The sample json above can be saved as (say) sampleScheduledQueryRule.json for the purpose of this walk through and can be deployed using Azure Resource Manager in Azure portal.

使用 Azure 资源模板进行跨资源查询的日志警报Log alert with cross-resource query using Azure Resource Template

以下是基于资源模板的计划查询规则创建结构,它使用指标度量值类型日志警报跨资源日志搜索查询,其中示例数据集作为变量。The following is the structure for Scheduled Query Rules creation based resource template using cross-resource log search query of metric measurement type log alert, with sample data set as variables.


{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
    },
    "variables": {
        "alertLocation": "Region Name for your Application Insights App or Log Analytics Workspace",
        "alertName": "sample log alert",
        "alertDescr": "Sample log search alert",
        "alertStatus": "true",
        "alertSource":{
            "Query":"union workspace(\"servicews\").Update, app('serviceapp').requests | summarize AggregatedValue = count() by bin(TimeGenerated,1h), Classification",
            "Resource1": "/subscriptions/a123d7efg-123c-1234-5678-a12bc3defgh4/resourceGroups/contosoRG/providers/microsoft.OperationalInsights/workspaces/servicews",
            "Resource2": "/subscriptions/a123d7efg-123c-1234-5678-a12bc3defgh4/resourceGroups/contosoRG/providers/microsoft.insights/components/serviceapp",
            "SourceId": "/subscriptions/a123d7efg-123c-1234-5678-a12bc3defgh4/resourceGroups/contosoRG/providers/microsoft.OperationalInsights/workspaces/servicews",
            "Type":"ResultCount"
        },
        "alertSchedule":{
            "Frequency": 15,
            "Time": 60
        },
        "alertActions":{
            "SeverityLevel": "4",
            "SuppressTimeinMin": 20
        },
        "alertTrigger":{
            "Operator":"GreaterThan",
            "Threshold":"1"
        },
        "metricMeasurement": {
            "thresholdOperator": "Equal",
            "threshold": "1",
            "metricTriggerType": "Consecutive",
            "metricColumn": "Classification"
        },
        "actionGrp":{
            "ActionGroup": "/subscriptions/a123d7efg-123c-1234-5678-a12bc3defgh4/resourceGroups/contosoRG/providers/microsoft.insights/actiongroups/sampleAG",
            "Subject": "Customized Email Header",
            "Webhook": "{ \"alertname\":\"#alertrulename\", \"IncludeSearchResults\":true }"
        }
    },
    "resources":[ {
        "name":"[variables('alertName')]",
        "type":"Microsoft.Insights/scheduledQueryRules",
        "apiVersion": "2018-04-16",
        "location": "[variables('alertLocation')]",
        "properties":{
            "description": "[variables('alertDescr')]",
            "enabled": "[variables('alertStatus')]",
            "source": {
                "query": "[variables('alertSource').Query]",
                "authorizedResources": "[concat(array(variables('alertSource').Resource1), array(variables('alertSource').Resource2))]",
                "dataSourceId": "[variables('alertSource').SourceId]",
                "queryType":"[variables('alertSource').Type]"
            },
            "schedule":{
                "frequencyInMinutes": "[variables('alertSchedule').Frequency]",
                "timeWindowInMinutes": "[variables('alertSchedule').Time]"
            },
            "action":{
                "odata.type": "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.AlertingAction",
                "severity":"[variables('alertActions').SeverityLevel]",
                "throttlingInMin": "[variables('alertActions').SuppressTimeinMin]",
                "aznsAction":{
                    "actionGroup": "[array(variables('actionGrp').ActionGroup)]",
                    "emailSubject":"[variables('actionGrp').Subject]",
                    "customWebhookPayload":"[variables('actionGrp').Webhook]"
                },
                "trigger":{
                    "thresholdOperator":"[variables('alertTrigger').Operator]",
                    "threshold":"[variables('alertTrigger').Threshold]",
                    "metricTrigger":{
                        "thresholdOperator": "[variables('metricMeasurement').thresholdOperator]",
                        "threshold": "[variables('metricMeasurement').threshold]",
                        "metricColumn": "[variables('metricMeasurement').metricColumn]",
                        "metricTriggerType": "[variables('metricMeasurement').metricTriggerType]"
                    }
                }
            }
        }
    } ]
}

重要

使用日志警报中的跨资源查询时,必须使用 authorizedResources 且用户必须有权访问所述的资源列表When using cross-resource query in log alert, the usage of authorizedResources is mandatory and user must have access to the list of resources stated

针对此演练,上面的示例 json 可以保存为(例如)sampleScheduledQueryRule.json,并且可以使用 Azure 门户中的 Azure 资源管理器进行部署。The sample json above can be saved as (say) sampleScheduledQueryRule.json for the purpose of this walk through and can be deployed using Azure Resource Manager in Azure portal.

使用 PowerShell 管理日志警报Managing log alerts using PowerShell

备注

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

Azure Monitor - 计划查询规则 API 是一个 REST API,与 Azure 资源管理器 REST API 完全兼容。Azure Monitor - Scheduled Query Rules API is a REST API and fully compatible with Azure Resource Manager REST API. 下面列出的 PowerShell cmdlet 可供利用计划查询规则 APIAnd PowerShell cmdlets listed below are available to leverage the Scheduled Query Rules API.

  1. New-AzScheduledQueryRule:用于新建日志警报规则的 Powershell cmdlet。New-AzScheduledQueryRule : Powershell cmdlet to create a new log alert rule.
  2. Set-AzScheduledQueryRule:用于更新现有日志警报规则的 Powershell cmdlet。Set-AzScheduledQueryRule : Powershell cmdlet to update an existing log alert rule.
  3. New-AzScheduledQueryRuleSource:用于创建或更新对象的 Powershell cmdlet,该对象为日志警报指定源参数。New-AzScheduledQueryRuleSource : Powershell cmdlet to create or update object specifying source parameters for a log alert. New-AzScheduledQueryRuleSet-AzScheduledQueryRule cmdlet 用作输入。Used as input by New-AzScheduledQueryRule and Set-AzScheduledQueryRule cmdlet.
  4. New-AzScheduledQueryRuleSchedule:用于创建或更新对象的 Powershell cmdlet,该对象为日志警报指定计划参数。New-AzScheduledQueryRuleSchedule: Powershell cmdlet to create or update object specifying schedule parameters for a log alert. New-AzScheduledQueryRuleSet-AzScheduledQueryRule cmdlet 用作输入。Used as input by New-AzScheduledQueryRule and Set-AzScheduledQueryRule cmdlet.
  5. New-AzScheduledQueryRuleAlertingAction:用于创建或更新对象的 Powershell cmdlet,该对象为日志警报指定操作参数。New-AzScheduledQueryRuleAlertingAction : Powershell cmdlet to create or update object specifying action parameters for a log alert. New-AzScheduledQueryRuleSet-AzScheduledQueryRule cmdlet 用作输入。Used as input by New-AzScheduledQueryRule and Set-AzScheduledQueryRule cmdlet.
  6. New-AzScheduledQueryRuleAznsActionGroup:用于创建或更新对象的 Powershell cmdlet,该对象为日志警报指定操作组参数。New-AzScheduledQueryRuleAznsActionGroup : Powershell cmdlet to create or update object specifying action groups parameters for a log alert. New-AzScheduledQueryRuleAlertingAction cmdlet 用作输入。Used as input by New-AzScheduledQueryRuleAlertingAction cmdlet.
  7. New-AzScheduledQueryRuleTriggerCondition:用于创建或更新对象的 Powershell cmdlet,该对象为日志警报指定触发条件参数。New-AzScheduledQueryRuleTriggerCondition : Powershell cmdlet to create or update object specifying trigger condition parameters for log alert. New-AzScheduledQueryRuleAlertingAction cmdlet 用作输入。Used as input by New-AzScheduledQueryRuleAlertingAction cmdlet.
  8. New-AzScheduledQueryRuleLogMetricTrigger:用于创建或更新对象的 Powershell cmdlet,该对象为指标度量单位类型日志警报指定指标触发条件参数。New-AzScheduledQueryRuleLogMetricTrigger : Powershell cmdlet to create or update object specifying metric trigger condition parameters for metric measurement type log alert. New-AzScheduledQueryRuleTriggerCondition cmdlet 用作输入。Used as input by New-AzScheduledQueryRuleTriggerCondition cmdlet.
  9. Get-AzScheduledQueryRule:用于列出现有日志警报规则或特定日志警报规则的 Powershell cmdletGet-AzScheduledQueryRule : Powershell cmdlet to list existing log alert rules or a specific log alert rule
  10. Update-AzScheduledQueryRule:用于启用或禁用日志警报规则的 Powershell cmdletUpdate-AzScheduledQueryRule : Powershell cmdlet to enable or disable log alert rule
  11. Remove-AzScheduledQueryRule:用于删除现有日志警报规则的 Powershell cmdletRemove-AzScheduledQueryRule: Powershell cmdlet to delete an existing log alert rule

备注

ScheduledQueryRules PowerShell cmdlet 只能管理使用 cmdlet 本身或 Azure Monitor - 计划查询规则 API 创建的规则。ScheduledQueryRules PowerShell cmdlets can only manage rules created cmdlet itself or using Azure Monitor - Scheduled Query Rules API. 仅当用户切换 Log Analytics 警报的 API 首选项后,使用旧版 Log Analytics 警报 APILog Analytics 保存的搜索和警报的旧版模板创建的日志警报规则才能使用 ScheduledQueryRules PowerShell cmdlet 进行管理。Log alert rules created using legacy Log Analytics Alert API and legacy templates of Log Analytics saved searches and alerts can be managed using ScheduledQueryRules PowerShell cmdlets only after user switches API preference for Log Analytics Alerts.

下面演示了使用 scheduledQueryRules PowerShell cmdlet 创建示例日志警报规则的步骤。Illustrated next are the steps for creation of a sample log alert rule using the scheduledQueryRules PowerShell cmdlets.

$source = New-AzScheduledQueryRuleSource -Query 'Heartbeat | summarize AggregatedValue = count() by bin(TimeGenerated, 5m), _ResourceId' -DataSourceId "/subscriptions/a123d7efg-123c-1234-5678-a12bc3defgh4/resourceGroups/contosoRG/providers/microsoft.OperationalInsights/workspaces/servicews"

$schedule = New-AzScheduledQueryRuleSchedule -FrequencyInMinutes 15 -TimeWindowInMinutes 30

$metricTrigger = New-AzScheduledQueryRuleLogMetricTrigger -ThresholdOperator "GreaterThan" -Threshold 2 -MetricTriggerType "Consecutive" -MetricColumn "_ResourceId"

$triggerCondition = New-AzScheduledQueryRuleTriggerCondition -ThresholdOperator "LessThan" -Threshold 5 -MetricTrigger $metricTrigger

$aznsActionGroup = New-AzScheduledQueryRuleAznsActionGroup -ActionGroup "/subscriptions/a123d7efg-123c-1234-5678-a12bc3defgh4/resourceGroups/contosoRG/providers/microsoft.insights/actiongroups/sampleAG" -EmailSubject "Custom email subject" -CustomWebhookPayload "{ \"alert\":\"#alertrulename\", \"IncludeSearchResults\":true }"

$alertingAction = New-AzScheduledQueryRuleAlertingAction -AznsAction $aznsActionGroup -Severity "3" -Trigger $triggerCondition

New-AzScheduledQueryRule -ResourceGroupName "contosoRG" -Location "Region Name for your Application Insights App or Log Analytics Workspace" -Action $alertingAction -Enabled $true -Description "Alert description" -Schedule $schedule -Source $source -Name "Alert Name"

使用 CLI 或 API 管理日志警报Managing log alerts using CLI or API

Azure Monitor - 计划查询规则 API 是一个 REST API,与 Azure 资源管理器 REST API 完全兼容。Azure Monitor - Scheduled Query Rules API is a REST API and fully compatible with Azure Resource Manager REST API. 因此,可使用 Azure CLI 的资源管理器命令,通过 Powershell 来利用它。Hence it can be used via Powershell using Resource Manager commands for Azure CLI.

备注

还可以使用旧式 Log Analytics 警报 API 以及 Log Analytics 保存的搜索和警报的旧式模板管理 Log Analytics 的日志警报。Log alerts for Log Analytics can also be managed using legacy Log Analytics Alert API and legacy templates of Log Analytics saved searches and alerts as well. 有关默认使用此处详述的新 ScheduledQueryRules API 的详细信息,请参阅切换到 Log Analytics 警报的新 APIFor more information on using the new ScheduledQueryRules API detailed here by default, see Switch to new API for Log Analytics Alerts.

日志警报目前没有专用的 CLI 命令;但是如下所示,这些警报可通过用于“资源模板”部分前面显示的示例资源模板 (sampleScheduledQueryRule.json) 的 Azure 资源管理器 CLI 命令来使用:Log alerts currently do not have dedicated CLI commands currently; but as illustrated below can be used via Azure Resource Manager CLI command for sample Resource Template shown earlier (sampleScheduledQueryRule.json) in the Resource Template section:

az group deployment create --resource-group contosoRG --template-file sampleScheduledQueryRule.json

成功执行操作后,将返回 201 声明新的警报规则创建,如果修改了现有警报规则,则返回 200。On successful operation, 201 will be returned to state new alert rule creation or 200 will be returned if an existing alert rule was modified.

后续步骤Next steps