Microsoft Azure Monitor Client Library for Python
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Azure Activity Logs provide subscription-level administrative and operational events. This module enables querying activity logs, managing activity log alert rules, and accessing tenant-level activity logs for comprehensive monitoring of Azure resource operations.
Retrieve activity log events with filtering and selection capabilities for subscription-level monitoring.
def list(filter: str, select: Optional[str] = None, **kwargs: Any) -> ItemPaged[EventData]:
"""
Provides the list of records from the activity logs with optional filtering and selection.
Parameters:
- filter: str - OData filter for activity log events (required)
- select: Optional[str] - OData select clause for specific properties
Returns:
ItemPaged[EventData] - Paginated collection of activity log events
"""Create and manage alert rules that trigger on specific activity log events and administrative operations.
def create_or_update(resource_group_name: str, activity_log_alert_name: str, activity_log_alert_rule: ActivityLogAlertResource, **kwargs: Any) -> ActivityLogAlertResource:
"""
Create or update an Activity Log Alert rule.
Parameters:
- resource_group_name: str - Name of the resource group
- activity_log_alert_name: str - Name of the alert rule
- activity_log_alert_rule: ActivityLogAlertResource - Alert rule configuration
Returns:
ActivityLogAlertResource - The created or updated alert rule
"""
def get(resource_group_name: str, activity_log_alert_name: str, **kwargs: Any) -> ActivityLogAlertResource:
"""
Get an Activity Log Alert rule.
Parameters:
- resource_group_name: str - Name of the resource group
- activity_log_alert_name: str - Name of the alert rule
Returns:
ActivityLogAlertResource - The alert rule details
"""
def delete(resource_group_name: str, activity_log_alert_name: str, **kwargs: Any) -> None:
"""
Delete an Activity Log Alert rule.
Parameters:
- resource_group_name: str - Name of the resource group
- activity_log_alert_name: str - Name of the alert rule
"""
def update(resource_group_name: str, activity_log_alert_name: str, activity_log_alert_rule_patch: AlertRulePatchObject, **kwargs: Any) -> ActivityLogAlertResource:
"""
Update an Activity Log Alert rule.
Parameters:
- resource_group_name: str - Name of the resource group
- activity_log_alert_name: str - Name of the alert rule
- activity_log_alert_rule_patch: AlertRulePatchObject - Properties to update
Returns:
ActivityLogAlertResource - The updated alert rule
"""List activity log alert rules within subscriptions and resource groups.
def list_by_subscription_id(**kwargs: Any) -> ItemPaged[ActivityLogAlertResource]:
"""
Get a list of all Activity Log Alert rules in a subscription.
Returns:
ItemPaged[ActivityLogAlertResource] - Paginated list of alert rules
"""
def list_by_resource_group(resource_group_name: str, **kwargs: Any) -> ItemPaged[ActivityLogAlertResource]:
"""
Get a list of all Activity Log Alert rules in a resource group.
Parameters:
- resource_group_name: str - Name of the resource group
Returns:
ItemPaged[ActivityLogAlertResource] - Paginated list of alert rules
"""Access tenant-level activity logs for organization-wide administrative operations.
def list(filter: Optional[str] = None, select: Optional[str] = None, **kwargs: Any) -> ItemPaged[EventData]:
"""
Gets the Activity Logs for the Tenant with optional OData filter.
Parameters:
- filter: Optional[str] - OData filter for tenant activity log events
- select: Optional[str] - OData select clause for specific properties
Returns:
ItemPaged[EventData] - Paginated collection of tenant activity log events
"""Retrieve available event categories for activity log filtering.
def list(**kwargs: Any) -> ItemPaged[LocalizableString]:
"""
Get the list of available event categories supported in the Activity Logs Service.
Returns:
ItemPaged[LocalizableString] - Available event categories
"""Manage and retrieve incidents for classic alert rules. Incidents represent the activation status of alert rules.
def get(resource_group_name: str, rule_name: str, incident_name: str, **kwargs: Any) -> Incident:
"""
Gets an incident associated to an alert rule.
Parameters:
- resource_group_name: str - Name of the resource group
- rule_name: str - Name of the alert rule
- incident_name: str - Name of the incident to retrieve
Returns:
Incident - The incident details
"""
def list_by_alert_rule(resource_group_name: str, rule_name: str, **kwargs: Any) -> ItemPaged[Incident]:
"""
Gets a list of incidents associated to an alert rule.
Parameters:
- resource_group_name: str - Name of the resource group
- rule_name: str - Name of the alert rule
Returns:
ItemPaged[Incident] - Paginated list of incidents for the alert rule
"""from datetime import datetime, timedelta
# Query activity logs for the last 24 hours
end_time = datetime.utcnow()
start_time = end_time - timedelta(days=1)
filter_expression = f"eventTimestamp ge '{start_time.isoformat()}Z' and eventTimestamp le '{end_time.isoformat()}Z'"
activity_events = client.activity_logs.list(
filter=filter_expression,
select="eventName,operationName,resourceGroupName,status"
)
for event in activity_events:
print(f"Operation: {event.operation_name}, Status: {event.status}")from azure.mgmt.monitor.models import (
ActivityLogAlertResource, AlertRuleAllOfCondition,
AlertRuleAnyOfOrLeafCondition, AlertRuleLeafCondition
)
# Define alert conditions for VM deletion
conditions = AlertRuleAllOfCondition(
all_of=[
AlertRuleLeafCondition(
field="category",
equals="Administrative"
),
AlertRuleLeafCondition(
field="operationName",
equals="Microsoft.Compute/virtualMachines/delete"
)
]
)
# Create activity log alert
alert_rule = ActivityLogAlertResource(
location="global",
scopes=[f"/subscriptions/{subscription_id}"],
condition=conditions,
actions={
"action_groups": [f"/subscriptions/{subscription_id}/resourceGroups/monitoring-rg/providers/microsoft.insights/actionGroups/admin-alerts"]
},
enabled=True,
description="Alert when VMs are deleted"
)
result = client.activity_log_alerts.create_or_update(
resource_group_name="monitoring-rg",
activity_log_alert_name="vm-deletion-alert",
activity_log_alert_rule=alert_rule
)# Query for specific resource operations
resource_group = "production-rg"
filter_expression = f"resourceGroupName eq '{resource_group}' and operationName.value eq 'Microsoft.Compute/virtualMachines/write'"
events = client.activity_logs.list(filter=filter_expression)
for event in events:
print(f"Resource: {event.resource_id}, Time: {event.event_timestamp}")class EventData:
"""Activity log event data."""
authorization: Optional[SenderAuthorization] # Authorization information
caller: Optional[str] # Caller identity
category: Optional[LocalizableString] # Event category
correlation_id: Optional[str] # Correlation identifier
description: Optional[str] # Event description
event_data_id: Optional[str] # Event data identifier
event_name: Optional[LocalizableString] # Event name
event_timestamp: Optional[datetime] # Event timestamp
http_request: Optional[HttpRequestInfo] # HTTP request info for API calls
level: Optional[EventLevel] # Event level (Critical, Error, Warning, Informational)
operation_id: Optional[str] # Operation identifier
operation_name: Optional[LocalizableString] # Operation name
resource_group_name: Optional[str] # Resource group name
resource_id: Optional[str] # Resource identifier
resource_provider_name: Optional[LocalizableString] # Resource provider
resource_type: Optional[LocalizableString] # Resource type
status: Optional[LocalizableString] # Operation status
sub_status: Optional[LocalizableString] # Operation sub-status
subscription_id: Optional[str] # Subscription identifier
tenant_id: Optional[str] # Tenant identifier
class ActivityLogAlertResource:
"""Activity log alert rule resource."""
location: str # Resource location
scopes: List[str] # Alert rule scopes (subscription/resource group IDs)
condition: AlertRuleAllOfCondition # Alert conditions
actions: Actions # Actions to take when alert fires
enabled: Optional[bool] # Whether alert is enabled
description: Optional[str] # Alert description
class AlertRuleAllOfCondition:
"""Alert rule condition requiring all criteria to match."""
all_of: List[AlertRuleAnyOfOrLeafCondition] # List of conditions (AND logic)
class AlertRuleLeafCondition:
"""Individual alert rule condition."""
field: str # Field name to evaluate
equals: Optional[str] # Equals comparison value
contains_any: Optional[List[str]] # Contains any of these values
class Actions:
"""Actions to execute when alert fires."""
action_groups: Optional[List[str]] # Action group resource IDs
class SenderAuthorization:
"""Authorization details for the operation."""
action: Optional[str] # Authorized action
role: Optional[str] # Authorization role
scope: Optional[str] # Authorization scope
class HttpRequestInfo:
"""HTTP request information for API operations."""
client_request_id: Optional[str] # Client request identifier
client_ip_address: Optional[str] # Client IP address
method: Optional[str] # HTTP method
uri: Optional[str] # Request URI
class LocalizableString:
"""Localizable string value."""
value: str # String value
localized_value: Optional[str] # Localized string value
class Incident:
"""Alert rule incident representing activation status."""
name: Optional[str] # Incident name
rule_name: Optional[str] # Associated alert rule name
is_active: Optional[bool] # Whether incident is currently active
activated_time: Optional[datetime] # When incident was activated
resolved_time: Optional[datetime] # When incident was resolved
EventLevel = Union["Critical", "Error", "Warning", "Informational", "Verbose"] # Event severity levelsInstall with Tessl CLI
npx tessl i tessl/pypi-azure-mgmt-monitor