azure-monitor-opentelemetry-exporter-java

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

Exportateur Azure Monitor OpenTelemetry pour Java

⚠️ AVIS DE DÉPRÉCIATION : Ce package est déprécié. Migrez vers azure-monitor-opentelemetry-autoconfigure.

Consultez le Guide de migration pour les instructions détaillées.

Exportez les données de télémétrie OpenTelemetry vers Azure Monitor / Application Insights.

Installation (Déprécié)

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-monitor-opentelemetry-exporter</artifactId>
    <version>1.0.0-beta.x</version>
</dependency>

Recommandé : Utilisez Autoconfigure à la place

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-monitor-opentelemetry-autoconfigure</artifactId>
    <version>LATEST</version>
</dependency>

Variables d'environnement

APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.com/

Configuration de base avec Autoconfigure (Recommandé)

Utilisation d'une variable d'environnement

import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder;
import io.opentelemetry.api.OpenTelemetry;
import com.azure.monitor.opentelemetry.exporter.AzureMonitorExporter;

// Chaîne de connexion depuis la variable d'environnement APPLICATIONINSIGHTS_CONNECTION_STRING
AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder = AutoConfiguredOpenTelemetrySdk.builder();
AzureMonitorExporter.customize(sdkBuilder);
OpenTelemetry openTelemetry = sdkBuilder.build().getOpenTelemetrySdk();

Avec une chaîne de connexion explicite

AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder = AutoConfiguredOpenTelemetrySdk.builder();
AzureMonitorExporter.customize(sdkBuilder, "{connection-string}");
OpenTelemetry openTelemetry = sdkBuilder.build().getOpenTelemetrySdk();

Création de spans

import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.context.Scope;

// Obtenir le tracer
Tracer tracer = openTelemetry.getTracer("com.example.myapp");

// Créer un span
Span span = tracer.spanBuilder("myOperation").startSpan();

try (Scope scope = span.makeCurrent()) {
    // Logique de votre application
    doWork();
} catch (Throwable t) {
    span.recordException(t);
    throw t;
} finally {
    span.end();
}

Ajout d'attributs de span

import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;

Span span = tracer.spanBuilder("processOrder")
    .setAttribute("order.id", "12345")
    .setAttribute("customer.tier", "premium")
    .startSpan();

try (Scope scope = span.makeCurrent()) {
    // Ajouter des attributs pendant l'exécution
    span.setAttribute("items.count", 3);
    span.setAttribute("total.amount", 99.99);

    processOrder();
} finally {
    span.end();
}

Processeur de span personnalisé

import io.opentelemetry.sdk.trace.SpanProcessor;
import io.opentelemetry.sdk.trace.ReadWriteSpan;
import io.opentelemetry.sdk.trace.ReadableSpan;
import io.opentelemetry.context.Context;

private static final AttributeKey<String> CUSTOM_ATTR = AttributeKey.stringKey("custom.attribute");

SpanProcessor customProcessor = new SpanProcessor() {
    @Override
    public void onStart(Context context, ReadWriteSpan span) {
        // Ajouter un attribut personnalisé à chaque span
        span.setAttribute(CUSTOM_ATTR, "customValue");
    }

    @Override
    public boolean isStartRequired() {
        return true;
    }

    @Override
    public void onEnd(ReadableSpan span) {
        // Post-traitement si nécessaire
    }

    @Override
    public boolean isEndRequired() {
        return false;
    }
};

// Enregistrer le processeur
AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder = AutoConfiguredOpenTelemetrySdk.builder();
AzureMonitorExporter.customize(sdkBuilder);

sdkBuilder.addTracerProviderCustomizer(
    (sdkTracerProviderBuilder, configProperties) -> 
        sdkTracerProviderBuilder.addSpanProcessor(customProcessor)
);

OpenTelemetry openTelemetry = sdkBuilder.build().getOpenTelemetrySdk();

Spans imbriqués

public void parentOperation() {
    Span parentSpan = tracer.spanBuilder("parentOperation").startSpan();
    try (Scope scope = parentSpan.makeCurrent()) {
        childOperation();
    } finally {
        parentSpan.end();
    }
}

public void childOperation() {
    // Lié automatiquement au parent via Context
    Span childSpan = tracer.spanBuilder("childOperation").startSpan();
    try (Scope scope = childSpan.makeCurrent()) {
        // Travail enfant
    } finally {
        childSpan.end();
    }
}

Enregistrement d'exceptions

Span span = tracer.spanBuilder("riskyOperation").startSpan();
try (Scope scope = span.makeCurrent()) {
    performRiskyWork();
} catch (Exception e) {
    span.recordException(e);
    span.setStatus(StatusCode.ERROR, e.getMessage());
    throw e;
} finally {
    span.end();
}

Métriques (via OpenTelemetry)

import io.opentelemetry.api.metrics.Meter;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.LongHistogram;

Meter meter = openTelemetry.getMeter("com.example.myapp");

// Compteur
LongCounter requestCounter = meter.counterBuilder("http.requests")
    .setDescription("Total HTTP requests")
    .setUnit("requests")
    .build();

requestCounter.add(1, Attributes.of(
    AttributeKey.stringKey("http.method"), "GET",
    AttributeKey.longKey("http.status_code"), 200L
));

// Histogramme
LongHistogram latencyHistogram = meter.histogramBuilder("http.latency")
    .setDescription("Request latency")
    .setUnit("ms")
    .ofLongs()
    .build();

latencyHistogram.record(150, Attributes.of(
    AttributeKey.stringKey("http.route"), "/api/users"
));

Concepts clés

Concept Description
Chaîne de connexion Chaîne de connexion Application Insights avec clé d'instrumentation
Tracer Crée des spans pour le tracing distribué
Span Représente une unité de travail avec timing et attributs
SpanProcessor Intercepte le cycle de vie du span pour la personnalisation
Exporter Envoie la télémétrie à Azure Monitor

Migration vers Autoconfigure

Le package azure-monitor-opentelemetry-autoconfigure fournit :

  • Instrumentation automatique des bibliothèques courantes
  • Configuration simplifiée
  • Meilleure intégration avec OpenTelemetry SDK

Étapes de migration

  1. Remplacez la dépendance :

    <!-- Supprimer -->
    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-monitor-opentelemetry-exporter</artifactId>
    </dependency>
    
    <!-- Ajouter -->
    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-monitor-opentelemetry-autoconfigure</artifactId>
    </dependency>
  2. Mettez à jour le code d'initialisation selon le Guide de migration

Bonnes pratiques

  1. Utilisez autoconfigure — Migrez vers azure-monitor-opentelemetry-autoconfigure
  2. Définissez des noms de span significatifs — Utilisez des noms d'opération descriptifs
  3. Ajoutez des attributs pertinents — Incluez des données contextuelles pour le débogage
  4. Traitez les exceptions — Enregistrez toujours les exceptions sur les spans
  5. Utilisez les conventions sémantiques — Suivez les conventions sémantiques OpenTelemetry
  6. Terminez les spans dans finally — Assurez-vous que les spans se terminent toujours
  7. Utilisez try-with-resources — Gestion de la portée avec le pattern try-with-resources

Liens de référence

Ressource URL
Package Maven https://central.sonatype.com/artifact/com.azure/azure-monitor-opentelemetry-exporter
GitHub https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/monitor/azure-monitor-opentelemetry-exporter
Guide de migration https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/monitor/azure-monitor-opentelemetry-exporter/MIGRATION.md
Package Autoconfigure https://central.sonatype.com/artifact/com.azure/azure-monitor-opentelemetry-autoconfigure
OpenTelemetry Java https://opentelemetry.io/docs/languages/java/
Application Insights https://learn.microsoft.com/azure/azure-monitor/app/app-insights-overview

Skills similaires