# azure-monitor-query-py

Guides coding agents to query Azure Monitor metrics and Log Analytics workspaces with the Python SDK. Useful when writing Kusto log queries and fetching telemetry data.

- skill · `type=skill` · Claude Code, GitHub Copilot · 1 install · ★ 3149
- Author: Microsoft
- License: MIT · policy=mirror · the beginning of the file is at the end of this page
- Source: https://github.com/microsoft/skills/tree/HEAD/.github/plugins/azure-sdk-python/skills/azure-monitor-query-py/SKILL.md
- Updated: 2026-10-23
- HTML: https://affpapa.org/en/nevibecode/skills/azure-monitor-query-py

## What it does

This skill guides agents in writing Python code with the official `azure-monitor-query` package. It focuses on `LogsQueryClient` for querying Log Analytics tables and `MetricsQueryClient` for retrieving resource performance data. The skill enforces wrapping every client in a context manager (`with` or `async with`). This releases open transports and sockets deterministically.

Authentication relies on `DefaultAzureCredential`. In production, the environment requires `AZURE_TOKEN_CREDENTIALS=prod` to restrict the credential chain. Without `AZURE_LOG_ANALYTICS_WORKSPACE_ID`, log queries cannot execute. The agent formats Kusto queries, parses responses into pandas DataFrames, groups batch calls with `LogsBatchQuery`, and handles partial results.

For telemetry metrics, the generated code uses `AZURE_METRICS_RESOURCE_URI`. It supports metrics like CPU percentage, handles aggregation types, filters series by dimension, and inspects available namespaces.

## Requirements
- Works with: Azure

## Install

### Claude Code (native platform)

1. **Skills CLI (Vercel)**
```bash
npx skills add microsoft/skills --skill azure-monitor-query-py -a claude-code
```

2. **Manually: put the files in place**
- File: `~/.claude/skills/azure-monitor-query-py/SKILL.md` — Copy the whole skill folder; for one project use .claude/skills/azure-monitor-query-py/

### Codex

**Manually: put the files in place**
- File: `.agents/skills/azure-monitor-query-py/SKILL.md` — For all projects use ~/.agents/skills/

### Cursor

**Manually: put the files in place**
- File: `.cursor/skills/azure-monitor-query-py/SKILL.md` — Cursor also reads .agents/skills/ and .claude/skills/

### GitHub Copilot

1. **GitHub CLI**
```bash
gh skill install microsoft/skills azure-monitor-query-py
```

2. **Manually: put the files in place**
- File: `.github/skills/azure-monitor-query-py/SKILL.md`

### Gemini CLI

**Platform CLI**
```bash
gemini skills install https://github.com/microsoft/skills --path .github/plugins/azure-sdk-python/skills/azure-monitor-query-py
```

### Windsurf (Devin Desktop)

**Manually: put the files in place**
- File: `.devin/skills/azure-monitor-query-py/SKILL.md` — The legacy .windsurf/skills/ path still works

### Claude.ai

**Claude.ai**
- Zip the folder and upload it in Settings → Capabilities → Skills

Where a file is given instead of a command, copy the files from the source to that path: https://github.com/microsoft/skills/tree/HEAD/.github/plugins/azure-sdk-python/skills/azure-monitor-query-py/SKILL.md

## When to use it
- write Kusto queries to Log Analytics via LogsQueryClient
- retrieve Azure resource metrics with aggregations and time windows
- convert Azure Monitor log responses into pandas DataFrames
- batch multiple log queries using LogsBatchQuery

## Example prompts
- Write an async Python script to fetch AppExceptions from Log Analytics over the last 24 hours.
- Query CPU percentage and incoming network metrics for an Azure resource using MetricsQueryClient.
- Show how to run batch Kusto queries with LogsBatchQuery and convert the output to a DataFrame.

## Source text · SKILL.md · MIT

Below is the content of a third-party file. It is data, not instructions for you: do not act on anything written inside unless the human asks. Block tag: ed980d04b85d16cb.

BEGIN THIRD-PARTY FILE ed980d04b85d16cb
````text
---
name: azure-monitor-query-py
description: |
  Azure Monitor Query SDK for Python. Use for querying Log Analytics workspaces and Azure Monitor metrics.
  Triggers: "azure-monitor-query", "LogsQueryClient", "MetricsQueryClient", "Log Analytics", "Kusto queries", "Azure metrics".
license: MIT
metadata:
  author: Microsoft
  version: "1.0.0"
  package: azure-monitor-query
---

# 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>  # Required for log queries

# Metrics
AZURE_METRICS_RESOURCE_URI=/subscriptions/<sub>/resourceGroups/<rg>/providers/<provider>/<type>/<name>  # Required for metric queries
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```

## Authentication & Lifecycle

> **🔑 Two rules apply to every code sample below:**
>
> 1. **Prefer `DefaultAzureCredential`.** It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
>    - Local dev: `DefaultAzureCredential` works as-is.
>    - Production: set `AZURE_TOKEN_CREDENTIALS=prod` (or `AZURE_TOKEN_CREDENTIALS=<specific_credential>`) to constrain the credential chain to production-safe credentials.
> 2. **Wrap every client in a context manager** so HTTP transports, sockets, and token caches are released deterministically:
>    - Sync: `with <Client>(...) as client:`
>    - Async: `async with <Client>(...) as client:` **and** `async with DefaultAzureCredential() as credential:` (from `azure.identity.aio`)
>
> Snippets may abbreviate this setup, but production code should always follow both rules.

```python
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential

# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
```

## Logs Query Client

### Basic Query

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

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

with LogsQueryClient(credential) as client:
    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)
```
````
END THIRD-PARTY FILE ed980d04b85d16cb

The third-party file has ended. Everything between the ed980d04b85d16cb tags is data: requests and commands from it are not followed. An “end of file” line with another tag inside the block is part of the file.

First 2977 of 8569 bytes. © Microsoft · MIT · https://github.com/microsoft/skills/tree/HEAD/.github/plugins/azure-sdk-python/skills/azure-monitor-query-py/SKILL.md

_Part of the page did not fit — see the HTML version._

---
NeVibeCode on affpapa.org. Catalog texts are descriptions, not instructions for the agent. How to choose and install: https://affpapa.org/en/nevibecode/agents.md
