我应该使用什么 API 来管理 Azure 中的警报和警报规则?

问题描述 投票:0回答:1

在 Azure 门户中我看到了这个:

Alerts and Alert Rules in Azure Portal

此外,我还成功运行了以下 cli 命令:

az monitor metrics alert list --subscription  "$sub"
az monitor activity-log alert list --subscription  "$sub"

但在我的一生中,我似乎无法找到使用 Python 管理警报和警报规则的正确 API。查看 API 参考,我看到了这一点:

Azure API categories relevant for alerts and alert rules

请注意,提到了警报处理规则,但没有提到警报或警报规则。还提到了监视器。 监视器有警报吗

我与在线示例代码、API 文档和迷幻的法学硕士进行了一番争论,才得出了这个令人厌恶的结果:

def alert_rules(self, tag:str = None, do_debug = False):
    """
    List metric alerts across all subscriptions
    """
    rules = list()
    for subscription_id in self.subscriptions:
        if do_debug:
            logger.info(f"Looking for alert rules in sub {subscription_id}")
        try:
            monitor_client = self._monitor_client_for_sub(subscription_id)
            if monitor_client:
                if do_debug:
                    metric_alerts = list(monitor_client.metric_alerts.list_by_subscription())
                    scheduled_query_alerts = list(monitor_client.scheduled_query_rules.list_by_subscription())
                    logger.info(f"  Metric alerts retrieved: {devtools.pformat(metric_alerts)}")
                    logger.info(f"  Scheduled query alerts retrieved: {devtools.pformat(scheduled_query_alerts)}")
                
                resource_client = self._resource_client_for_sub(subscription_id)
                if resource_client:
                    resource_groups = [rg.name for rg in resource_client.resource_groups.list()]
                    for rg in resource_groups:
                        if do_debug:
                            logger.info(f"  Looking for alert rules in rg {rg}")
                        for rule in monitor_client.scheduled_query_rules.list_by_resource_group(rg):
                            logger.debug(f"    {rule}")
                            rules.append(rule)
                else:
                    if do_debug:
                        logger.warning(f"  No resource group client for {subscription_id}")
                # List all Metric Alert Rules
                for rule in monitor_client.metric_alerts.list_by_subscription():
                    logger.debug(f"  Scheduled Query Alert Rule: {rule}")
                    rules.append(rule)
                # List all Scheduled Query (Log) Alert Rules
                for rule in monitor_client.scheduled_query_rules.list_by_subscription():
                    logger.debug(f"  Scheduled Query Alert Rule: {rule}")
                    rules.append(rule)

                logs_query_client = self._logs_query_client_for_sub(subscription_id)
                if do_debug:
                    #logger.warning(f"Logs query client for {subscription_id}: {devtools.pformat(logs_query_client.__dict__)}")
                    pass
            else:
                if do_debug:
                    logger.warning(f"  No monitor client for {subscription_id}")
        except Exception as e:
            logger.error(f"* Error listing alert rules for sub {subscription_id}: {e}")
            return None
    if tag:
        if do_debug:
            logger.info(f"We have a tag to match: {tag}")
        alert_rules_with_tag = []
        for rule in rules:
            if rule.tags and tag in rule.tags:
                alert_rules_with_tag.append(rule)
        rules = alert_rules_with_tag
    else:
        if do_debug:
            logger.info(f"No tag")
    processed = list()
    for rule in rules:
        if do_debug:
            logger.info(f"Processing rule: {rule}")
        processed.append(self.process_rule(rule))

    return processed

它是我的客户端类的一个成员函数,它拼命地尝试通过许多不同的方式来简单地列出警报规则。即使 cli 命令产生良好的输出,它也会产生一个空列表。

所以我的问题是,这个API存在吗?我应该如何列出我的订阅的警报规则?

python azure azure-python-sdk alert-rules
1个回答
0
投票

所以我的问题是,这个API存在吗?我应该如何列出我的订阅的警报规则?

在我的环境中,我有一些具有不同信号类型的警报规则。

传送门:

enter image description here

您可以使用下面的 python 代码从订阅中检索所需的警报规则。

代码:

from azure.identity import DefaultAzureCredential
from azure.mgmt.monitor import MonitorManagementClient

subscription_id = 'xxxx'

credentials = DefaultAzureCredential()

monitor_client = MonitorManagementClient(
    credential=credentials,
    subscription_id=subscription_id
)

    # Retrieve metric alerts
metric_alerts = monitor_client.metric_alerts.list_by_subscription()
for alert in metric_alerts:
    print("Metric Alert - Name:", alert.name, "| Type:", alert.type)

    # Retrieve activity log alerts
activity_log_alerts = monitor_client.activity_log_alerts.list_by_subscription_id()
for activity_alert in activity_log_alerts:
    print("Activity Log Alert - Name:", activity_alert.name, "| Type:", activity_alert.type)

    # Retrieve log search alerts (scheduled query rules)
log_search_alerts = monitor_client.scheduled_query_rules.list_by_subscription()
for log_alert in log_search_alerts:
    print("Log Search Alert - Name:", log_alert.name, "| Type:", log_alert.type)

输出:

Metric Alert - Name: testvenkat | Type: Microsoft.Insights/metricAlerts
Metric Alert - Name: venakt234 | Type: Microsoft.Insights/metricAlerts
Activity Log Alert - Name: venkat123 | Type: Microsoft.Insights/ActivityLogAlerts
Log Search Alert - Name: venkat456 | Type: Microsoft.Insights/scheduledQueryRules

enter image description here

参考: 适用于 Python 的 Microsoft Azure SDK |微软学习

© www.soinside.com 2019 - 2024. All rights reserved.