為 Azure 監視器中的記錄建立計量警示Create Metric Alerts for Logs in Azure Monitor

概觀Overview

注意

本文已更新為使用 Azure Az PowerShell 模組。This article has been updated to use the Azure Az PowerShell module. Az PowerShell 模組是用來與 Azure 互動的建議 PowerShell 模組。The Az PowerShell module is the recommended PowerShell module for interacting with Azure. 若要開始使用 Az PowerShell 模組,請參閱安裝 Azure PowerShellTo get started with the Az PowerShell module, see Install Azure PowerShell. 若要瞭解如何遷移至 Az PowerShell 模組,請參閱將 Azure PowerShell 從 AzureRM 遷移至 Az。To learn how to migrate to the Az PowerShell module, see Migrate Azure PowerShell from AzureRM to Az.

您可以針對從記錄中的計量(包括 Azure 或內部部署中的資源)所解壓縮的熱門 Log Analytics 記錄,使用計量警示。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-premises. 以下列出支援的 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.
  • 記錄的計量警示提供多個維度,允許篩選較簡單且不需要在分析中釘選查詢的特定值,例如電腦、作業系統類型等。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 監視器計量來查看從 Log Analytics 工作區解壓縮的支援計量,則必須在該特定度量上建立記錄的計量警示。To view a supported metric extracted from a Log Analytics workspace via Azure Monitor - Metrics, a metric alert for log must be created on that specific metric. 在記錄的計量警示中選擇的維度,只會顯示透過 Azure 監視器計量進行探索。The dimensions chosen in the metric alert for logs - will only appear for exploration via Azure Monitor - Metrics.

建立 Log Analytics 的計量警示Creating metric alert for Log Analytics

來自常用記錄的計量資料會先輸送至 [Azure 監視器 - 計量],再於 Log Analytics 中處理。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-premises 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. 例如,您必須先在 效能計數器解決方案中設定其 % Available Memory 計數器。For example, for % Available Memory counter of it must be configured in Performance counters solution first.

設定記錄的計量警示Configuring Metric Alert for Logs

您可以使用 Azure 入口網站、Resource Manager 範本、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 監視器 - 排程的查詢規則,先建立將記錄資料轉換為計量的明確規則。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.

注意

針對 Log Analytics 工作區建立計量警示時,透過 Azure 入口網站對應的規則,將記錄資料轉換為計量(透過 Azure 監視器-排程查詢規則 會在背景中自動建立), 而不需要任何使用者介入或動作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 Resource Manager 範本;此時,要建立靜態閾值計量警示,必須透過 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.OperationalInsights/workspaces/workspaceName"
            }
        },
        "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 deployment group create --resource-group myRG --template-file metricfromLogsAlertStatic.json --parameters @metricfromLogsAlertStatic.parameters.json

具有動態閾值的記錄計量警示Metric Alerts for Logs with Dynamic Thresholds

若要達到相同效果,您可以使用下面的範例 Azure Resource Manager 範本;此時,要建立動態閾值計量警示,必須透過 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.OperationalInsights/workspaces/workspaceName"
            }
        },
        "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 deployment group create --resource-group myRG --template-file metricfromLogsAlertDynamic.json --parameters @metricfromLogsAlertDynamic.parameters.json

下一步Next steps