选项
首页首页 Skill 开发运营和 CI/CD azure-monitor-opentelemetry-py

azure-monitor-opentelemetry-py

microsoft/skills microsoft/skills

通过一行代码为 Python 应用程序配置带有 OpenTelemetry 自动插桩的 Azure Monitor Application Insights。

...展开全部
0
更新时间 2026-09-15

Azure Monitor OpenTelemetry Python 发行版

使用 OpenTelemetry 自动插桩为 Application Insights 提供一键式设置。

安装

pip install azure-monitor-opentelemetry

环境变量

APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.com/  # 所有身份验证方法必需
AZURE_TOKEN_CREDENTIALS=prod # 仅在生产环境中使用 DefaultAzureCredential 时必需

🔑 身份验证与生命周期: 本发行版默认配置为使用连接字符串,但对于 AAD 身份验证的遥测数据摄取(在支持的场景中),建议通过 credential= 参数使用 DefaultAzureCredential — 请参阅 Azure AD 身份验证部分。您与导出器一起创建的任何 Azure SDK 客户端都应包装在 with/async with 块中(来自 azure.identity.aio 的异步凭据同理)。

快速入门

from azure.identity import DefaultAzureCredential
from azure.monitor.opentelemetry import configure_azure_monitor

# 连接字符串用于标识 Application Insights 资源(从 APPLICATIONINSIGHTS_CONNECTION_STRING 环境变量读取)。
# DefaultAzureCredential 通过 Microsoft Entra ID 对遥测数据摄取进行身份验证(优于仅使用仪器密钥的身份验证)。
configure_azure_monitor(
    credential=DefaultAzureCredential(),
)

# 您的应用程序代码...

显式配置

from azure.identity import DefaultAzureCredential
from azure.monitor.opentelemetry import configure_azure_monitor

# 从环境变量读取 APPLICATIONINSIGHTS_CONNECTION_STRING 以标识资源;
# DefaultAzureCredential 通过 Microsoft Entra ID 对遥测数据摄取进行身份验证。
configure_azure_monitor(
    credential=DefaultAzureCredential(),
)

与 Flask 配合使用

from flask import Flask
from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor()

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello, World!"

if __name__ == "__main__":
    app.run()

与 Django 配合使用

# settings.py
from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor()

# Django 设置...

与 FastAPI 配合使用

from fastapi import FastAPI
from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor()

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

自定义追踪

from opentelemetry import trace
from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor()

tracer = trace.get_tracer(__name__)

with tracer.start_as_current_span("my-operation") as span:
    span.set_attribute("custom.attribute", "value")
    # 执行工作...

自定义指标

from opentelemetry import metrics
from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor()

meter = metrics.get_meter(__name__)
counter = meter.create_counter("my_counter")

counter.add(1, {"dimension": "value"})

自定义日志

import logging
from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor()

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

logger.info("This will appear in Application Insights")
logger.error("Errors are captured too", exc_info=True)

采样

from azure.monitor.opentelemetry import configure_azure_monitor

# 对 10% 的请求进行采样
configure_azure_monitor(
    sampling_ratio=0.1
)

云角色名称

为应用地图设置云角色名称:

from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry.sdk.resources import Resource, SERVICE_NAME

configure_azure_monitor(
    resource=Resource.create({SERVICE_NAME: "my-service-name"})
)

禁用特定插桩

from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor(
    instrumentations=["flask", "requests"]  # 仅启用这些
)

启用实时指标

from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor(
    enable_live_metrics=True
)

Azure AD 身份验证

from azure.monitor.opentelemetry import configure_azure_monitor
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential

# 本地开发:DefaultAzureCredential。生产环境:设置 AZURE_TOKEN_CREDENTIALS=prod 或 AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# 或者在生产环境中直接使用特定凭据:
# 请参阅 https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

configure_azure_monitor(
    credential=credential
)
</specific_credential>

包含的自动插桩

遥测类型
Flask追踪
Django追踪
FastAPI追踪
Requests追踪
urllib3追踪
httpx追踪
aiohttp追踪
psycopg2追踪
pymysql追踪
pymongo追踪
redis追踪

配置选项

参数描述默认值
`connection_string`Application Insights 连接字符串来自环境变量
`credential`用于 AAD 身份验证的 Azure 凭据
`sampling_ratio`采样率 (0.0 到 1.0)1.0
`resource`OpenTelemetry 资源自动检测
`instrumentations`要启用的插桩列表全部
`enable_live_metrics`启用实时指标流False

最佳实践

  1. 选择同步或异步并保持一致。 不要在同一调用路径中混合使用 azure.xxx 同步客户端和 azure.xxx.aio 异步客户端。每个模块选择一种模式。
  2. 在进程退出时刷新并关闭提供程序。 在进程退出时调用关闭/刷新 API(例如 tracer_provider.shutdown()meter_provider.shutdown()logger_provider.shutdown()),以便在进程终止前刷新遥测数据。
  3. 尽早调用 configure_azure_monitor() — 在导入插桩库之前
  4. 在生产环境中使用环境变量 存储连接字符串
  5. 为多服务应用设置云角色名称
  6. 在高流量应用中启用采样
  7. 使用结构化日志记录 以获得更好的日志分析查询
  8. 向跨度添加自定义属性 以获得更好的调试体验
  9. 在生产工作负载中使用 Microsoft Entra 身份验证
在 GitHub 上查看
---
name: azure-monitor-opentelemetry-py
description: Configures Azure Monitor Application Insights with OpenTelemetry auto-instrumentation for Python applications in one line.
license: MIT
---

# Azure Monitor OpenTelemetry Distro for Python

One-line setup for Application Insights with OpenTelemetry auto-instrumentation.

## Installation

```bash
pip install azure-monitor-opentelemetry
```

## Environment Variables

```bash
APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.com/  # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```

> **🔑 Auth & lifecycle:** This distro is configured with a connection string by design, but for *AAD-authenticated ingestion* (where supported) prefer `DefaultAzureCredential` via the `credential=` parameter — see the [Azure AD Authentication](#azure-ad-authentication) section. Any Azure SDK clients you create alongside the exporter should be wrapped in `with`/`async with` blocks (and async credentials from `azure.identity.aio` likewise).

## Quick Start

```python
from azure.identity import DefaultAzureCredential
from azure.monitor.opentelemetry import configure_azure_monitor

# Connection string identifies the App Insights resource (read from APPLICATIONINSIGHTS_CONNECTION_STRING env var).
# DefaultAzureCredential authenticates ingestion via Microsoft Entra ID (preferred over instrumentation-key-only auth).
configure_azure_monitor(
    credential=DefaultAzureCredential(),
)

# Your application code...
```

## Explicit Configuration

```python
from azure.identity import DefaultAzureCredential
from azure.monitor.opentelemetry import configure_azure_monitor

# Reads APPLICATIONINSIGHTS_CONNECTION_STRING from env to identify the resource;
# DefaultAzureCredential authenticates ingestion via Microsoft Entra ID.
configure_azure_monitor(
    credential=DefaultAzureCredential(),
)
```

## With Flask

```python
from flask import Flask
from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor()

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello, World!"

if __name__ == "__main__":
    app.run()
```

## With Django

```python
# settings.py
from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor()

# Django settings...
```

## With FastAPI

```python
from fastapi import FastAPI
from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor()

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}
```

## Custom Traces

```python
from opentelemetry import trace
from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor()

tracer = trace.get_tracer(__name__)

with tracer.start_as_current_span("my-operation") as span:
    span.set_attribute("custom.attribute", "value")
    # Do work...
```

## Custom Metrics

```python
from opentelemetry import metrics
from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor()

meter = metrics.get_meter(__name__)
counter = meter.create_counter("my_counter")

counter.add(1, {"dimension": "value"})
```

## Custom Logs

```python
import logging
from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor()

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

logger.info("This will appear in Application Insights")
logger.error("Errors are captured too", exc_info=True)
```

## Sampling

```python
from azure.monitor.opentelemetry import configure_azure_monitor

# Sample 10% of requests
configure_azure_monitor(
    sampling_ratio=0.1
)
```

## Cloud Role Name

Set cloud role name for Application Map:

```python
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry.sdk.resources import Resource, SERVICE_NAME

configure_azure_monitor(
    resource=Resource.create({SERVICE_NAME: "my-service-name"})
)
```

## Disable Specific Instrumentations

```python
from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor(
    instrumentations=["flask", "requests"]  # Only enable these
)
```

## Enable Live Metrics

```python
from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor(
    enable_live_metrics=True
)
```

## Azure AD Authentication

```python
from azure.monitor.opentelemetry import configure_azure_monitor
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()

configure_azure_monitor(
    credential=credential
)
```

## Auto-Instrumentations Included

| Library | Telemetry Type |
|---------|---------------|
| Flask | Traces |
| Django | Traces |
| FastAPI | Traces |
| Requests | Traces |
| urllib3 | Traces |
| httpx | Traces |
| aiohttp | Traces |
| psycopg2 | Traces |
| pymysql | Traces |
| pymongo | Traces |
| redis | Traces |

## Configuration Options

| Parameter | Description | Default |
|-----------|-------------|---------|
| `connection_string` | Application Insights connection string | From env var |
| `credential` | Azure credential for AAD auth | None |
| `sampling_ratio` | Sampling rate (0.0 to 1.0) | 1.0 |
| `resource` | OpenTelemetry Resource | Auto-detected |
| `instrumentations` | List of instrumentations to enable | All |
| `enable_live_metrics` | Enable Live Metrics stream | False |

## 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. **Flush and shut down providers at process exit.** Call the shutdown/flush APIs (e.g. `tracer_provider.shutdown()`, `meter_provider.shutdown()`, `logger_provider.shutdown()`) at process exit to flush telemetry before the process terminates.
3. **Call configure_azure_monitor() early** — Before importing instrumented libraries
4. **Use environment variables** for connection string in production
5. **Set cloud role name** for multi-service applications
6. **Enable sampling** in high-traffic applications
7. **Use structured logging** for better log analytics queries
8. **Add custom attributes** to spans for better debugging
9. **Use Microsoft Entra authentication** for production workloads

所有文件

1 个文件

安装 azure-monitor-opentelemetry-py

将技能文件下载并解压至 .claude/skills/ 目录。

下载ZIP

克隆仓库并复制技能文件到您的项目中。

git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-monitor-opentelemetry-py # Copy SKILL.md to your .claude/skills/ directory

复制 复制
快速设置: 将技能文件夹复制到 .claude/skills/ 目录。Claude 将自动检测并使用该技能。

相关技能

base44-cli
更新时间 2026-06-29
klingai-upgrade-migration
更新时间 2026-07-03
Railway CLI Management
更新时间 2026-07-02
Verification &amp; Quality Assurance
更新时间 2026-06-29
OR