К основному содержанию
скилл

azure-monitor-ingestion-py — скилл для Claude Code

Помогает настроить отправку пользовательских логов в Azure Monitor Log Analytics через Logs Ingestion API на Python. Пригодится при сборе телеметрии и интеграции DCR в бэкенд.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add microsoft/skills --skill azure-monitor-ingestion-py -a claude-code
Открыть на GitHub

Что делает azure-monitor-ingestion-py

Скилл даёт готовые паттерны работы с библиотекой azure-monitor-ingestion. Он генерирует код для асинхронного и синхронного LogsIngestionClient, объясняет структуру DCR-правил и настройку стримов вида Custom-<TableName>_CL. Библиотека автоматически сжимает логи gzip-ом и разбивает их на части до 1 МБ.

Для работы требуются созданные в Azure ресурсы: Log Analytics workspace, Data Collection Endpoint (DCE), правило DCR и целевая таблица. Авторизация строится через DefaultAzureCredential из пакета azure-identity. Без заданных переменных AZURE_DCE_ENDPOINT и AZURE_DCR_RULE_ID выгрузить данные в облако не получится.

Какие задачи решает

  • отправить пользовательские логи в Log Analytics workspace через Logs Ingestion API
  • настроить асинхронную выгрузку событий с помощью LogsIngestionClient
  • обработать частичные сбои отправки через коллбэк on_error
  • загрузить массив логов напрямую из JSON-файла

Примеры запросов агенту

  • Напиши асинхронный скрипт на Python для отправки логов в Azure Monitor через LogsIngestionClient
  • Покажи пример отправки логов из файла logs.json с повтором неудачных записей через on_error
  • Как настроить DefaultAzureCredential и контекстный менеджер для azure-monitor-ingestion?

Как установить azure-monitor-ingestion-py

1Через Skills CLI (Vercel)

npx skills add microsoft/skills --skill azure-monitor-ingestion-py -a claude-code

2Вручную: положить файлы

~/.claude/skills/azure-monitor-ingestion-py/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/azure-monitor-ingestion-py/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о azure-monitor-ingestion-py

Как установить azure-monitor-ingestion-py в Claude Code?

Выполните команду npx skills add microsoft/skills --skill azure-monitor-ingestion-py -a claude-code. Файл навыка появится по пути ~/.claude/skills/azure-monitor-ingestion-py/SKILL.md.

Что делает скилл azure-monitor-ingestion-py?

Он обучает ассистента правилам работы с Python SDK azure-monitor-ingestion. Навык помогает генерировать код отправки данных в Log Analytics через DCR и настраивать обработку ошибок.

Нужно ли вручную делить логи на батчи при загрузке?

Нет, SDK сам делит записи на пачки размером до 1 МБ и сжимает их с помощью gzip. Отправка этих пачек выполняется параллельно.

Исходный текст

SKILL.md · MIT
---
name: azure-monitor-ingestion-py
description: |
  Azure Monitor Ingestion SDK for Python. Use for sending custom logs to Log Analytics workspace via Logs Ingestion API.
  Triggers: "azure-monitor-ingestion", "LogsIngestionClient", "custom logs", "DCR", "data collection rule", "Log Analytics".
license: MIT
metadata:
  author: Microsoft
  version: "1.0.0"
  package: azure-monitor-ingestion
---

# Azure Monitor Ingestion SDK for Python

Send custom logs to Azure Monitor Log Analytics workspace using the Logs Ingestion API.

## Installation

```bash
pip install azure-monitor-ingestion
pip install azure-identity
```

## Environment Variables

```bash
# Data Collection Endpoint (DCE)
AZURE_DCE_ENDPOINT=https://<dce-name>.<region>.ingest.monitor.azure.com  # Required for all auth methods

# Data Collection Rule (DCR) immutable ID
AZURE_DCR_RULE_ID=dcr-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx  # Required for all auth methods

# Stream name from DCR
AZURE_DCR_STREAM_NAME=Custom-MyTable_CL  # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```

## Prerequisites

Before using this SDK, you need:

1. **Log Analytics Workspace** — Target for your logs
2. **Data Collection Endpoint (DCE)** — Ingestion endpoint
3. **Data Collection Rule (DCR)** — Defines schema and destination
4. **Custom Table** — In Log Analytics (created via DCR or manually)

## 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.monitor.ingestion import LogsIngestionClient
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
import os

# 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()

with LogsIngestionClient(
    endpoint=os.environ["AZURE_DCE_ENDPOINT"],
    credential=credential
) as client:
    # Use `client.upload(...)` for all subsequent operations (see examples below)
    ...
```

## Upload Custom Logs

```python
from azure.monitor.ingestion import LogsIngestionClient
from azure.identity import DefaultAzureCredential
import os

rule_id = os.environ["AZURE_DCR_RULE_ID"]
stream_name = os.environ["AZURE_DCR_STREAM_NAME"]

logs = [
    {"TimeGenerated": "2024-01-15T10:00:00Z", "Computer": "server1", "Message": "Application started"},
    {"TimeGenerated": "2024-01-15T10:01:00Z", "Computer": "server1", "Message": "Processing request"},
    {"TimeGenerated": "2024-01-15T10:02:00Z", "Computer": "server2", "Message": "Connection established"}
]

with LogsIngestionClient(
    endpoint=os.environ["AZURE_DCE_ENDPOINT"],
    credential=DefaultAzureCredential()
) as client:
    client.upload(rule_id=rule_id, stream_name=stream_name, logs=logs)
```

## Upload from JSON File

```python
import json

with open("logs.json", "r") as f:
    logs = json.load(f)

client.upload(rule_id=rule_id, stream_name=stream_name, logs=logs)
```

## Custom Error Handling

Handle partial failures with a callback:

```python
failed_logs = []

def on_error(error):
    print(f"Upload failed: {error.error}")
    failed_logs.extend(error.failed_logs)

client.upload(
    rule_id=rule_id,
    stream_name=stream_name,
    logs=logs,
    on_error=on_error
)

# Retry failed logs
if failed_logs:
    print(f"Retrying {len(failed_logs)} failed logs...")
    client.upload(rule_id=rule_id, stream_name=stream_name, logs=failed_logs)
```

## Ignore Errors

```python
def ignore_errors(error):
    pass  # Silently ignore upload failures

client.upload(
    rule_id=rule_id,
    stream_name=stream_name,
    logs=logs,
    on_error=ignore_errors
)
```

## Async Client

```python
import asyncio
from azure.monitor.ingestion.aio import LogsIngestionClient
from azure.identity.aio import DefaultAzureCredential

async def upload_logs():
    async with LogsIngestionClient(
        endpoint=endpoint,
        credential=DefaultAzureCredential()
    ) as client:
        await client.upload(
            rule_id=rule_id,
            stream_name=stream_name,
            logs=logs
        )

asyncio.run(upload_logs())
```

## Sovereign Clouds

```python
from azure.identity import AzureAuthorityHosts, DefaultAzureCredential
from azure.monitor.ingestion import LogsIngestionClient

# Azure Government
credential = DefaultAzureCredential(authority=AzureAuthorityHosts.AZURE_GOVERNMENT)
with LogsIngestionClient(
    endpoint="https://example.ingest.monitor.azure.us",
    credential=credential,
    credential_scopes=["https://monitor.azure.us/.default"]
) as client:
    # client.upload(...)
    ...
```

## Batching Behavior

The SDK automatically:
- Splits logs into chunks of 1MB or less
- Compresses each chunk with gzip
- Uploads chunks in parallel

No manual batching needed for large log sets.

## Client Types

| Client | Purpose |
|--------|---------|
| `LogsIngestionClient` | Sync client for uploading logs |
| `LogsIngestionClient` (aio) | Async client for uploading logs |

## Key Concepts

| Concept | Description |
|---------|-------------|
| **DCE** | Data Collection Endpoint — ingestion URL |
| **DCR** | Data Collection Rule — defines schema, transformations, destination |
| **Stream** | Named data flow within a DCR |
| **Custom Table** | Target table in Log Analytics (ends with `_CL`) |

## DCR Stream Name Format

Stream names follow patterns:
- `Custom-<TableName>_CL` — For custom tables
- `Microsoft-<TableName>` — For built-in tables

## Best Practices

1. **Pick sync OR async and stay consistent.** Do not mix `azure.xxx` sync clients with `azure.xxx.aio` async clients in the same call path. Choose one mode per module.
2. **Always use context managers for clients and async credentials.** Wrap every client in `with Client(...) as client:` (sync) or `async with Client(...) as client:` (async) to ensure proper cleanup. For async `DefaultAzureCredential` from `azure.identity.aio`, also use `async with credential:` so tokens and transports are cleaned up.
3. **Use `DefaultAzureCredential`** for code that runs locally. Use a specific token credential for code that runs in Azure.
4. **Handle errors gracefully** — use `on_error` callback for partial failures
5. **Include TimeGenerated** — Required field for all logs
6. **Match DCR schema** — Log fields must match DCR column definitions
7. **Use async client** for high-throughput scenarios
8. **Batch uploads** — SDK handles batching, but send reasonable chunks
9. **Monitor ingestion** — Check Log Analytics for ingestion status

## Reference Files

| File | Contents |
|------|----------|
| [references/capabilities.md](references/capabilities.md) | Additional non-hero capabilities, operation-group coverage, and production checklists. |
| [references/non-hero-scenarios.md](references/non-hero-scenarios.md) | Dedicated non-hero examples for secondary/advanced scenarios. |

© Microsoft · MIT · microsoft/skills

Похожие скиллы

Все скиллы по теме «Облака: AWS, Azure, GCP» →
caveman-manage JuliusBrussee Проверяет состояние и результаты экспериментов Caveman Cloud, предлагает одно действие или блокирует рискованный запрос. Нужен перед запуском, одобрением, отменой или откатом. CX Codex +1 104 200установок workers-best-practices cloudflare Скилл настраивает ИИ на проверку продакшен-кода Cloudflare Workers по актуальным правилам рантайма, типам Wrangler и антипаттернам. CX Codex +1 126 100установок cloudflare-email-service cloudflare Скилл для работы с Cloudflare Email Sending и Email Routing: помогает настроить отправку и приём писем в Workers. CX Codex +1 102 300установок firebase-basics официальный google Скилл настраивает Firebase CLI, помогает войти в аккаунт, создать или выбрать проект и скачать конфигурацию Android или iOS. CX Codex 14 100установок cloudflare-one cloudflare Помогает агенту проектировать, настраивать и разбирать развёртывания Cloudflare One Zero Trust и SASE. Пригодится, когда нужно спланировать Access, Gateway или туннели без похода в документацию вручную. CX Codex +1 93 100установок cloudflare-one-migrations cloudflare Помогает спланировать переход с VPN, SWG или SASE на Cloudflare One: сопоставляет политики, находит пробелы и расписывает порядок выката. CX Codex +1 89 500установок

Из того же набора232

Весь набор →
react-flow-node-ts Генерирует типизированные узлы для холста React Flow со связками Handle и стором Zustand. Пригодится при сборке визуальных редакторов и пайплайнов. 2установок azure-speech-to-text-rest-py Скилл настраивает транскрипцию коротких аудиозаписей через REST API Azure Speech на Python. Позволяет распознавать речь до 60 секунд без тяжёлого Speech SDK. 2установок azure-search-documents-py Подсказывает агенту, как писать код для Azure AI Search на Python: векторный и гибридный поиск, семантический ранжинг, индексы. 2установок azure-monitor-opentelemetry-py Скилл помогает подключить Azure Monitor OpenTelemetry к Python-приложению и отправлять телеметрию в Application Insights. Пригодится для настройки трассировок, метрик и логов. 2установок azure-mgmt-apimanagement-py Помогает агенту управлять Azure API Management через Python SDK: создавать шлюзы, импортировать OpenAPI и настраивать политики. 2установок azure-eventhub-py Скилл для работы с Azure Event Hubs из Python: отправка событий, чтение партиций, чекпоинты в blob-хранилище. Пригодится, когда агент пишет продюсеров и консьюмеров. 2установок azure-eventgrid-py Генерирует чистый код на Python для публикации сообщений в Azure Event Grid. Помогает настроить авторизацию через Entra ID и отправку CloudEvents. 2установок azure-data-tables-py Скилл помогает писать Python-код для Azure Tables и Cosmos DB Table API: управлять таблицами, выполнять операции с сущностями и собирать пакетные транзакции. 2установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой