azure-monitor-opentelemetry-py
microsoft/skills
Python 애플리케이션에 대한 OpenTelemetry 자동 계측(Auto-instrumentation)을 사용하여 Azure Monitor Application Insights를 한 줄로 구성합니다.
...모든 것을 확장하십시오Azure Monitor OpenTelemetry Distro for Python
Application Insights에 대한 OpenTelemetry 자동 계측(one-line setup)을 위한 원클릭 설정입니다.
설치
pip install azure-monitor-opentelemetry
환경 변수
APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.com/ # 모든 인증 방식에 필수
AZURE_TOKEN_CREDENTIALS=prod # 프로덕션 환경에서 DefaultAzureCredential을 사용하는 경우에만 필수
🔑 인증 및 수명 주기: 이 디스트로는 설계상 연결 문자열(connection string)로 구성되어 있지만, 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
# 연결 문자열은 App Insights 리소스를 식별합니다 (APPLICATIONINSIGHTS_CONNECTION_STRING 환경 변수에서 읽음).
# DefaultAzureCredential은 Microsoft Entra ID를 통해 데이터 수집을 인증합니다 (instrumentation-key-only 인증보다 선호됨).
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
)
클라우드 역할 이름
Application Map에 대한 클라우드 역할 이름을 설정합니다:
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 자격 증명 | None |
| `sampling_ratio` | 샘플링 비율 (0.0 ~ 1.0) | 1.0 |
| `resource` | OpenTelemetry Resource | 자동 감지 |
| `instrumentations` | 활성화할 계측 목록 | 전체 |
| `enable_live_metrics` | 실시간 메트릭 스트림 활성화 | False |
모범 사례
- 동기 또는 비동기 중 하나를 선택하고 일관성을 유지하십시오. 동일한 호출 경로에서
azure.xxx동기 클라이언트와azure.xxx.aio비동기 클라이언트를 혼합하지 마십시오. 모듈별로 하나의 모드를 선택하십시오. - 프로세스 종료 시 공급자를 플러시하고 종료하십시오. 프로세스가 종료되기 전에 텔레메터를 플러시하기 위해 프로세스 종료 시 종료/플러시 API(예:
tracer_provider.shutdown(),meter_provider.shutdown(),logger_provider.shutdown())를 호출하십시오. - configure_azure_monitor()를 조기에 호출하십시오 — 계측된 라이브러리를 가져오기 전
- 프로덕션에서 연결 문자열을 위해 환경 변수를 사용하십시오
- 다중 서비스 애플리케이션에 대해 클라우드 역할 이름을 설정하십시오
- 고트래픽 애플리케이션에서 샘플링을 활성화하십시오
- 더 나은 로그 분석 쿼리를 위해 구조화된 로깅을 사용하십시오
- 더 나은 디버깅을 위해 스판에 사용자 정의 속성을 추가하십시오
- 프로덕션 워크로드에 Microsoft Entra 인증을 사용하십시오
---
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
복사





집
