|
Add this skill
npx mdskills install sickn33/azure-monitor-query-pyComprehensive reference with excellent code examples but lacks agent-specific instructions
1---2name: azure-monitor-query-py3description: |4 Azure Monitor Query SDK for Python. Use for querying Log Analytics workspaces and Azure Monitor metrics.5 Triggers: "azure-monitor-query", "LogsQueryClient", "MetricsQueryClient", "Log Analytics", "Kusto queries", "Azure metrics".6package: azure-monitor-query7---89# Azure Monitor Query SDK for Python1011Query logs and metrics from Azure Monitor and Log Analytics workspaces.1213## Installation1415```bash16pip install azure-monitor-query17```1819## Environment Variables2021```bash22# Log Analytics23AZURE_LOG_ANALYTICS_WORKSPACE_ID=<workspace-id>2425# Metrics26AZURE_METRICS_RESOURCE_URI=/subscriptions/<sub>/resourceGroups/<rg>/providers/<provider>/<type>/<name>27```2829## Authentication3031```python32from azure.identity import DefaultAzureCredential3334credential = DefaultAzureCredential()35```3637## Logs Query Client3839### Basic Query4041```python42from azure.monitor.query import LogsQueryClient43from datetime import timedelta4445client = LogsQueryClient(credential)4647query = """48AppRequests49| where TimeGenerated > ago(1h)50| summarize count() by bin(TimeGenerated, 5m), ResultCode51| order by TimeGenerated desc52"""5354response = client.query_workspace(55 workspace_id=os.environ["AZURE_LOG_ANALYTICS_WORKSPACE_ID"],56 query=query,57 timespan=timedelta(hours=1)58)5960for table in response.tables:61 for row in table.rows:62 print(row)63```6465### Query with Time Range6667```python68from datetime import datetime, timezone6970response = client.query_workspace(71 workspace_id=workspace_id,72 query="AppRequests | take 10",73 timespan=(74 datetime(2024, 1, 1, tzinfo=timezone.utc),75 datetime(2024, 1, 2, tzinfo=timezone.utc)76 )77)78```7980### Convert to DataFrame8182```python83import pandas as pd8485response = client.query_workspace(workspace_id, query, timespan=timedelta(hours=1))8687if response.tables:88 table = response.tables[0]89 df = pd.DataFrame(data=table.rows, columns=[col.name for col in table.columns])90 print(df.head())91```9293### Batch Query9495```python96from azure.monitor.query import LogsBatchQuery9798queries = [99 LogsBatchQuery(workspace_id=workspace_id, query="AppRequests | take 5", timespan=timedelta(hours=1)),100 LogsBatchQuery(workspace_id=workspace_id, query="AppExceptions | take 5", timespan=timedelta(hours=1))101]102103responses = client.query_batch(queries)104105for response in responses:106 if response.tables:107 print(f"Rows: {len(response.tables[0].rows)}")108```109110### Handle Partial Results111112```python113from azure.monitor.query import LogsQueryStatus114115response = client.query_workspace(workspace_id, query, timespan=timedelta(hours=24))116117if response.status == LogsQueryStatus.PARTIAL:118 print(f"Partial results: {response.partial_error}")119elif response.status == LogsQueryStatus.FAILURE:120 print(f"Query failed: {response.partial_error}")121```122123## Metrics Query Client124125### Query Resource Metrics126127```python128from azure.monitor.query import MetricsQueryClient129from datetime import timedelta130131metrics_client = MetricsQueryClient(credential)132133response = metrics_client.query_resource(134 resource_uri=os.environ["AZURE_METRICS_RESOURCE_URI"],135 metric_names=["Percentage CPU", "Network In Total"],136 timespan=timedelta(hours=1),137 granularity=timedelta(minutes=5)138)139140for metric in response.metrics:141 print(f"{metric.name}:")142 for time_series in metric.timeseries:143 for data in time_series.data:144 print(f" {data.timestamp}: {data.average}")145```146147### Aggregations148149```python150from azure.monitor.query import MetricAggregationType151152response = metrics_client.query_resource(153 resource_uri=resource_uri,154 metric_names=["Requests"],155 timespan=timedelta(hours=1),156 aggregations=[157 MetricAggregationType.AVERAGE,158 MetricAggregationType.MAXIMUM,159 MetricAggregationType.MINIMUM,160 MetricAggregationType.COUNT161 ]162)163```164165### Filter by Dimension166167```python168response = metrics_client.query_resource(169 resource_uri=resource_uri,170 metric_names=["Requests"],171 timespan=timedelta(hours=1),172 filter="ApiName eq 'GetBlob'"173)174```175176### List Metric Definitions177178```python179definitions = metrics_client.list_metric_definitions(resource_uri)180for definition in definitions:181 print(f"{definition.name}: {definition.unit}")182```183184### List Metric Namespaces185186```python187namespaces = metrics_client.list_metric_namespaces(resource_uri)188for ns in namespaces:189 print(ns.fully_qualified_namespace)190```191192## Async Clients193194```python195from azure.monitor.query.aio import LogsQueryClient, MetricsQueryClient196from azure.identity.aio import DefaultAzureCredential197198async def query_logs():199 credential = DefaultAzureCredential()200 client = LogsQueryClient(credential)201202 response = await client.query_workspace(203 workspace_id=workspace_id,204 query="AppRequests | take 10",205 timespan=timedelta(hours=1)206 )207208 await client.close()209 await credential.close()210 return response211```212213## Common Kusto Queries214215```kusto216// Requests by status code217AppRequests218| summarize count() by ResultCode219| order by count_ desc220221// Exceptions over time222AppExceptions223| summarize count() by bin(TimeGenerated, 1h)224225// Slow requests226AppRequests227| where DurationMs > 1000228| project TimeGenerated, Name, DurationMs229| order by DurationMs desc230231// Top errors232AppExceptions233| summarize count() by ExceptionType234| top 10 by count_235```236237## Client Types238239| Client | Purpose |240|--------|---------|241| `LogsQueryClient` | Query Log Analytics workspaces |242| `MetricsQueryClient` | Query Azure Monitor metrics |243244## Best Practices2452461. **Use timedelta** for relative time ranges2472. **Handle partial results** for large queries2483. **Use batch queries** when running multiple queries2494. **Set appropriate granularity** for metrics to reduce data points2505. **Convert to DataFrame** for easier data analysis2516. **Use aggregations** to summarize metric data2527. **Filter by dimensions** to narrow metric results253
Full transparency — inspect the skill content before installing.