вариант
ДомДом Skill DevOps и CI/CD azure-monitor-opentelemetry-exporter-java

azure-monitor-opentelemetry-exporter-java

microsoft/skills microsoft/skills

Экспортируйте трассировки OpenTelemetry, метрики и журналы в Azure Monitor/Application Insights с использованием устаревшего экспортера или рекомендуемого пакета автонастройки.

...Расширить все
0
Обновлено время 19 сентября 2026 г.

Экспортер OpenTelemetry для Azure Monitor на Java

⚠️ УВЕДОМЛЕНИЕ ОБ УСТАРЕВАНИИ: Этот пакет устарел. Перейдите на azure-monitor-opentelemetry-autoconfigure.

См. Руководство по миграции для получения подробных инструкций.

Экспорт данных телеметрии OpenTelemetry в Azure Monitor / Application Insights.

Установка (Устаревший метод)

<dependency><groupid>com.azure</groupid><artifactid>azure-monitor-opentelemetry-exporter</artifactid><version>1.0.0-beta.x</version></dependency>

Рекомендуется: вместо этого используйте Autoconfigure

<dependency><groupid>com.azure</groupid><artifactid>azure-monitor-opentelemetry-autoconfigure</artifactid><version>LATEST</version></dependency>

Переменные среды

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

Базовая настройка с использованием Autoconfigure (Рекомендуется)

Использование переменной среды

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

// Строка подключения из переменной окружения APPLICATIONINSIGHTS_CONNECTION_STRING
AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder = AutoConfiguredOpenTelemetrySdk.builder();
AzureMonitorExporter.customize(sdkBuilder);
OpenTelemetry openTelemetry = sdkBuilder.build().getOpenTelemetrySdk();

С явной строкой подключения

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

Создание интервалов (Spans)

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

// Получение трассировщика
Tracer tracer = openTelemetry.getTracer("com.example.myapp");

// Создание интервала
Span span = tracer.spanBuilder("myOperation").startSpan();

try (Scope scope = span.makeCurrent()) {
    // Логика вашего приложения
    doWork();
} catch (Throwable t) {
    span.recordException(t);
    throw t;
} finally {
    span.end();
}

Добавление атрибутов интервала (Span Attributes)

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()) {
    // Добавление атрибутов во время выполнения
    span.setAttribute("items.count", 3);
    span.setAttribute("total.amount", 99.99);

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

Пользовательский процессор интервалов (Span Processor)

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) {
        // Добавление пользовательского атрибута к каждому интервалу
        span.setAttribute(CUSTOM_ATTR, "customValue");
    }

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

    @Override
    public void onEnd(ReadableSpan span) {
        // Постобработка при необходимости
    }

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

// Регистрация процессора
AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder = AutoConfiguredOpenTelemetrySdk.builder();
AzureMonitorExporter.customize(sdkBuilder);

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

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

Вложенные интервалы (Nested Spans)

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

public void childOperation() {
    // Автоматическая связь с родительским интервалом через Context
    Span childSpan = tracer.spanBuilder("childOperation").startSpan();
    try (Scope scope = childSpan.makeCurrent()) {
        // Работа дочернего интервала
    } finally {
        childSpan.end();
    }
}

Запись исключений (Recording 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();
}

Метрики (через 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");

// Счетчик
LongCounter requestCounter = meter.counterBuilder("http.requests")
    .setDescription("Общее количество HTTP-запросов")
    .setUnit("requests")
    .build();

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

// Гистограмма
LongHistogram latencyHistogram = meter.histogramBuilder("http.latency")
    .setDescription("Задержка запроса")
    .setUnit("ms")
    .ofLongs()
    .build();

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

Ключевые понятия

ПонятиеОписание
Строка подключенияСтрока подключения Application Insights с ключом инструментации
Трассировщик (Tracer)Создает интервалы для распределенной трассировки
Интервал (Span)Представляет единицу работы с таймингами и атрибутами
Процессор интервалов (SpanProcessor)Перехватывает жизненный цикл интервала для настройки
Экспортер (Exporter)Отправляет телеметрию в Azure Monitor

Миграция на Autoconfigure

Пакет azure-monitor-opentelemetry-autoconfigure предоставляет:

  • Автоматическую инструментацию распространенных библиотек
  • Упрощенную конфигурацию
  • Лучшую интеграцию с SDK OpenTelemetry

Шаги миграции

  1. Замените зависимость:

    
     <dependency><groupid>com.azure</groupid><artifactid>azure-monitor-opentelemetry-exporter</artifactid></dependency><dependency><groupid>com.azure</groupid><artifactid>azure-monitor-opentelemetry-autoconfigure</artifactid></dependency>
  2. Обновите код инициализации в соответствии с Руководством по миграции

Рекомендуемые практики

  1. Используйте autoconfigure — Перейдите на azure-monitor-opentelemetry-autoconfigure
  2. Задавайте осмысленные имена интервалов — Используйте описательные имена операций
  3. Добавляйте релевантные атрибуты — Включайте контекстные данные для отладки
  4. Обрабатывайте исключения — Всегда записывайте исключения в интервалы
  5. Используйте семантические соглашения — Следуйте семантическим соглашениям OpenTelemetry
  6. Завершайте интервалы в блоке finally — Убедитесь, что интервалы всегда завершаются
  7. Используйте try-with-resources — Управление областью видимости с помощью шаблона try-with-resources

Ссылки на справочные материалы

РесурсURL
Пакет Mavenhttps://central.sonatype.com/artifact/com.azure/azure-monitor-opentelemetry-exporter
GitHubhttps://github.com/Azure/azure-sdk-for-java/tree/main/sdk/monitor/azure-monitor-opentelemetry-exporter
Руководство по миграцииhttps://github.com/Azure/azure-sdk-for-java/blob/main/sdk/monitor/azure-monitor-opentelemetry-exporter/MIGRATION.md
Пакет Autoconfigurehttps://central.sonatype.com/artifact/com.azure/azure-monitor-opentelemetry-autoconfigure
OpenTelemetry для Javahttps://opentelemetry.io/docs/languages/java/
Application Insightshttps://learn.microsoft.com/azure/azure-monitor/app/app-insights-overview
Посмотреть на GitHub
---
name: azure-monitor-opentelemetry-exporter-java
description: Export OpenTelemetry traces, metrics, and logs to Azure Monitor/Application Insights using the deprecated exporter or the recommended autoconfigure package.
license: MIT
---

# Azure Monitor OpenTelemetry Exporter for Java

> **⚠️ DEPRECATION NOTICE**: This package is deprecated. Migrate to `azure-monitor-opentelemetry-autoconfigure`.
>
> See [Migration Guide](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/monitor/azure-monitor-opentelemetry-exporter/MIGRATION.md) for detailed instructions.

Export OpenTelemetry telemetry data to Azure Monitor / Application Insights.

## Installation (Deprecated)

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

## Recommended: Use Autoconfigure Instead

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

## Environment Variables

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

## Basic Setup with Autoconfigure (Recommended)

### Using Environment Variable

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

// Connection string from APPLICATIONINSIGHTS_CONNECTION_STRING env var
AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder = AutoConfiguredOpenTelemetrySdk.builder();
AzureMonitorExporter.customize(sdkBuilder);
OpenTelemetry openTelemetry = sdkBuilder.build().getOpenTelemetrySdk();
```

### With Explicit Connection String

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

## Creating Spans

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

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

// Create span
Span span = tracer.spanBuilder("myOperation").startSpan();

try (Scope scope = span.makeCurrent()) {
    // Your application logic
    doWork();
} catch (Throwable t) {
    span.recordException(t);
    throw t;
} finally {
    span.end();
}
```

## Adding Span Attributes

```java
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()) {
    // Add attributes during execution
    span.setAttribute("items.count", 3);
    span.setAttribute("total.amount", 99.99);
    
    processOrder();
} finally {
    span.end();
}
```

## Custom Span Processor

```java
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) {
        // Add custom attribute to every span
        span.setAttribute(CUSTOM_ATTR, "customValue");
    }

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

    @Override
    public void onEnd(ReadableSpan span) {
        // Post-processing if needed
    }

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

// Register processor
AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder = AutoConfiguredOpenTelemetrySdk.builder();
AzureMonitorExporter.customize(sdkBuilder);

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

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

## Nested Spans

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

public void childOperation() {
    // Automatically links to parent via Context
    Span childSpan = tracer.spanBuilder("childOperation").startSpan();
    try (Scope scope = childSpan.makeCurrent()) {
        // Child work
    } finally {
        childSpan.end();
    }
}
```

## Recording Exceptions

```java
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();
}
```

## Metrics (via OpenTelemetry)

```java
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");

// Counter
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
));

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

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

## Key Concepts

| Concept | Description |
|---------|-------------|
| Connection String | Application Insights connection string with instrumentation key |
| Tracer | Creates spans for distributed tracing |
| Span | Represents a unit of work with timing and attributes |
| SpanProcessor | Intercepts span lifecycle for customization |
| Exporter | Sends telemetry to Azure Monitor |

## Migration to Autoconfigure

The `azure-monitor-opentelemetry-autoconfigure` package provides:
- Automatic instrumentation of common libraries
- Simplified configuration
- Better integration with OpenTelemetry SDK

### Migration Steps

1. Replace dependency:
   ```xml
   <!-- Remove -->
   <dependency>
       <groupId>com.azure</groupId>
       <artifactId>azure-monitor-opentelemetry-exporter</artifactId>
   </dependency>
   
   <!-- Add -->
   <dependency>
       <groupId>com.azure</groupId>
       <artifactId>azure-monitor-opentelemetry-autoconfigure</artifactId>
   </dependency>
   ```

2. Update initialization code per [Migration Guide](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/monitor/azure-monitor-opentelemetry-exporter/MIGRATION.md)

## Best Practices

1. **Use autoconfigure** — Migrate to `azure-monitor-opentelemetry-autoconfigure`
2. **Set meaningful span names** — Use descriptive operation names
3. **Add relevant attributes** — Include contextual data for debugging
4. **Handle exceptions** — Always record exceptions on spans
5. **Use semantic conventions** — Follow OpenTelemetry semantic conventions
6. **End spans in finally** — Ensure spans are always ended
7. **Use try-with-resources** — Scope management with try-with-resources pattern

## Reference Links

| Resource | URL |
|----------|-----|
| Maven Package | 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 |
| Migration Guide | https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/monitor/azure-monitor-opentelemetry-exporter/MIGRATION.md |
| Autoconfigure Package | 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 |

Все файлы

0 файлов

Установить azure-monitor-opentelemetry-exporter-java

Скачайте и извлеките файлы навыков в вашу директорию .claude/skills/.

Скачать ZIP

Клонируйте репозиторий и скопируйте файлы навыка в свой проект.

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

Копировать Копировать
Быстрая настройка: Скопируйте папку навыка в .claude/skills/ Claude автоматически обнаружит и использует этот навык
Репозиторий microsoft/skills

Похожие навыки

Verification &amp; Quality Assurance
Обновлено время 29 июня 2026 г.
base44-cli
Обновлено время 29 июня 2026 г.
klingai-upgrade-migration
Обновлено время 3 июля 2026 г.
Railway CLI Management
Обновлено время 2 июля 2026 г.
OR