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

在 Azure Monitor 中创建日志的指标警报Create Metric Alerts for Logs in Azure Monitor

概述Overview

备注

本文进行了更新,以便使用新的 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 支持比经典警报更具优势的指标警报类型Azure Monitor supports metric alert type which has benefits over the classic alerts. 指标可用于 Azure 服务的大型列表Metrics are available for large list of Azure services. 本文解释某个资源子集的用法 - Microsoft.OperationalInsights/workspacesThis article explains usage of a subset (that is) for resource - Microsoft.OperationalInsights/workspaces.

还可对常用 Log Analytics 日志(作为“日志中的指标”的一部分提取为指标)使用指标警报,包括 Azure 中或本地的资源。You can use metric alerts on popular Log Analytics logs extracted as metrics as part of Metrics from Logs including resources in Azure or on-premise. 下面列出了支持的 Log Analytics 解决方案:The supported Log Analytics solutions are listed below:

与 Azure 中基于查询的日志警报相比,使用日志的指标警报可带来多种优势;下面列出了其中的某些优势:There are many benefits for using Metric Alerts for Logs over query based Log Alerts in Azure; some of them are listed below:

  • 指标警报提供近实时监视功能,日志的指标警报从日志源克隆数据以确保相同Metric Alerts offer near-real time monitoring capability and Metric Alerts for Logs forks data from log source to ensure the same.
  • 指标警报是有状态的 - 只会在激发警报以及解决警报时才通知一次;相反,日志警报是无状态的,只要满足警报条件,它就会按时间间隔保持激发。Metric Alerts are stateful - only notifying once when alert is fired and once when alert is resolved; as opposed to Log alerts, which are stateless and keep firing at every interval if the alert condition is met.
  • 日志的指标警报提供多个维度,可以简化根据特定的值(例如“计算机”、“OS 类型”等)进行筛选的操作;无需在 Analytics 中编写查询。Metric Alerts for Log provide multiple dimensions, allowing filtering to specific values like Computers, OS Type, etc. simpler; without the need for penning query in analytics.

备注

只有在选定期间内存在其数据时,特定的指标和/或维度才会显示。Specific metric and/or dimension will only be shown if data for it exists in chosen period. 这些指标适用于使用 Azure Log Analytics 工作区的客户。These metrics are available for customers with Azure Log Analytics workspaces.

日志支持的指标和维度Metrics and dimensions supported for logs

指标警报支持针对使用维度的指标发出警报。Metric alerts support alerting for metrics that use dimensions. 可以使用维度将指标筛选到适当级别。You can use dimensions to filter your metric to the right level. 受支持的解决方案将提供 Log Analytics 工作区中受日志支持的指标的完整列表。The full list of metrics supported for Logs from Log Analytics workspaces is listed; across supported solutions.

备注

若要通过 Azure Monitor - 指标查看从 Log Analytics 工作区中提取的受支持指标,必须为所述指标创建日志的指标警报。To view supported metrics for being extracted from Log Analytics workspace via Azure Monitor - Metrics; a metric alert for log must be created for the said metric. 只能通过“Azure Monitor - 指标”浏览在“日志的指标警报”中选择的维度。The dimensions chosen in Metric Alert for logs - will only appear for exploration via Azure Monitor - Metrics.

为 Log Analytics 创建指标警报Creating metric alert for Log Analytics

在 Log Analytics 中处理常用日志中的指标数据之前,会先通过管道将其传送到“Azure Monitor - 指标”。Metric data from popular logs is piped before it is processed in Log Analytics, into Azure Monitor - Metrics. 这样,用户便可以利用指标平台的功能以及指标警报 - 包括创建频率低至 1 分钟的警报。This allows users to leverage the capabilities of the Metric platform as well as metric alert - including having alerts with frequency as low as 1 minute. 下面列出了为日志创建指标警报的方式。Listed below are the means of crafting a metric alert for logs.

日志的指标警报的先决条件Prerequisites for Metric Alert for Logs

在针对 Log Analytics 数据收集的日志指标正常工作之前,必须设置以下各项,并确保这些项可用:Before Metric for Logs gathered on Log Analytics data works, the following must be set up and available:

  1. 活动的 Log Analytics 工作区:有效且活动的 Log Analytics 工作区必须存在。Active Log Analytics Workspace: A valid and active Log Analytics workspace must be present. 有关详细信息,请参阅在 Azure 门户中创建 Log Analytics 工作区For more information, see Create a Log Analytics Workspace in Azure portal.
  2. 为 Log Analytics 工作区配置了代理:需要为 Azure VM 和/或本地 VM 配置代理,以便将数据发送到前一步骤中使用的 Log Analytics 工作区。Agent is configured for Log Analytics Workspace: Agent needs to be configured for Azure VMs (and/or) On-Premise VMs to send data into the Log Analytics Workspace used in earlier step. 有关详细信息,请参阅 Log Analytics - 代理概述For more information, see Log Analytics - Agent Overview.
  3. 安装受支持的 Log Analytics 解决方案:应配置 Log Analytics 解决方案,并将数据发送到 Log Analytics 工作区支持的解决方案中,这是Windows & Linux检测信号记录的性能计数器,用于代理运行状况、更新管理事件数据Supported Log Analytics Solutions is installed: Log Analytics solution should be configured and sending data into Log Analytics workspace - supported solutions are Performance counters for Windows & Linux, Heartbeat records for Agent Health, Update management, and Event data.
  4. 配置为发送日志的 Log Analytics 解决方案:Log Analytics 解决方案应已启用与 Log Analytics 工作区支持的指标对应的所需日志/数据。Log Analytics solutions configured to send logs: Log Analytics solution should have the required logs/data corresponding to metrics supported for Log Analytics workspaces enabled. 例如,必须先在性能计数器解决方案中配置它的“可用内存百分比”计数器。For example, for % Available Memory counter of it must be configured in Performance counters solution first.

配置日志的指标警报Configuring Metric Alert for Logs

可以使用 Azure 门户、资源管理器模板、REST API、PowerShell 和 Azure CLI 来创建和管理指标警报。Metric alerts can be created and managed using the Azure portal, Resource Manager Templates, REST API, PowerShell, and Azure CLI. 由于日志的指标警报是指标警报的变体,在满足先决条件后,可为指定的 Log Analytics 工作区创建日志的指标警报。Since Metric Alerts for Logs, is a variant of metric alerts - once the prerequisites are done, metric alert for logs can be created for specified Log Analytics workspace. 指标警报的所有特征和功能同样适用于日志的指标警报,包括有效负载架构、适用的配额限制和计费价格。All characteristics and functionalities of metric alerts will be applicable to metric alerts for logs, as well; including payload schema, applicable quota limits, and billed price.

有关详细分步说明和示例,请参阅创建和管理指标警报For step-by-step details and samples - see creating and managing metric alerts. 具体而言,对于日志的指标警报,请遵照说明管理指标警报,并确保:Specifically, for Metric Alerts for Logs - follow the instructions for managing metric alerts and ensure the following:

  • 指标警报的目标是有效的 Log Analytics 工作区Target for metric alert is a valid Log Analytics workspace
  • 为选定 Log Analytics 工作区的指标警报选择的信号类型为“指标”Signal chosen for metric alert for selected Log Analytics workspace is of type Metric
  • 使用维度筛选器根据特定的条件或资源进行筛选;日志的指标是多维的Filter for specific conditions or resource using dimension filters; metrics for logs are multi-dimensional
  • 配置信号逻辑时,可以创建单个警报来跨越多个维度值(例如“计算机”)When configuring Signal Logic, a single alert can be created to span multiple values of dimension (like Computer)
  • 如果使用 Azure 门户为选定的 Log Analytics 工作区创建指标警报,则用户必须先手动创建一个显式规则,以便使用 Azure Monitor - 计划的查询规则将日志数据转换为指标。If not using Azure portal for creating metric alert for selected Log Analytics workspace; then user must manually first create an explicit rule for converting log data into a metric using Azure Monitor - Scheduled Query Rules.

备注

通过 Azure 门户为 Log Analytics 工作区创建指标警报时,会自动在后台创建相应的规则用于通过 Azure Monitor - 计划的查询规则将日志数据转换为指标,无需任何用户干预或操作。When creating metric alert for Log Analytics workspace via Azure portal - corresponding rule for converting log data into metric via Azure Monitor - Scheduled Query Rules is automatically created in background, without the need of any user intervention or action. 如果不使用 Azure 门户创建日志的指标警报,请参阅日志的指标警报的资源模板部分,了解在创建指标警报之前,创建基于 ScheduledQueryRule 的“日志到指标”转换规则的示例方法 - 否则没有任何数据可用于创建日志的指标警报。For metric alert for logs creation using means other than Azure portal, see Resource Template for Metric Alerts for Logs section on sample means of creating a ScheduledQueryRule based log to metric conversion rule before metric alert creation - else there will be no data for the metric alert on logs created.

日志的指标警报的资源模板Resource Template for Metric Alerts for Logs

如前所述,从日志创建指标警报的过程由两个部分组成:As stated earlier, the process for creation of metric alerts from logs is two pronged:

  1. 使用 scheduledQueryRule API 创建用于从支持的日志中提取指标的规则Create a rule for extracting metrics from supported logs using scheduledQueryRule API
  2. 针对从日志中提取的(步骤 1)和从用作目标资源的 Log Analytics 工作区中提取的指标创建指标警报Create a metric alert for metric extracted from log (in step1) and Log Analytics workspace as a target resource

带有静态阈值的日志的指标警报Metric Alerts for Logs with static threshold

为实现相同的效果,可以使用下面的示例 Azure 资源管理器模板 - 只有在成功创建了用于通过 scheduledQueryRule 从日志中提取指标的规则之后,才能创建静态阈值指标警报。To achieve the same, one can use the sample Azure Resource Manager Template below - where creation of a static threshold metric alert depends on successful creation of the rule for extracting metrics from logs via scheduledQueryRule.

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "convertRuleName": {
            "type": "string",
            "minLength": 1,
            "metadata": {
                "description": "Name of the rule to convert log to metric"
            }
        },
        "convertRuleDescription": {
            "type": "string",
            "minLength": 1,
            "metadata": {
                "description": "Description for log converted to metric"
            }
        },
        "convertRuleRegion": {
            "type": "string",
            "minLength": 1,
            "metadata": {
                "description": "Name of the region used by workspace"
            }
        },
        "convertRuleStatus": {
            "type": "string",
            "defaultValue": "true",
            "metadata": {
                "description": "Specifies whether the log conversion rule is enabled"
            }
        },
        "convertRuleMetric": {
            "type": "string",
            "minLength": 1,
            "metadata": {
                "description": "Name of the metric once extraction done from logs."
            }
        },
        "alertName": {
            "type": "string",
            "minLength": 1,
            "metadata": {
                "description": "Name of the alert"
            }
        },
        "alertDescription": {
            "type": "string",
            "defaultValue": "This is a metric alert",
            "metadata": {
                "description": "Description of alert"
            }
        },
        "alertSeverity": {
            "type": "int",
            "defaultValue": 3,
            "allowedValues": [
                0,
                1,
                2,
                3,
                4
            ],
            "metadata": {
                "description": "Severity of alert {0,1,2,3,4}"
            }
        },
        "isEnabled": {
            "type": "bool",
            "defaultValue": true,
            "metadata": {
                "description": "Specifies whether the alert is enabled"
            }
        },
        "resourceId": {
            "type": "string",
            "minLength": 1,
            "metadata": {
                "description": "Full Resource ID of the resource emitting the metric that will be used for the comparison. For example /subscriptions/00000000-0000-0000-0000-0000-00000000/resourceGroups/ResourceGroupName/providers/Microsoft.compute/virtualMachines/VM_xyz"
            }
        },
        "metricName": {
            "type": "string",
            "minLength": 1,
            "metadata": {
                "description": "Name of the metric used in the comparison to activate the alert."
            }
        },
        "operator": {
            "type": "string",
            "defaultValue": "GreaterThan",
            "allowedValues": [
                "Equals",
                "NotEquals",
                "GreaterThan",
                "GreaterThanOrEqual",
                "LessThan",
                "LessThanOrEqual"
            ],
            "metadata": {
                "description": "Operator comparing the current value with the threshold value."
            }
        },
        "threshold": {
            "type": "string",
            "defaultValue": "0",
            "metadata": {
                "description": "The threshold value at which the alert is activated."
            }
        },
        "timeAggregation": {
            "type": "string",
            "defaultValue": "Average",
            "allowedValues": [
                "Average",
                "Minimum",
                "Maximum",
                "Total"
            ],
            "metadata": {
                "description": "How the data that is collected should be combined over time."
            }
        },
        "windowSize": {
            "type": "string",
            "defaultValue": "PT5M",
            "metadata": {
                "description": "Period of time used to monitor alert activity based on the threshold. Must be between five minutes and one day. ISO 8601 duration format."
            }
        },
        "evaluationFrequency": {
            "type": "string",
            "defaultValue": "PT1M",
            "metadata": {
                "description": "how often the metric alert is evaluated represented in ISO 8601 duration format"
            }
        },
        "actionGroupId": {
            "type": "string",
            "defaultValue": "",
            "metadata": {
                "description": "The ID of the action group that is triggered when the alert is activated or deactivated"
            }
        }
    },
    "variables": {
        "convertRuleTag": "hidden-link:/subscriptions/1234-56789-1234-567a/resourceGroups/resourceGroupName/providers/Microsoft.OperationalInsights/workspaces/workspaceName",
        "convertRuleSourceWorkspace": {
            "SourceId": "/subscriptions/1234-56789-1234-567a/resourceGroups/resourceGroupName/providers/Microsoft.OperationalInsights/workspaces/workspaceName"
        }
    },
    "resources": [
        {
            "name": "[parameters('convertRuleName')]",
            "type": "Microsoft.Insights/scheduledQueryRules",
            "apiVersion": "2018-04-16",
            "location": "[parameters('convertRuleRegion')]",
            "tags": {
                "[variables('convertRuleTag')]": "Resource"
            },
            "properties": {
                "description": "[parameters('convertRuleDescription')]",
                "enabled": "[parameters('convertRuleStatus')]",
                "source": {
                    "dataSourceId": "[variables('convertRuleSourceWorkspace').SourceId]"
                },
                "action": {
                    "odata.type": "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.LogToMetricAction",
                    "criteria": [{
                            "metricName": "[parameters('convertRuleMetric')]",
                            "dimensions": []
                        }
                    ]
                }
            }
        },
        {
            "name": "[parameters('alertName')]",
            "type": "Microsoft.Insights/metricAlerts",
            "location": "global",
            "apiVersion": "2018-03-01",
            "tags": {},
            "dependsOn":["[resourceId('Microsoft.Insights/scheduledQueryRules',parameters('convertRuleName'))]"],
            "properties": {
                "description": "[parameters('alertDescription')]",
                "severity": "[parameters('alertSeverity')]",
                "enabled": "[parameters('isEnabled')]",
                "scopes": ["[parameters('resourceId')]"],
                "evaluationFrequency":"[parameters('evaluationFrequency')]",
                "windowSize": "[parameters('windowSize')]",
                "criteria": {
                    "odata.type": "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria",
                    "allOf": [
                        {
                            "name" : "1st criterion",
                            "metricName": "[parameters('metricName')]",
                            "dimensions":[],
                            "operator": "[parameters('operator')]",
                            "threshold" : "[parameters('threshold')]",
                            "timeAggregation": "[parameters('timeAggregation')]"
                        }
                    ]
                },
                "actions": [
                    {
                        "actionGroupId": "[parameters('actionGroupId')]"
                    }
                ]
            }
        }
    ]
}

假设上述 JSON 保存为 metricfromLogsAlertStatic.json,可将其与某个参数 JSON 文件相结合,在资源模板中创建警报。Say the above JSON is saved as metricfromLogsAlertStatic.json - then it can be coupled with a parameter JSON file for Resource Template based creation. 下面列出了示例参数 JSON 文件:A sample parameter JSON file is listed below:

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "convertRuleName": {
            "value": "TestLogtoMetricRule" 
        },
        "convertRuleDescription": {
            "value": "Test rule to extract metrics from logs via template"
        },
        "convertRuleRegion": {
            "value": "West Central US"
        },
        "convertRuleStatus": {
            "value": "true"
        },
        "convertRuleMetric": {
            "value": "Average_% Idle Time"
        },
        "alertName": {
            "value": "TestMetricAlertonLog"
        },
        "alertDescription": {
            "value": "New multi-dimensional metric alert created via template"
        },
        "alertSeverity": {
            "value":3
        },
        "isEnabled": {
            "value": true
        },
        "resourceId": {
            "value": "/subscriptions/1234-56789-1234-567a/resourceGroups/myRG/providers/Microsoft.OperationalInsights/workspaces/workspaceName"
        },
        "metricName":{
            "value": "Average_% Idle Time"
        },
        "operator": {
            "value": "GreaterThan"
        },
        "threshold":{
            "value": "1"
        },
        "timeAggregation":{
            "value": "Average"
        },
        "actionGroupId": {
            "value": "/subscriptions/1234-56789-1234-567a/resourceGroups/myRG/providers/microsoft.insights/actionGroups/actionGroupName"
        }
    }
}

假设上述参数文件保存为 metricfromLogsAlertStatic.parameters.json,则可以使用 Azure 门户中用于创建警报的资源模板来创建日志的指标警报。Assuming the above parameter file is saved as metricfromLogsAlertStatic.parameters.json; then one can create metric alert for logs using Resource Template for creation in Azure portal.

也可以使用以下 Azure Powershell 命令:Alternatively, one can use the Azure Powershell command below as well:

New-AzResourceGroupDeployment -ResourceGroupName "myRG" -TemplateFile metricfromLogsAlertStatic.json TemplateParameterFile metricfromLogsAlertStatic.parameters.json

或使用 Azure CLI 部署资源模板:Or use deploy Resource Template using Azure CLI:

az group deployment create --resource-group myRG --template-file metricfromLogsAlertStatic.json --parameters @metricfromLogsAlertStatic.parameters.json

带有动态阈值的日志的指标警报Metric Alerts for Logs with Dynamic Thresholds

为实现相同的效果,可以使用下面的示例 Azure 资源管理器模板 - 只有在成功创建了用于通过 scheduledQueryRule 从日志中提取指标的规则之后,才能创建动态阈值指标警报。To achieve the same, one can use the sample Azure Resource Manager Template below - where creation of a Dynamic Thresholds metric alert depends on successful creation of the rule for extracting metrics from logs via scheduledQueryRule.

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "convertRuleName": {
            "type": "string",
            "minLength": 1,
            "metadata": {
                "description": "Name of the rule to convert log to metric"
            }
        },
        "convertRuleDescription": {
            "type": "string",
            "minLength": 1,
            "metadata": {
                "description": "Description for log converted to metric"
            }
        },
        "convertRuleRegion": {
            "type": "string",
            "minLength": 1,
            "metadata": {
                "description": "Name of the region used by workspace"
            }
        },
        "convertRuleStatus": {
            "type": "string",
            "defaultValue": "true",
            "metadata": {
                "description": "Specifies whether the log conversion rule is enabled"
            }
        },
        "convertRuleMetric": {
            "type": "string",
            "minLength": 1,
            "metadata": {
                "description": "Name of the metric once extraction done from logs."
            }
        },
        "alertName": {
            "type": "string",
            "minLength": 1,
            "metadata": {
                "description": "Name of the alert"
            }
        },
        "alertDescription": {
            "type": "string",
            "defaultValue": "This is a metric alert",
            "metadata": {
                "description": "Description of alert"
            }
        },
        "alertSeverity": {
            "type": "int",
            "defaultValue": 3,
            "allowedValues": [
                0,
                1,
                2,
                3,
                4
            ],
            "metadata": {
                "description": "Severity of alert {0,1,2,3,4}"
            }
        },
        "isEnabled": {
            "type": "bool",
            "defaultValue": true,
            "metadata": {
                "description": "Specifies whether the alert is enabled"
            }
        },
        "resourceId": {
            "type": "string",
            "minLength": 1,
            "metadata": {
                "description": "Full Resource ID of the resource emitting the metric that will be used for the comparison. For example /subscriptions/00000000-0000-0000-0000-0000-00000000/resourceGroups/ResourceGroupName/providers/Microsoft.compute/virtualMachines/VM_xyz"
            }
        },
        "metricName": {
            "type": "string",
            "minLength": 1,
            "metadata": {
                "description": "Name of the metric used in the comparison to activate the alert."
            }
        },
        "operator": {
            "type": "string",
            "defaultValue": "GreaterOrLessThan",
            "allowedValues": [
                "GreaterThan",
                "LessThan",
                "GreaterOrLessThan"
            ],
            "metadata": {
                "description": "Operator comparing the current value with the threshold value."
            }
        },
        "alertSensitivity": {
            "type": "string",
            "defaultValue": "Medium",
            "allowedValues": [
                "High",
                "Medium",
                "Low"
            ],
            "metadata": {
                "description": "Tunes how 'noisy' the Dynamic Thresholds alerts will be: 'High' will result in more alerts while 'Low' will result in fewer alerts."
            }
        },
        "numberOfEvaluationPeriods": {
            "type": "string",
            "defaultValue": "4",
            "metadata": {
                "description": "The number of periods to check in the alert evaluation."
            }
        },
        "minFailingPeriodsToAlert": {
            "type": "string",
            "defaultValue": "3",
            "metadata": {
                "description": "The number of unhealthy periods to alert on (must be lower or equal to numberOfEvaluationPeriods)."
            }
        },
        "timeAggregation": {
            "type": "string",
            "defaultValue": "Average",
            "allowedValues": [
                "Average",
                "Minimum",
                "Maximum",
                "Total"
            ],
            "metadata": {
                "description": "How the data that is collected should be combined over time."
            }
        },
        "windowSize": {
            "type": "string",
            "defaultValue": "PT5M",
            "metadata": {
                "description": "Period of time used to monitor alert activity based on the threshold. Must be between five minutes and one day. ISO 8601 duration format."
            }
        },
        "evaluationFrequency": {
            "type": "string",
            "defaultValue": "PT1M",
            "metadata": {
                "description": "how often the metric alert is evaluated represented in ISO 8601 duration format"
            }
        },
        "actionGroupId": {
            "type": "string",
            "defaultValue": "",
            "metadata": {
                "description": "The ID of the action group that is triggered when the alert is activated or deactivated"
            }
        }
    },
    "variables": {
        "convertRuleTag": "hidden-link:/subscriptions/1234-56789-1234-567a/resourceGroups/resourceGroupName/providers/Microsoft.OperationalInsights/workspaces/workspaceName",
        "convertRuleSourceWorkspace": {
            "SourceId": "/subscriptions/1234-56789-1234-567a/resourceGroups/resourceGroupName/providers/Microsoft.OperationalInsights/workspaces/workspaceName"
        }
    },
    "resources": [
        {
            "name": "[parameters('convertRuleName')]",
            "type": "Microsoft.Insights/scheduledQueryRules",
            "apiVersion": "2018-04-16",
            "location": "[parameters('convertRuleRegion')]",
            "tags": {
                "[variables('convertRuleTag')]": "Resource"
            },
            "properties": {
                "description": "[parameters('convertRuleDescription')]",
                "enabled": "[parameters('convertRuleStatus')]",
                "source": {
                    "dataSourceId": "[variables('convertRuleSourceWorkspace').SourceId]"
                },
                "action": {
                    "odata.type": "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.LogToMetricAction",
                    "criteria": [{
                            "metricName": "[parameters('convertRuleMetric')]",
                            "dimensions": []
                        }
                    ]
                }
            }
        },
        {
            "name": "[parameters('alertName')]",
            "type": "Microsoft.Insights/metricAlerts",
            "location": "global",
            "apiVersion": "2018-03-01",
            "tags": {},
            "dependsOn":["[resourceId('Microsoft.Insights/scheduledQueryRules',parameters('convertRuleName'))]"],
            "properties": {
                "description": "[parameters('alertDescription')]",
                "severity": "[parameters('alertSeverity')]",
                "enabled": "[parameters('isEnabled')]",
                "scopes": ["[parameters('resourceId')]"],
                "evaluationFrequency":"[parameters('evaluationFrequency')]",
                "windowSize": "[parameters('windowSize')]",
                "criteria": {
                    "odata.type": "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria",
                    "allOf": [
                        {
                            "criterionType": "DynamicThresholdCriterion",
                            "name" : "1st criterion",
                            "metricName": "[parameters('metricName')]",
                            "dimensions":[],
                            "operator": "[parameters('operator')]",
                            "alertSensitivity": "[parameters('alertSensitivity')]",
                            "failingPeriods": {
                                "numberOfEvaluationPeriods": "[parameters('numberOfEvaluationPeriods')]",
                                "minFailingPeriodsToAlert": "[parameters('minFailingPeriodsToAlert')]"
                            },
                            "timeAggregation": "[parameters('timeAggregation')]"
                        }
                    ]
                },
                "actions": [
                    {
                        "actionGroupId": "[parameters('actionGroupId')]"
                    }
                ]
            }
        }
    ]
}

假设上述 JSON 保存为 metricfromLogsAlertDynamic.json,可将其与某个参数 JSON 文件相结合,在资源模板中创建警报。Say the above JSON is saved as metricfromLogsAlertDynamic.json - then it can be coupled with a parameter JSON file for Resource Template based creation. 下面列出了示例参数 JSON 文件:A sample parameter JSON file is listed below:

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "convertRuleName": {
            "value": "TestLogtoMetricRule"
        },
        "convertRuleDescription": {
            "value": "Test rule to extract metrics from logs via template"
        },
        "convertRuleRegion": {
            "value": "West Central US"
        },
        "convertRuleStatus": {
            "value": "true"
        },
        "convertRuleMetric": {
            "value": "Average_% Idle Time"
        },
        "alertName": {
            "value": "TestMetricAlertonLog"
        },
        "alertDescription": {
            "value": "New multi-dimensional metric alert created via template"
        },
        "alertSeverity": {
            "value":3
        },
        "isEnabled": {
            "value": true
        },
        "resourceId": {
            "value": "/subscriptions/1234-56789-1234-567a/resourceGroups/myRG/providers/Microsoft.OperationalInsights/workspaces/workspaceName"
        },
        "metricName":{
            "value": "Average_% Idle Time"
        },
        "operator": {
            "value": "GreaterOrLessThan"
          },
          "alertSensitivity": {
              "value": "Medium"
          },
          "numberOfEvaluationPeriods": {
              "value": "4"
          },
          "minFailingPeriodsToAlert": {
              "value": "3"
          },
        "timeAggregation":{
            "value": "Average"
        },
        "actionGroupId": {
            "value": "/subscriptions/1234-56789-1234-567a/resourceGroups/myRG/providers/microsoft.insights/actionGroups/actionGroupName"
        }
    }
}

假设上述参数文件保存为 metricfromLogsAlertDynamic.parameters.json,则可以使用 Azure 门户中用于创建警报的资源模板来创建日志的指标警报。Assuming the above parameter file is saved as metricfromLogsAlertDynamic.parameters.json; then one can create metric alert for logs using Resource Template for creation in Azure portal.

也可以使用以下 Azure Powershell 命令:Alternatively, one can use the Azure Powershell command below as well:

New-AzResourceGroupDeployment -ResourceGroupName "myRG" -TemplateFile metricfromLogsAlertDynamic.json TemplateParameterFile metricfromLogsAlertDynamic.parameters.json

或使用 Azure CLI 部署资源模板:Or use deploy Resource Template using Azure CLI:

az group deployment create --resource-group myRG --template-file metricfromLogsAlertDynamic.json --parameters @metricfromLogsAlertDynamic.parameters.json

后续步骤Next steps