CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-azure-mgmt-monitor

Microsoft Azure Monitor Client Library for Python

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

metric-alerts.mddocs/

Metric Alerts and Monitoring

Metric alerts monitor resource metrics and trigger actions when thresholds are exceeded. This module supports static and dynamic thresholds, multi-resource alerts, and comprehensive alert status monitoring for proactive resource management.

Capabilities

Metric Alert Management

Create, update, and manage metric alert rules with support for static and dynamic thresholds.

def create_or_update(resource_group_name: str, rule_name: str, parameters: MetricAlertResource, **kwargs: Any) -> MetricAlertResource:
    """
    Create or update a metric alert rule.
    
    Parameters:
    - resource_group_name: str - Name of the resource group
    - rule_name: str - Name of the alert rule
    - parameters: MetricAlertResource - Alert rule configuration
    
    Returns:
    MetricAlertResource - The created or updated alert rule
    """

def get(resource_group_name: str, rule_name: str, **kwargs: Any) -> MetricAlertResource:
    """
    Retrieve an alert rule.
    
    Parameters:
    - resource_group_name: str - Name of the resource group
    - rule_name: str - Name of the alert rule
    
    Returns:
    MetricAlertResource - The alert rule details
    """

def delete(resource_group_name: str, rule_name: str, **kwargs: Any) -> None:
    """
    Delete an alert rule.
    
    Parameters:
    - resource_group_name: str - Name of the resource group
    - rule_name: str - Name of the alert rule
    """

def update(resource_group_name: str, rule_name: str, parameters: MetricAlertResourcePatch, **kwargs: Any) -> MetricAlertResource:
    """
    Update an alert rule.
    
    Parameters:
    - resource_group_name: str - Name of the resource group
    - rule_name: str - Name of the alert rule
    - parameters: MetricAlertResourcePatch - Properties to update
    
    Returns:
    MetricAlertResource - The updated alert rule
    """

Metric Alert Listing

List metric alert rules within subscriptions and resource groups.

def list_by_subscription(**kwargs: Any) -> ItemPaged[MetricAlertResource]:
    """
    Retrieve alert rules for a subscription.
    
    Returns:
    ItemPaged[MetricAlertResource] - Paginated list of alert rules
    """

def list_by_resource_group(resource_group_name: str, **kwargs: Any) -> ItemPaged[MetricAlertResource]:
    """
    Retrieve alert rules for a resource group.
    
    Parameters:
    - resource_group_name: str - Name of the resource group
    
    Returns:
    ItemPaged[MetricAlertResource] - Paginated list of alert rules
    """

Alert Status Monitoring

Monitor the status of metric alert instances and retrieve detailed status information.

def list(resource_group_name: str, rule_name: str, **kwargs: Any) -> MetricAlertStatusCollection:
    """
    Retrieve an alert rule status collection.
    
    Parameters:
    - resource_group_name: str - Name of the resource group
    - rule_name: str - Name of the alert rule
    
    Returns:
    MetricAlertStatusCollection - Alert status information
    """

def list_by_name(resource_group_name: str, rule_name: str, status_name: str, **kwargs: Any) -> MetricAlertStatusCollection:
    """
    Retrieve an alert rule status by name.
    
    Parameters:
    - resource_group_name: str - Name of the resource group
    - rule_name: str - Name of the alert rule
    - status_name: str - Name of the status
    
    Returns:
    MetricAlertStatusCollection - Specific alert status information
    """

Usage Examples

Creating a Static Threshold Alert

from azure.mgmt.monitor.models import (
    MetricAlertResource, MetricAlertSingleResourceMultipleMetricCriteria,
    MetricCriteria, MetricAlertAction
)

# Define alert criteria for high CPU usage
criteria = MetricAlertSingleResourceMultipleMetricCriteria(
    all_of=[
        MetricCriteria(
            name="HighCPU",
            metric_name="Percentage CPU",
            metric_namespace="Microsoft.Compute/virtualMachines",
            operator="GreaterThan",
            threshold=80.0,
            time_aggregation="Average"
        )
    ]
)

# Define actions
actions = [
    MetricAlertAction(
        action_group_id=f"/subscriptions/{subscription_id}/resourceGroups/monitoring-rg/providers/Microsoft.Insights/actionGroups/admin-alerts"
    )
]

# Create metric alert
alert_rule = MetricAlertResource(
    location="global",
    description="Alert when CPU exceeds 80%",
    enabled=True,
    scopes=[f"/subscriptions/{subscription_id}/resourceGroups/production-rg/providers/Microsoft.Compute/virtualMachines/web-server"],
    evaluation_frequency="PT1M",  # Evaluate every minute
    window_size="PT5M",  # 5-minute window
    criteria=criteria,
    actions=actions,
    severity=2  # Warning severity
)

result = client.metric_alerts.create_or_update(
    resource_group_name="monitoring-rg",
    rule_name="high-cpu-alert",
    parameters=alert_rule
)

Creating a Dynamic Threshold Alert

from azure.mgmt.monitor.models import (
    MetricAlertMultipleResourceMultipleMetricCriteria,
    DynamicMetricCriteria, DynamicThresholdFailingPeriods
)

# Define dynamic threshold criteria
failing_periods = DynamicThresholdFailingPeriods(
    number_of_evaluation_periods=4,
    min_failing_periods_to_alert=3
)

dynamic_criteria = MetricAlertMultipleResourceMultipleMetricCriteria(
    all_of=[
        DynamicMetricCriteria(
            name="AbnormalRequestRate",
            metric_name="Requests/Sec",
            metric_namespace="Microsoft.Web/sites",
            operator="GreaterOrLessThan",
            time_aggregation="Average",
            alert_sensitivity="Medium",
            failing_periods=failing_periods,
            ignore_data_before=datetime.utcnow() - timedelta(days=7)
        )
    ]
)

# Create dynamic threshold alert
dynamic_alert = MetricAlertResource(
    location="global",
    description="Dynamic alert for abnormal request patterns",
    enabled=True,
    scopes=[f"/subscriptions/{subscription_id}/resourceGroups/web-apps-rg"],
    evaluation_frequency="PT1M",
    window_size="PT15M",
    criteria=dynamic_criteria,
    actions=actions,
    severity=1  # Error severity
)

Multi-Resource Alert

# Create alert that monitors multiple resources
multi_resource_scopes = [
    f"/subscriptions/{subscription_id}/resourceGroups/web-rg/providers/Microsoft.Web/sites/app1",
    f"/subscriptions/{subscription_id}/resourceGroups/web-rg/providers/Microsoft.Web/sites/app2",
    f"/subscriptions/{subscription_id}/resourceGroups/web-rg/providers/Microsoft.Web/sites/app3"
]

multi_criteria = MetricAlertMultipleResourceMultipleMetricCriteria(
    all_of=[
        MetricCriteria(
            name="HighResponseTime",
            metric_name="AverageResponseTime", 
            metric_namespace="Microsoft.Web/sites",
            operator="GreaterThan",
            threshold=2.0,
            time_aggregation="Average"
        )
    ]
)

multi_alert = MetricAlertResource(
    location="global",
    description="Multi-resource response time alert",
    enabled=True,
    scopes=multi_resource_scopes,
    evaluation_frequency="PT5M",
    window_size="PT15M", 
    criteria=multi_criteria,
    actions=actions,
    severity=2
)

Checking Alert Status

# Get alert status
status_collection = client.metric_alerts_status.list(
    resource_group_name="monitoring-rg",
    rule_name="high-cpu-alert"
)

for status_item in status_collection.value:
    print(f"Status: {status_item.status}")
    print(f"Timestamp: {status_item.timestamp}")
    if status_item.dimensions:
        print(f"Dimensions: {status_item.dimensions}")

Types

class MetricAlertResource:
    """Metric alert rule resource."""
    location: str  # Resource location (typically "global")
    description: Optional[str]  # Alert description
    enabled: bool  # Whether alert is enabled
    scopes: List[str]  # Resources to monitor (resource IDs)
    evaluation_frequency: str  # How often to evaluate (ISO 8601 duration)
    window_size: str  # Time window for evaluation (ISO 8601 duration)
    criteria: MetricAlertCriteria  # Alert criteria
    actions: Optional[List[MetricAlertAction]]  # Actions when alert fires
    severity: int  # Alert severity (0=Critical, 1=Error, 2=Warning, 3=Informational, 4=Verbose)
    auto_mitigate: Optional[bool]  # Auto-resolve when condition no longer met
    target_resource_type: Optional[str]  # Target resource type for multi-resource alerts
    target_resource_region: Optional[str]  # Target resource region for multi-resource alerts

class MetricAlertCriteria:
    """Base class for metric alert criteria."""
    pass

class MetricAlertSingleResourceMultipleMetricCriteria(MetricAlertCriteria):
    """Criteria for single resource with multiple metrics."""
    all_of: List[MetricCriteria]  # All criteria must be met (AND logic)

class MetricAlertMultipleResourceMultipleMetricCriteria(MetricAlertCriteria):
    """Criteria for multiple resources with multiple metrics."""
    all_of: List[MultiMetricCriteria]  # All criteria must be met (AND logic)

class MetricCriteria:
    """Static threshold metric criteria."""
    name: str  # Criteria name
    metric_name: str  # Metric name to monitor
    metric_namespace: str  # Metric namespace
    operator: ComparisonOperationType  # Comparison operator
    threshold: float  # Threshold value
    time_aggregation: AggregationType  # Time aggregation method
    dimensions: Optional[List[MetricDimension]]  # Metric dimensions to filter
    skip_metric_validation: Optional[bool]  # Skip metric validation

class DynamicMetricCriteria(MultiMetricCriteria):
    """Dynamic threshold metric criteria."""
    name: str  # Criteria name
    metric_name: str  # Metric name to monitor
    metric_namespace: str  # Metric namespace
    operator: DynamicThresholdOperator  # Dynamic threshold operator
    time_aggregation: AggregationType  # Time aggregation method
    alert_sensitivity: DynamicThresholdSensitivity  # Sensitivity level
    failing_periods: DynamicThresholdFailingPeriods  # Failing period configuration
    ignore_data_before: Optional[datetime]  # Ignore data before this date
    dimensions: Optional[List[MetricDimension]]  # Metric dimensions to filter

class MetricAlertAction:
    """Action to execute when alert fires."""
    action_group_id: str  # Action group resource ID
    webhook_properties: Optional[Dict[str, str]]  # Custom webhook properties

class MetricAlertStatusCollection:
    """Collection of metric alert statuses."""
    value: Optional[List[MetricAlertStatus]]  # Alert status list

class MetricAlertStatus:
    """Metric alert status information."""
    name: Optional[str]  # Status name
    id: Optional[str]  # Status ID
    type: Optional[str]  # Status type
    properties: Optional[MetricAlertStatusProperties]  # Status properties

class MetricAlertStatusProperties:
    """Metric alert status properties."""
    dimensions: Optional[Dict[str, str]]  # Alert dimensions
    status: Optional[str]  # Alert status
    timestamp: Optional[datetime]  # Status timestamp

class MetricDimension:
    """Metric dimension filter."""
    name: str  # Dimension name
    operator: str  # Filter operator
    values: List[str]  # Dimension values

class DynamicThresholdFailingPeriods:
    """Dynamic threshold failing period configuration."""
    number_of_evaluation_periods: float  # Number of evaluation periods
    min_failing_periods_to_alert: float  # Minimum failing periods to trigger alert

ComparisonOperationType = Union["Equals", "NotEquals", "GreaterThan", "GreaterThanOrEqual", "LessThan", "LessThanOrEqual"]
DynamicThresholdOperator = Union["GreaterThan", "LessThan", "GreaterOrLessThan"]
DynamicThresholdSensitivity = Union["Low", "Medium", "High"]
AggregationType = Union["Average", "Minimum", "Maximum", "Total", "Count"]

Install with Tessl CLI

npx tessl i tessl/pypi-azure-mgmt-monitor

docs

action-groups.md

activity-logs.md

autoscaling.md

data-collection.md

index.md

log-analytics.md

metric-alerts.md

metrics.md

workspaces.md

tile.json