azure-monitor-opentelemetry-py

npx skills add https://github.com/microsoft/skills --skill azure-monitor-opentelemetry-py

Azure Monitor OpenTelemetry Distro pour Python

Configuration en une ligne pour Application Insights avec auto-instrumentation OpenTelemetry.

Installation

pip install azure-monitor-opentelemetry

Variables d'environnement

APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.com/  # Requis pour toutes les méthodes d'authentification
AZURE_TOKEN_CREDENTIALS=prod # Requis uniquement si DefaultAzureCredential est utilisé en production

Démarrage rapide

from azure.monitor.opentelemetry import configure_azure_monitor

# Configuration en une ligne - lit la chaîne de connexion depuis l'environnement
configure_azure_monitor()

# Votre code applicatif...

Configuration explicite

from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor(
    connection_string="InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.com/"
)

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

Avec Django

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

configure_azure_monitor()

# Paramètres Django...

Avec 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"}

Traces personnalisées

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")
    # Effectuer le travail...

Métriques personnalisées

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"})

Journaux personnalisés

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)

Échantillonnage

from azure.monitor.opentelemetry import configure_azure_monitor

# Échantillonner 10 % des requêtes
configure_azure_monitor(
    sampling_ratio=0.1
)

Nom du rôle cloud

Définir le nom du rôle cloud pour 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"})
)

Désactiver des instrumentations spécifiques

from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor(
    instrumentations=["flask", "requests"]  # Activer uniquement celles-ci
)

Activer Live Metrics

from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor(
    enable_live_metrics=True
)

Authentification Azure AD

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

# Dev local : DefaultAzureCredential. Production : définir AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Ou utiliser une information d'identification spécifique directement en production :
# Voir https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

configure_azure_monitor(
    credential=credential
)

Auto-instrumentations incluses

Bibliothèque Type de télémétrie
Flask Traces
Django Traces
FastAPI Traces
Requests Traces
urllib3 Traces
httpx Traces
aiohttp Traces
psycopg2 Traces
pymysql Traces
pymongo Traces
redis Traces

Options de configuration

Paramètre Description Défaut
connection_string Chaîne de connexion Application Insights Variable env
credential Credential Azure pour authentification AAD None
sampling_ratio Taux d'échantillonnage (0,0 à 1,0) 1,0
resource Resource OpenTelemetry Détection automatique
instrumentations Liste des instrumentations à activer Toutes
enable_live_metrics Activer le flux Live Metrics False

Bonnes pratiques

  1. Appeler configure_azure_monitor() au démarrage — Avant d'importer les bibliothèques instrumentées
  2. Utiliser des variables d'environnement pour la chaîne de connexion en production
  3. Définir le nom du rôle cloud pour les applications multi-services
  4. Activer l'échantillonnage dans les applications à fort trafic
  5. Utiliser la journalisation structurée pour des requêtes d'analyse de journaux améliorées
  6. Ajouter des attributs personnalisés aux spans pour un meilleur débogage
  7. Utiliser l'authentification AAD pour les charges de travail en production

Skills similaires