azure-monitor-query-py

Azure Monitor Query SDK for Python. Use for querying Log Analytics workspaces and Azure Monitor metrics.

31,392 stars
Complexity: medium

About this skill

This skill empowers AI agents to interact directly with Azure Monitor and Log Analytics workspaces using the Azure Monitor Query SDK for Python. It allows agents to retrieve log data through Kusto Query Language (KQL) and fetch various Azure Monitor metrics, providing real-time insights into resource performance, health, and operational data. The skill handles authentication via Azure Identity's `DefaultAzureCredential` and requires configuration of workspace IDs or resource URIs as environment variables. It's ideal for agents needing to perform diagnostics, generate reports, automate responses, or conduct security investigations based on Azure operational data.

Best use case

**Monitoring and Diagnostics**: Allow an AI agent to check the health and performance of Azure resources by querying metrics and logs in real-time. **Automated Reporting**: Enable an agent to generate reports on Azure resource usage, security events, or application performance by fetching relevant data. **Alerting and Incident Response**: Empower an agent to investigate the root cause of alerts by querying logs and metrics when an issue is detected, facilitating faster resolution. **Security Investigations**: Query security logs from Azure Sentinel/Log Analytics to identify potential threats, anomalies, or compliance breaches. **Cost Management Insights**: Retrieve consumption or usage data from Log Analytics to assist in analyzing and optimizing Azure spending.

Azure Monitor Query SDK for Python. Use for querying Log Analytics workspaces and Azure Monitor metrics.

Successfully executed Kusto queries returning structured log data from Log Analytics workspaces. Retrieval of specific Azure Monitor metrics (e.g., CPU usage, network in/out, database DTUs) for specified resources over defined timeframes. An AI agent capable of providing accurate, data-driven answers or initiating actions based on up-to-date Azure operational insights. Improved diagnostic capabilities and automated data collection for AI agents managing Azure environments. The ability for the agent to present complex monitoring data in a digestible format or use it as input for further analysis.

Practical example

Example input

{"query_type": "logs", "workspace_id": "YOUR_LOG_ANALYTICS_WORKSPACE_ID", "kusto_query": "AzureActivity | where CategoryValue == 'Administrative' and ActivityStatus == 'Succeeded' | summarize Count=count() by OperationName"}
{"query_type": "metrics", "resource_uri": "/subscriptions/<subscriptionId>/resourceGroups/<resourceGroupName>/providers/Microsoft.Web/sites/<appName>", "metric_name": "CpuTime", "timespan": "PT1H", "interval": "PT5M", "aggregation": "Average,Maximum"}

Example output

{"status": "success", "data": [{"OperationName": "Microsoft.Resources/subscriptions/resourcegroups/write", "Count": 15}, {"OperationName": "Microsoft.Compute/virtualMachines/start/action", "Count": 3}], "query_details": {"query_executed": "AzureActivity | where CategoryValue == 'Administrative' and ActivityStatus == 'Succeeded' | summarize Count=count() by OperationName", "rows_returned": 2}}
{"status": "success", "data": [{"timestamp": "2024-01-01T00:00:00Z", "Average": 5.2, "Maximum": 7.1}, {"timestamp": "2024-01-01T00:05:00Z", "Average": 4.8, "Maximum": 6.5}], "metric_details": {"name": "CpuTime", "unit": "Seconds", "timespan": "PT1H", "interval": "PT5M", "aggregation": "Average,Maximum"}}

When to use this skill

  • When an AI agent needs to programmatically retrieve operational data (logs, metrics) from Azure Monitor or Log Analytics workspaces.
  • When automating tasks that require insights into Azure resource performance, events, or security posture.
  • When integrating Azure monitoring data into custom dashboards, internal tools, or AI-driven analytics platforms via an agent.
  • When an agent needs to perform diagnostic queries in response to user requests, system alerts, or scheduled checks.

When not to use this skill

  • When the agent's task does not involve interacting with Azure Monitor or Log Analytics.
  • When only historical data archives are needed, rather than real-time or near real-time operational data.
  • If direct access to the Azure management plane (e.g., creating resources, managing policies) is required, as this skill focuses solely on querying monitoring data.
  • When a pre-built Azure portal dashboard, existing alerting rule, or a simpler REST API call sufficiently covers the monitoring need without complex agent intervention.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/azure-monitor-query-py/SKILL.md --create-dirs "https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/main/plugins/antigravity-awesome-skills-claude/skills/azure-monitor-query-py/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/azure-monitor-query-py/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How azure-monitor-query-py Compares

Feature / Agentazure-monitor-query-pyStandard Approach
Platform SupportClaudeLimited / Varies
Context Awareness High Baseline
Installation ComplexitymediumN/A

Frequently Asked Questions

What does this skill do?

Azure Monitor Query SDK for Python. Use for querying Log Analytics workspaces and Azure Monitor metrics.

Which AI agents support this skill?

This skill is designed for Claude.

How difficult is it to install?

The installation complexity is rated as medium. You can find the installation instructions above.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

# Azure Monitor Query SDK for Python

Query logs and metrics from Azure Monitor and Log Analytics workspaces.

## Installation

```bash
pip install azure-monitor-query
```

## Environment Variables

```bash
# Log Analytics
AZURE_LOG_ANALYTICS_WORKSPACE_ID=<workspace-id>

# Metrics
AZURE_METRICS_RESOURCE_URI=/subscriptions/<sub>/resourceGroups/<rg>/providers/<provider>/<type>/<name>
```

## Authentication

```python
from azure.identity import DefaultAzureCredential

credential = DefaultAzureCredential()
```

## Logs Query Client

### Basic Query

```python
from azure.monitor.query import LogsQueryClient
from datetime import timedelta

client = LogsQueryClient(credential)

query = """
AppRequests
| where TimeGenerated > ago(1h)
| summarize count() by bin(TimeGenerated, 5m), ResultCode
| order by TimeGenerated desc
"""

response = client.query_workspace(
    workspace_id=os.environ["AZURE_LOG_ANALYTICS_WORKSPACE_ID"],
    query=query,
    timespan=timedelta(hours=1)
)

for table in response.tables:
    for row in table.rows:
        print(row)
```

### Query with Time Range

```python
from datetime import datetime, timezone

response = client.query_workspace(
    workspace_id=workspace_id,
    query="AppRequests | take 10",
    timespan=(
        datetime(2024, 1, 1, tzinfo=timezone.utc),
        datetime(2024, 1, 2, tzinfo=timezone.utc)
    )
)
```

### Convert to DataFrame

```python
import pandas as pd

response = client.query_workspace(workspace_id, query, timespan=timedelta(hours=1))

if response.tables:
    table = response.tables[0]
    df = pd.DataFrame(data=table.rows, columns=[col.name for col in table.columns])
    print(df.head())
```

### Batch Query

```python
from azure.monitor.query import LogsBatchQuery

queries = [
    LogsBatchQuery(workspace_id=workspace_id, query="AppRequests | take 5", timespan=timedelta(hours=1)),
    LogsBatchQuery(workspace_id=workspace_id, query="AppExceptions | take 5", timespan=timedelta(hours=1))
]

responses = client.query_batch(queries)

for response in responses:
    if response.tables:
        print(f"Rows: {len(response.tables[0].rows)}")
```

### Handle Partial Results

```python
from azure.monitor.query import LogsQueryStatus

response = client.query_workspace(workspace_id, query, timespan=timedelta(hours=24))

if response.status == LogsQueryStatus.PARTIAL:
    print(f"Partial results: {response.partial_error}")
elif response.status == LogsQueryStatus.FAILURE:
    print(f"Query failed: {response.partial_error}")
```

## Metrics Query Client

### Query Resource Metrics

```python
from azure.monitor.query import MetricsQueryClient
from datetime import timedelta

metrics_client = MetricsQueryClient(credential)

response = metrics_client.query_resource(
    resource_uri=os.environ["AZURE_METRICS_RESOURCE_URI"],
    metric_names=["Percentage CPU", "Network In Total"],
    timespan=timedelta(hours=1),
    granularity=timedelta(minutes=5)
)

for metric in response.metrics:
    print(f"{metric.name}:")
    for time_series in metric.timeseries:
        for data in time_series.data:
            print(f"  {data.timestamp}: {data.average}")
```

### Aggregations

```python
from azure.monitor.query import MetricAggregationType

response = metrics_client.query_resource(
    resource_uri=resource_uri,
    metric_names=["Requests"],
    timespan=timedelta(hours=1),
    aggregations=[
        MetricAggregationType.AVERAGE,
        MetricAggregationType.MAXIMUM,
        MetricAggregationType.MINIMUM,
        MetricAggregationType.COUNT
    ]
)
```

### Filter by Dimension

```python
response = metrics_client.query_resource(
    resource_uri=resource_uri,
    metric_names=["Requests"],
    timespan=timedelta(hours=1),
    filter="ApiName eq 'GetBlob'"
)
```

### List Metric Definitions

```python
definitions = metrics_client.list_metric_definitions(resource_uri)
for definition in definitions:
    print(f"{definition.name}: {definition.unit}")
```

### List Metric Namespaces

```python
namespaces = metrics_client.list_metric_namespaces(resource_uri)
for ns in namespaces:
    print(ns.fully_qualified_namespace)
```

## Async Clients

```python
from azure.monitor.query.aio import LogsQueryClient, MetricsQueryClient
from azure.identity.aio import DefaultAzureCredential

async def query_logs():
    credential = DefaultAzureCredential()
    client = LogsQueryClient(credential)
    
    response = await client.query_workspace(
        workspace_id=workspace_id,
        query="AppRequests | take 10",
        timespan=timedelta(hours=1)
    )
    
    await client.close()
    await credential.close()
    return response
```

## Common Kusto Queries

```kusto
// Requests by status code
AppRequests
| summarize count() by ResultCode
| order by count_ desc

// Exceptions over time
AppExceptions
| summarize count() by bin(TimeGenerated, 1h)

// Slow requests
AppRequests
| where DurationMs > 1000
| project TimeGenerated, Name, DurationMs
| order by DurationMs desc

// Top errors
AppExceptions
| summarize count() by ExceptionType
| top 10 by count_
```

## Client Types

| Client | Purpose |
|--------|---------|
| `LogsQueryClient` | Query Log Analytics workspaces |
| `MetricsQueryClient` | Query Azure Monitor metrics |

## Best Practices

1. **Use timedelta** for relative time ranges
2. **Handle partial results** for large queries
3. **Use batch queries** when running multiple queries
4. **Set appropriate granularity** for metrics to reduce data points
5. **Convert to DataFrame** for easier data analysis
6. **Use aggregations** to summarize metric data
7. **Filter by dimensions** to narrow metric results

## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

Related Skills

azure-resource-manager-sql-dotnet

31392
from sickn33/antigravity-awesome-skills

Azure Resource Manager SDK for Azure SQL in .NET.

Cloud ManagementClaudeGitHub CopilotCursor

azure-resource-manager-redis-dotnet

31392
from sickn33/antigravity-awesome-skills

Azure Resource Manager SDK for Redis in .NET.

Cloud ManagementClaude

azure-resource-manager-postgresql-dotnet

31392
from sickn33/antigravity-awesome-skills

Azure PostgreSQL Flexible Server SDK for .NET. Database management for PostgreSQL Flexible Server deployments.

Cloud ManagementClaude

azure-resource-manager-mysql-dotnet

31392
from sickn33/antigravity-awesome-skills

Azure MySQL Flexible Server SDK for .NET. Database management for MySQL Flexible Server deployments.

Cloud ManagementClaude

azure-resource-manager-cosmosdb-dotnet

31392
from sickn33/antigravity-awesome-skills

Azure Resource Manager SDK for Cosmos DB in .NET.

Cloud ManagementClaude

azure-mgmt-weightsandbiases-dotnet

31392
from sickn33/antigravity-awesome-skills

Azure Weights & Biases SDK for .NET. ML experiment tracking and model management via Azure Marketplace. Use for creating W&B instances, managing SSO, marketplace integration, and ML observability.

Cloud ManagementClaude

azure-mgmt-botservice-py

31392
from sickn33/antigravity-awesome-skills

Azure Bot Service Management SDK for Python. Use for creating, managing, and configuring Azure Bot Service resources.

Cloud ManagementClaudeChatGPTGemini

azure-mgmt-botservice-dotnet

31392
from sickn33/antigravity-awesome-skills

Azure Resource Manager SDK for Bot Service in .NET. Management plane operations for creating and managing Azure Bot resources, channels (Teams, DirectLine, Slack), and connection settings.

Cloud ManagementClaude

azure-mgmt-apicenter-py

31392
from sickn33/antigravity-awesome-skills

Azure API Center Management SDK for Python. Use for managing API inventory, metadata, and governance across your organization.

Cloud ManagementClaude

azure-containerregistry-py

31392
from sickn33/antigravity-awesome-skills

Azure Container Registry SDK for Python. Use for managing container images, artifacts, and repositories.

Cloud ManagementClaude

azure-keyvault-certificates-rust

31355
from sickn33/antigravity-awesome-skills

Azure Key Vault Certificates SDK for Rust. Use for creating, importing, and managing certificates.

Cloud ManagementClaude

cost-optimization

31392
from sickn33/antigravity-awesome-skills

Strategies and patterns for optimizing cloud costs across AWS, Azure, and GCP.

Cloud ManagementClaude