azure-monitor-ingestion-py
A Python SDK for streaming custom log data into Azure Monitor Log Analytics.
Install
mkdir -p .claude/skills/azure-monitor-ingestion-py && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/7451" && unzip -o skill.zip -d .claude/skills/azure-monitor-ingestion-py && rm skill.zipInstalls to .claude/skills/azure-monitor-ingestion-py
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
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".Key capabilities
- →Upload custom logs to Log Analytics
- →Handle partial upload failures via callbacks
- →Perform parallel log chunk uploads
- →Compress log data using gzip
- →Support sovereign cloud endpoints
How it works
The client uses a Data Collection Rule and Endpoint to stream logs into a specific Log Analytics table. It automatically handles batching, compression, and parallel transmission.
Inputs & outputs
When to use azure-monitor-ingestion-py
- →Send custom application logs
- →Implement data collection rules
- →Monitor telemetry in Log Analytics
About this skill
Azure Monitor Ingestion SDK for Python
Send custom logs to Azure Monitor Log Analytics workspace using the Logs Ingestion API.
Installation
pip install azure-monitor-ingestion
pip install azure-identity
Environment Variables
# 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:
- Log Analytics Workspace — Target for your logs
- Data Collection Endpoint (DCE) — Ingestion endpoint
- Data Collection Rule (DCR) — Defines schema and destination
- Custom Table — In Log Analytics (created via DCR or manually)
Authentication & Lifecycle
🔑 Two rules apply to every code sample below:
- 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:
DefaultAzureCredentialworks as-is.- Production: set
AZURE_TOKEN_CREDENTIALS=prod(orAZURE_TOKEN_CREDENTIALS=<specific_credential>) to constrain the credential chain to production-safe credentials.- 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:andasync with DefaultAzureCredential() as credential:(fromazure.identity.aio)Snippets may abbreviate this setup, but production code should always follow both rules.
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
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
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:
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
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
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
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 tablesMicrosoft-<TableName>— For built-in tables
Best Practices
- Pick sync OR async and stay consistent. Do not mix
azure.xxxsync clients withazure.xxx.aioasync clients in the same call path. Choose one mode per module. - Always use context managers for clients and async credentials. Wrap every client in
with Client(...) as client:(sync) orasync with Client(...) as client:(async) to ensure proper cleanup. For asyncDefaultAzureCredentialfromazure.identity.aio, also useasync with credential:so tokens and transports are cleaned up. - Use
DefaultAzureCredentialfor code that runs locally. Use a specific token credential for code that runs in Azure. - Handle errors gracefully — use
on_errorcallback for partial failures - Include TimeGenerated — Required field for all logs
- Match DCR schema — Log fields must match DCR column definitions
- Use async client for high-throughput scenarios
- Batch uploads — SDK handles batching, but send reasonable chunks
- Monitor ingestion — Check Log Analytics for ingestion status
Reference Files
| File | Contents |
|---|---|
| references/capabilities.md | Additional non-hero capabilities, operation-group coverage, and production checklists. |
| references/non-hero-scenarios.md | Dedicated non-hero examples for secondary/advanced scenarios. |
When not to use it
- →Sending logs without a defined Data Collection Rule
Prerequisites
Limitations
- →Logs must match the schema defined in the Data Collection Rule
- →Requires TimeGenerated field in all log entries
How it compares
This approach uses the Logs Ingestion API for standardized, schema-validated data collection compared to legacy HTTP data collector methods.
Compared to similar skills
azure-monitor-ingestion-py side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| azure-monitor-ingestion-py (this skill) | 1 | 29d | Review | Intermediate |
| distributed-tracing | 5 | 2mo | No flags | Intermediate |
| langfuse | 7 | 6mo | No flags | Intermediate |
| langsmith-observability | 4 | 7mo | Review | Intermediate |
Try saying
Example prompts that trigger this skill in your AI assistant.
More by microsoft
View all by microsoft →You might also like
distributed-tracing
wshobson
Implement distributed tracing with Jaeger and Tempo to track requests across microservices and identify performance bottlenecks. Use when debugging microservices, analyzing request flows, or implementing observability for distributed systems.
langfuse
davila7
Expert in Langfuse - the open-source LLM observability platform. Covers tracing, prompt management, evaluation, datasets, and integration with LangChain, LlamaIndex, and OpenAI. Essential for debugging, monitoring, and improving LLM applications in production. Use when: langfuse, llm observability, llm tracing, prompt management, llm evaluation.
langsmith-observability
davila7
LLM observability platform for tracing, evaluation, and monitoring. Use when debugging LLM applications, evaluating model outputs against datasets, monitoring production systems, or building systematic testing pipelines for AI applications.
phoenix-observability
davila7
Open-source AI observability platform for LLM tracing, evaluation, and monitoring. Use when debugging LLM applications with detailed traces, running evaluations on datasets, or monitoring production AI systems with real-time insights.
mlops-observability
fmind
Guide to implement full stack observability including reproducibility, lineage, monitoring, alerting, and explainability.
trulens-instrumentation
truera
Instrument LLM apps with TruLens OTEL-based tracing - from setup to debugging and optimization