Azure中管理Alerts与Alert Rules的API选型及规则列出方法问询
问题描述
我在Azure门户中能看到告警及告警规则相关界面,已经通过以下CLI命令成功获取告警规则:
az monitor metrics alert list --subscription "$sub" az monitor activity-log alert list --subscription "$sub"
但找不到用于Python管理告警和告警规则的正确API,查看API参考时只看到Alert Processing Rule和Monitors相关分类,疑惑Monitors是否等同于Alerts?
我编写了一段Python代码尝试列出告警规则,但即使CLI能输出结果,代码仍返回空列表。请问是否存在对应的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
解决方案
核心概念澄清
Azure Monitor是整个监控服务的总称,包含告警、指标、日志等模块,Monitors不等于Alerts,Alerts是Monitor下的子模块,专门处理告警规则的定义与触发。
对应Python API及问题排查
你使用的CLI命令对应两类告警:az monitor metrics alert对应指标告警,az monitor activity-log alert对应活动日志告警,加上日志查询告警(Scheduled Query Rules),三类告警分别对应azure-mgmt-monitor SDK中的不同操作类:
- 指标告警:
metric_alerts - 日志查询告警:
scheduled_query_rules - 活动日志告警:
activity_log_alerts
你的代码存在以下问题:
- 未处理活动日志告警,这是CLI能获取结果但代码返回空列表的关键原因
- 重复添加日志查询规则(既遍历资源组查询又通过订阅级查询重复添加)
- 需确认
_monitor_client_for_sub方法是否正确初始化了MonitorManagementClient(需使用有效凭据,比如DefaultAzureCredential)
修正后的完整代码
以下是覆盖三类告警的订阅级查询代码:
from azure.mgmt.monitor import MonitorManagementClient from azure.identity import DefaultAzureCredential import logging logger = logging.getLogger(__name__) def get_all_alert_rules(subscription_id: str, do_debug: bool = False): rules = [] # 初始化Monitor客户端 credential = DefaultAzureCredential() monitor_client = MonitorManagementClient(credential, subscription_id) if do_debug: logger.info(f"Querying alert rules in subscription {subscription_id}") # 1. 获取指标告警 try: metric_alerts = list(monitor_client.metric_alerts.list_by_subscription()) if do_debug: logger.info(f"Found {len(metric_alerts)} metric alerts") rules.extend(metric_alerts) except Exception as e: logger.error(f"Failed to get metric alerts: {str(e)}") # 2. 获取日志查询告警(Scheduled Query Rules) try: scheduled_query_rules = list(monitor_client.scheduled_query_rules.list_by_subscription()) if do_debug: logger.info(f"Found {len(scheduled_query_rules)} scheduled query rules") rules.extend(scheduled_query_rules) except Exception as e: logger.error(f"Failed to get scheduled query rules: {str(e)}") # 3. 获取活动日志告警 try: activity_log_alerts = list(monitor_client.activity_log_alerts.list_by_subscription()) if do_debug: logger.info(f"Found {len(activity_log_alerts)} activity log alerts") rules.extend(activity_log_alerts) except Exception as e: logger.error(f"Failed to get activity log alerts: {str(e)}") return rules # 调用示例 # all_rules = get_all_alert_rules("your-subscription-id", do_debug=True)
对你现有代码的修改建议
- 新增活动日志告警的查询逻辑:
list(monitor_client.activity_log_alerts.list_by_subscription()) - 删除重复的日志查询规则添加逻辑(保留订阅级查询或资源组查询其一即可)
- 检查
_monitor_client_for_sub方法,确保使用DefaultAzureCredential或其他有效凭据初始化MonitorManagementClient
内容的提问来源于stack exchange,提问作者Mr. Developerdude
相关产品推荐
相关产品推荐

