이 가이드에서는 Azure Monitor Application Insights 내에서 OTel(OpenTelemetry) 계측을 통합하고 사용자 지정하는 방법에 대한 지침을 제공합니다.
OpenTelemetry 개념에 대한 자세한 내용은 OpenTelemetry 개요 또는 OpenTelemetry FAQ를 참조하세요.
자동 데이터 수집
배포판은 OpenTelemetry 계측 라이브러리를 번들로 묶어 데이터를 자동으로 수집합니다.
포함된 계측 라이브러리
요청
종속성
로깅
Azure Monitor로 전송되는 로그 수를 줄이거나 늘리려면 적절한 로그 수준을 설정하거나 필터를 적용하도록 로깅을 구성합니다. 예를 들어 OpenTelemetry/Azure Monitor에만 Warning
Error
로그를 보내도록 선택할 수 있습니다. OpenTelemetry는 로그 라우팅 또는 필터링을 제어하지 않습니다. 구성에서 ILogger
이러한 결정을 내립니다.
ILogger
을(를) 설정하는 방법에 대한 자세한 내용은 로깅 구성을 참조하세요.
자세한 ILogger
내용은 C# 및 .NET의 로깅 및코드 예제를 참조하세요.
Azure Monitor 내보내기는 계측 라이브러리를 포함하지 않습니다.
다음 코드 샘플을 사용하여 Azure SDK(소프트웨어 개발 키트) 에서 종속성을 수집하여 원본을 수동으로 구독할 수 있습니다.
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
// The following line subscribes to dependencies emitted from Azure SDKs
.AddSource("Azure.*")
.AddAzureMonitorTraceExporter()
.AddHttpClientInstrumentation(o => o.FilterHttpRequestMessage = (_) =>
{
// Azure SDKs create their own client span before calling the service using HttpClient
// In this case, we would see two spans corresponding to the same operation
// 1) created by Azure SDK 2) created by HttpClient
// To prevent this duplication we are filtering the span from HttpClient
// as span from Azure SDK contains all relevant information needed.
var parentActivity = Activity.Current?.Parent;
if (parentActivity != null && parentActivity.Source.Name.Equals("Azure.Core.Http"))
{
return false;
}
return true;
})
.Build();
Azure Monitor로 전송되는 로그 수를 줄이거나 늘리려면 적절한 로그 수준을 설정하거나 필터를 적용하도록 로깅을 구성합니다. 예를 들어 OpenTelemetry/Azure Monitor에만 Warning
Error
로그를 보내도록 선택할 수 있습니다. OpenTelemetry는 로그 라우팅 또는 필터링을 제어하지 않습니다. 구성에서 ILogger
이러한 결정을 내립니다.
ILogger
을(를) 설정하는 방법에 대한 자세한 내용은 로깅 구성을 참조하세요.
요청
- Java 메시지 서비스(JMS) 소비자
- Kafka 소비자
- Netty
- 석영
- RabbitMQ
- 서블릿
- Spring 일정
참고 항목
Servlet 및 Netty 자동 침입은 Java EE, Jakarta EE, Spring Boot, Quarkus 및 Micronaut
을 비롯한 대부분의 Java HTTP 서비스를 포함합니다.
종속성(다운스트림 분산 추적 전파 포함)
- Apache HttpClient
- Apache HttpAsyncClient
- AsyncHttpClient
- Google HttpClient
- gRPC
- java.net.HttpURLConnection
- Java 11 HttpClient
- JAX-RS 클라이언트
- 제티(HttpClient)
- JMS
- Kafka
- Netty 클라이언트
- OkHttp
- RabbitMQ
종속성(다운스트림 분산 추적 전파 제외)
- Cassandra를 지원합니다.
- JDBC(Java Database Connectivity) 지원
- MongoDB(비동기 및 동기화)를 지원합니다.
- Redis 지원(lettuce 및 jedis)
메트릭
- Spring Boot Actuator 메트릭을 포함한 마이크로미터 메트릭
- JMX(Java Management Extensions) 메트릭
로그
- Logback(MDC 속성 포함)¹
- Log4j(MDC/스레드 컨텍스트 속성 포함) 1
- JBoss 로깅(MDC 속성 포함) 1
- java.util.logging
Azure Monitor에서 수집하는 로그 수를 줄이거나 늘리려면 먼저 애플리케이션의 로깅 라이브러리에서 원하는 로깅 수준(예: WARNING
또는 ERROR
)을 설정합니다.
기본 컬렉션
다음 Azure SDK에서 내보낸 원격 분석은 기본적으로 자동으로 수집됩니다.
[//]: # "Azure Cosmos DB 4.22.0+ due to https://github.com/Azure/azure-sdk-for-java/pull/25571"
[//]: # "the remaining above names and links scraped from https://azure.github.io/azure-sdk/releases/latest/java.html"
[//]: # "and version synched manually against the oldest version in maven central built on azure-core 1.14.0"
[//]: # ""
[//]: # "var table = document.querySelector('#tg-sb-content > div > table')"
[//]: # "var str = ''"
[//]: # "for (var i = 1, row; row = table.rows[i]; i++) {"
[//]: # " var name = row.cells[0].getElementsByTagName('div')[0].textContent.trim()"
[//]: # " var stableRow = row.cells[1]"
[//]: # " var versionBadge = stableRow.querySelector('.badge')"
[//]: # " if (!versionBadge) {"
[//]: # " continue"
[//]: # " }"
[//]: # " var version = versionBadge.textContent.trim()"
[//]: # " var link = stableRow.querySelectorAll('a')[2].href"
[//]: # " str += '* [' + name + '](' + link + ') ' + version + '\n'"
[//]: # "}"
[//]: # "console.log(str)"
Spring Boot 네이티브 애플리케이션에 대한 요청
- Spring Web
- Spring Web MVC(Model-View-Controller)
- Spring WebFlux
Spring Boot 네이티브 애플리케이션에 대한 종속성
메트릭
Spring Boot 네이티브 애플리케이션에 대한 로그
Azure Monitor에서 수집하는 로그 수를 줄이거나 늘리려면 먼저 애플리케이션의 로깅 라이브러리에서 원하는 로깅 수준(예: WARNING
또는 ERROR
)을 설정합니다.
Quartz 네이티브 애플리케이션의 경우 Quarkus 설명서를 참조하세요.
다음 OpenTelemetry 계측 라이브러리는 Azure Monitor Application Insights 배포판의 일부로 포함됩니다. 자세한 내용은 JavaScript용 Azure SDK를 참조하세요.
요청
종속성
로그
Azure Monitor에서 수집하는 로그 수를 줄이거나 늘리려면 먼저 애플리케이션의 로깅 라이브러리에서 원하는 로깅 수준(예: WARNING
또는 ERROR
)을 설정합니다.
AzureMonitorOpenTelemetryOptions
를 사용하여 계측을 구성할 수 있습니다.
// Import Azure Monitor OpenTelemetry
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
// Import OpenTelemetry HTTP Instrumentation to get config type
const { HttpInstrumentationConfig } = require("@azure/monitor-opentelemetry");
// Import HTTP to get type
const { IncomingMessage } = require("http");
// Specific Instrumentation configs could be added
const httpInstrumentationConfig: HttpInstrumentationConfig = {
ignoreIncomingRequestHook: (request: IncomingMessage) => {
return false; //Return true if you want to ignore a specific request
},
enabled: true
};
// Instrumentations configuration
const options: AzureMonitorOpenTelemetryOptions = {
instrumentationOptions: {
http: httpInstrumentationConfig,
azureSdk: { enabled: true },
mongoDb: { enabled: true },
mySql: { enabled: true },
postgreSql: { enabled: true },
redis: { enabled: true },
redis4: { enabled: true },
}
};
// Enable Azure Monitor integration
useAzureMonitor(options);
요청
종속성
로그
Azure Monitor에서 수집하는 로그 수를 줄이거나 늘리려면 먼저 애플리케이션의 로깅 라이브러리에서 원하는 로깅 수준(예: WARNING
또는 ERROR
)을 설정합니다.
Python 로깅 라이브러리를 사용하는 예제는 GitHub에서 찾을 수 있습니다.
Azure SDK에서 제공하는 원격 분석은 기본적으로 자동으로 수집됩니다.
각주
- ¹: ‘처리되지 않은/잡히지 않은’ 예외의 자동 보고 지원
- ²: OpenTelemetry 메트릭 지원
팁
계측 라이브러리에서 자동으로 수집되거나 사용자 지정 코딩에서 수동으로 수집되거나 관계없이 모든 OpenTelemetry 메트릭은 현재 청구 목적으로 Application Insights "사용자 지정 메트릭"으로 간주됩니다.
자세히 알아보세요.
OpenTelemetry 커뮤니티에서 계측 라이브러리를 포함하면 더 많은 데이터를 자동으로 수집할 수 있습니다.
주의
커뮤니티 계측 라이브러리의 품질을 지원하거나 보장하지 않습니다. 배포판에 대해 제안하려면 피드백 커뮤니티에 게시하거나 투표하세요. 일부는 실험적 OpenTelemetry 사양을 기반으로 하며 향후 호환성이 손상되는 변경이 발생할 수 있습니다.
커뮤니티 라이브러리를 추가하려면 라이브러리에 대한 NuGet 패키지를 추가한 후 ConfigureOpenTelemetryMeterProvider
또는 ConfigureOpenTelemetryTracerProvider
메서드를 사용합니다.
다음 예제에서는 추가 메트릭을 수집하기 위해 런타임 계측 을 추가하는 방법을 보여 줍니다.
dotnet add package OpenTelemetry.Instrumentation.Runtime
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add runtime instrumentation.
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddRuntimeInstrumentation());
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
다음 예제에서는 추가 메트릭을 수집하기 위해 런타임 계측 을 추가하는 방법을 보여 줍니다.
// Create a new OpenTelemetry meter provider and add runtime instrumentation and the Azure Monitor metric exporter.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
.AddRuntimeInstrumentation()
.AddAzureMonitorMetricExporter();
커뮤니티 계측 라이브러리를 사용하여 Java 배포판을 확장할 수 없습니다. 다른 계측 라이브러리를 포함하도록 요청하려면 GitHub 페이지에서 문제를 엽니다.
다음 단계에서 GitHub 페이지에 대한 링크를 찾을 수 있습니다.
GraalVM Java 네이티브 애플리케이션에서는 커뮤니티 계측 라이브러리를 사용할 수 없습니다.
다른 OpenTelemetry 계측은 여기에서 사용할 수 있으며 ApplicationInsightsClient에서 TraceHandler를 사용하여 추가할 수 있습니다.
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics, trace, ProxyTracerProvider } = require("@opentelemetry/api");
// Import the OpenTelemetry instrumentation registration function and Express instrumentation
const { registerInstrumentations } = require( "@opentelemetry/instrumentation");
const { ExpressInstrumentation } = require('@opentelemetry/instrumentation-express');
// Get the OpenTelemetry tracer provider and meter provider
const tracerProvider = (trace.getTracerProvider() as ProxyTracerProvider).getDelegate();
const meterProvider = metrics.getMeterProvider();
// Enable Azure Monitor integration
useAzureMonitor();
// Register the Express instrumentation
registerInstrumentations({
// List of instrumentations to register
instrumentations: [
new ExpressInstrumentation(), // Express instrumentation
],
// OpenTelemetry tracer provider
tracerProvider: tracerProvider,
// OpenTelemetry meter provider
meterProvider: meterProvider
});
커뮤니티 계측 라이브러리(공식적으로 지원/Azure Monitor 배포판에 포함되지 않음)를 추가하려면 계측을 사용하여 직접 계측할 수 있습니다. 커뮤니티 계측 라이브러리 목록은 여기에서 찾을 수 있습니다.
참고 항목
지원되는 계측 라이브러리를 instrument()
및 배포판 configure_azure_monitor()
과 함께 수동으로 계측하는 것은 권장되지 않습니다. 지원되지 않는 시나리오이며, 원격 분석에서 예기치 않은 결과가 발생할 수 있습니다.
# Import the `configure_azure_monitor()`, `SQLAlchemyInstrumentor`, `create_engine`, and `text` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
from sqlalchemy import create_engine, text
# Configure OpenTelemetry to use Azure Monitor.
configure_azure_monitor()
# Create a SQLAlchemy engine.
engine = create_engine("sqlite:///:memory:")
# SQLAlchemy instrumentation is not officially supported by this package, however, you can use the OpenTelemetry `instrument()` method manually in conjunction with `configure_azure_monitor()`.
SQLAlchemyInstrumentor().instrument(
engine=engine,
)
# Database calls using the SQLAlchemy library will be automatically captured.
with engine.connect() as conn:
result = conn.execute(text("select 'hello world'"))
print(result.all())
사용자 지정 원격 분석 수집
이 섹션에서는 애플리케이션에서 사용자 지정 원격 분석을 수집하는 방법을 설명합니다.
언어 및 신호 유형에 따라 다음을 포함하여 사용자 지정 원격 분석을 수집하는 다양한 방법이 있습니다.
- 오픈텔레메트리 API
- 언어별 로깅/메트릭 라이브러리
- Application Insights 클래식 API
다음 표는 현재 지원되는 사용자 지정 원격 분석 유형을 나타냅니다.
언어 |
사용자 지정 이벤트 |
사용자 지정 메트릭 |
종속성 |
예외 |
페이지 보기 |
요청 |
흔적 |
ASP.NET Core |
|
|
|
|
|
|
|
OpenTelemetry API |
|
예 |
예 |
예 |
|
예 |
|
ILogger API |
|
|
|
|
|
|
예 |
AI 클래식 API |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
자바 |
|
|
|
|
|
|
|
OpenTelemetry API |
|
예 |
예 |
예 |
|
예 |
|
Logback, Log4j , JUL |
|
|
|
예 |
|
|
예 |
마이크로미터 메트릭 |
|
예 |
|
|
|
|
|
AI 클래식 API |
예 |
예 |
예 |
예 |
예 |
예 |
예 |
|
|
|
|
|
|
|
|
Node.js |
|
|
|
|
|
|
|
OpenTelemetry API |
|
예 |
예 |
예 |
|
예 |
|
|
|
|
|
|
|
|
|
파이썬 |
|
|
|
|
|
|
|
OpenTelemetry API |
|
예 |
예 |
예 |
|
예 |
|
Python 로깅 모듈 |
|
|
|
|
|
|
예 |
이벤트 확장 |
예 |
|
|
|
|
|
예 |
참고 항목
Application Insights Java 3.x 및 Application Insights Node.js 3.x는 Application Insights 클래식 API에서 원격 분석을 수집합니다. 이 동작은 업그레이드를 간소화하고 OpenTelemetry API에 모든 사용자 지정 원격 분석 유형이 포함될 때까지 사용자 지정 원격 분석을 일시적으로 지원합니다.
사용자 지정 메트릭 추가
이 컨텍스트에서 사용자 지정 메트릭 용어는 OpenTelemetry 계측 라이브러리가 자동으로 수집하는 것 이상으로 추가 메트릭을 수집하기 위해 코드를 수동으로 계측하는 것을 의미합니다.
OpenTelemetry API는 다양한 메트릭 시나리오를 처리하기 위해 6개의 메트릭 "계측기"를 제공하며 메트릭 탐색기에서 메트릭을 시각화할 때 올바른 "집계 형식"을 선택해야 합니다. 이 요구 사항은 OpenTelemetry Metric API를 사용하여 메트릭을 전송하고 계측 라이브러리를 사용할 때 적용됩니다.
다음 표에서는 각 OpenTelemetry 메트릭 계측에 대해 권장되는 집계 형식 을 보여줍니다.
OpenTelemetry 계측기 |
Azure Monitor 집계 형식 |
카운터 |
합계 |
비동기 카운터 |
합계 |
히스토그램 |
최소, 최대, 평균, 합계 및 개수 |
비동기 계기 |
평균 |
업다운 카운터 |
합계 |
비동기식 UpDownCounter |
합계 |
주의
대부분의 경우 다른 집계 형식은 의미가 없습니다.
OpenTelemetry 사양은 계측을 설명하고 각 계측을 사용할 수 있는 경우의 예를 제공합니다.
팁
히스토그램은 Application Insights GetMetric Classic API와 가장 다재다능하고 가장 유사합니다. Azure Monitor는 현재 히스토그램 계측기를 지원되는 5가지 집계 형식으로 평면화하며 백분위수 지원이 진행 중입니다. 다재다능하지는 않지만 다른 OpenTelemetry 계측은 애플리케이션의 성능에 미치는 영향이 적습니다.
히스토그램 예
애플리케이션 시작은 이름으로 미터를 구독해야 합니다.
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add a meter named "OTel.AzureMonitor.Demo".
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
동일한 이름을 사용하여 Meter
를 초기화해야 합니다.
// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");
// Create a new histogram metric named "FruitSalePrice".
Histogram<long> myFruitSalePrice = meter.CreateHistogram<long>("FruitSalePrice");
// Create a new Random object.
var rand = new Random();
// Record a few random sale prices for apples and lemons, with different colors.
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "green"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
public class Program
{
// Create a static readonly Meter object named "OTel.AzureMonitor.Demo".
// This meter will be used to track metrics about the application.
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
// Create a new MeterProvider object using the OpenTelemetry SDK.
// The MeterProvider object is responsible for managing meters and sending
// metric data to exporters.
// It is important to keep the MetricsProvider instance active
// throughout the process lifetime.
//
// The MeterProviderBuilder is configured to add a meter named
// "OTel.AzureMonitor.Demo" and an Azure Monitor metric exporter.
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
// Create a new Histogram metric named "FruitSalePrice".
// This metric will track the distribution of fruit sale prices.
Histogram<long> myFruitSalePrice = meter.CreateHistogram<long>("FruitSalePrice");
// Create a new Random object. This object will be used to generate random sale prices.
var rand = new Random();
// Record a few random sale prices for apples and lemons, with different colors.
// Each record includes a timestamp, a value, and a set of attributes.
// The attributes can be used to filter and analyze the metric data.
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "green"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
// Display a message to the user and wait for them to press Enter.
// This allows the user to see the message and the console before the
// application exits.
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
}
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.metrics.DoubleHistogram;
import io.opentelemetry.api.metrics.Meter;
public class Program {
public static void main(String[] args) {
Meter meter = GlobalOpenTelemetry.getMeter("OTEL.AzureMonitor.Demo");
DoubleHistogram histogram = meter.histogramBuilder("histogram").build();
histogram.record(1.0);
histogram.record(100.0);
histogram.record(30.0);
}
}
OpenTelemetry
를 삽입합니다.
히스토그램 만들기:
import io.opentelemetry.api.metrics.DoubleHistogram;
import io.opentelemetry.api.metrics.Meter;
Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
DoubleHistogram histogram = meter.histogramBuilder("histogram").build();
histogram.record(1.0);
histogram.record(100.0);
histogram.record(30.0);
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the meter for the "testMeter" namespace
const meter = metrics.getMeter("testMeter");
// Create a histogram metric
let histogram = meter.createHistogram("histogram");
// Record values to the histogram metric with different tags
histogram.record(1, { "testKey": "testValue" });
histogram.record(30, { "testKey": "testValue2" });
histogram.record(100, { "testKey2": "testValue" });
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
import os
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# Get a meter provider and a meter with the name "otel_azure_monitor_histogram_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_histogram_demo")
# Record three values to the histogram.
histogram = meter.create_histogram("histogram")
histogram.record(1.0, {"test_key": "test_value"})
histogram.record(100.0, {"test_key2": "test_value"})
histogram.record(30.0, {"test_key": "test_value2"})
# Wait for background execution.
input()
카운터 예제
애플리케이션 시작은 이름으로 미터를 구독해야 합니다.
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add a meter named "OTel.AzureMonitor.Demo".
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
동일한 이름을 사용하여 Meter
를 초기화해야 합니다.
// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");
// Create a new counter metric named "MyFruitCounter".
Counter<long> myFruitCounter = meter.CreateCounter<long>("MyFruitCounter");
// Record the number of fruits sold, grouped by name and color.
myFruitCounter.Add(1, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(2, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(1, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(2, new("name", "apple"), new("color", "green"));
myFruitCounter.Add(5, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(4, new("name", "lemon"), new("color", "yellow"));
public class Program
{
// Create a static readonly Meter object named "OTel.AzureMonitor.Demo".
// This meter will be used to track metrics about the application.
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
// Create a new MeterProvider object using the OpenTelemetry SDK.
// The MeterProvider object is responsible for managing meters and sending
// metric data to exporters.
// It is important to keep the MetricsProvider instance active
// throughout the process lifetime.
//
// The MeterProviderBuilder is configured to add a meter named
// "OTel.AzureMonitor.Demo" and an Azure Monitor metric exporter.
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
// Create a new counter metric named "MyFruitCounter".
// This metric will track the number of fruits sold.
Counter<long> myFruitCounter = meter.CreateCounter<long>("MyFruitCounter");
// Record the number of fruits sold, grouped by name and color.
myFruitCounter.Add(1, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(2, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(1, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(2, new("name", "apple"), new("color", "green"));
myFruitCounter.Add(5, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(4, new("name", "lemon"), new("color", "yellow"));
// Display a message to the user and wait for them to press Enter.
// This allows the user to see the message and the console before the
// application exits.
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
}
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
public class Program {
public static void main(String[] args) {
Meter meter = GlobalOpenTelemetry.getMeter("OTEL.AzureMonitor.Demo");
LongCounter myFruitCounter = meter
.counterBuilder("MyFruitCounter")
.build();
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "green"));
myFruitCounter.add(5, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(4, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
}
}
OpenTelemetry
를 삽입합니다.
카운터 만들기:
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
LongCounter myFruitCounter = meter.counterBuilder("MyFruitCounter")
.build();
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "green"));
myFruitCounter.add(5, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(4, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the meter for the "testMeter" namespace
const meter = metrics.getMeter("testMeter");
// Create a counter metric
let counter = meter.createCounter("counter");
// Add values to the counter metric with different tags
counter.add(1, { "testKey": "testValue" });
counter.add(5, { "testKey2": "testValue" });
counter.add(3, { "testKey": "testValue2" });
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
import os
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# Get a meter provider and a meter with the name "otel_azure_monitor_counter_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_counter_demo")
# Create a counter metric with the name "counter".
counter = meter.create_counter("counter")
# Add three values to the counter.
# The first argument to the `add()` method is the value to add.
# The second argument is a dictionary of dimensions.
# Dimensions are used to group related metrics together.
counter.add(1.0, {"test_key": "test_value"})
counter.add(5.0, {"test_key2": "test_value"})
counter.add(3.0, {"test_key": "test_value2"})
# Wait for background execution.
input()
계기 예
애플리케이션 시작은 이름으로 미터를 구독해야 합니다.
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add a meter named "OTel.AzureMonitor.Demo".
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
동일한 이름을 사용하여 Meter
를 초기화해야 합니다.
// Get the current process.
var process = Process.GetCurrentProcess();
// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");
// Create a new observable gauge metric named "Thread.State".
// This metric will track the state of each thread in the current process.
ObservableGauge<int> myObservableGauge = meter.CreateObservableGauge("Thread.State", () => GetThreadState(process));
private static IEnumerable<Measurement<int>> GetThreadState(Process process)
{
// Iterate over all threads in the current process.
foreach (ProcessThread thread in process.Threads)
{
// Create a measurement for each thread, including the thread state, process ID, and thread ID.
yield return new((int)thread.ThreadState, new("ProcessId", process.Id), new("ThreadId", thread.Id));
}
}
public class Program
{
// Create a static readonly Meter object named "OTel.AzureMonitor.Demo".
// This meter will be used to track metrics about the application.
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
// Create a new MeterProvider object using the OpenTelemetry SDK.
// The MeterProvider object is responsible for managing meters and sending
// metric data to exporters.
// It is important to keep the MetricsProvider instance active
// throughout the process lifetime.
//
// The MeterProviderBuilder is configured to add a meter named
// "OTel.AzureMonitor.Demo" and an Azure Monitor metric exporter.
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
// Get the current process.
var process = Process.GetCurrentProcess();
// Create a new observable gauge metric named "Thread.State".
// This metric will track the state of each thread in the current process.
ObservableGauge<int> myObservableGauge = meter.CreateObservableGauge("Thread.State", () => GetThreadState(process));
// Display a message to the user and wait for them to press Enter.
// This allows the user to see the message and the console before the
// application exits.
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
private static IEnumerable<Measurement<int>> GetThreadState(Process process)
{
// Iterate over all threads in the current process.
foreach (ProcessThread thread in process.Threads)
{
// Create a measurement for each thread, including the thread state, process ID, and thread ID.
yield return new((int)thread.ThreadState, new("ProcessId", process.Id), new("ThreadId", thread.Id));
}
}
}
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.Meter;
public class Program {
public static void main(String[] args) {
Meter meter = GlobalOpenTelemetry.getMeter("OTEL.AzureMonitor.Demo");
meter.gaugeBuilder("gauge")
.buildWithCallback(
observableMeasurement -> {
double randomNumber = Math.floor(Math.random() * 100);
observableMeasurement.record(randomNumber, Attributes.of(AttributeKey.stringKey("testKey"), "testValue"));
});
}
}
OpenTelemetry
를 삽입합니다.
게이지 만들기:
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.Meter;
Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
meter.gaugeBuilder("gauge")
.buildWithCallback(
observableMeasurement -> {
double randomNumber = Math.floor(Math.random() * 100);
observableMeasurement.record(randomNumber, Attributes.of(AttributeKey.stringKey("testKey"), "testValue"));
});
// Import the useAzureMonitor function and the metrics module from the @azure/monitor-opentelemetry and @opentelemetry/api packages, respectively.
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");
// Enable Azure Monitor integration.
useAzureMonitor();
// Get the meter for the "testMeter" meter name.
const meter = metrics.getMeter("testMeter");
// Create an observable gauge metric with the name "gauge".
let gauge = meter.createObservableGauge("gauge");
// Add a callback to the gauge metric. The callback will be invoked periodically to generate a new value for the gauge metric.
gauge.addCallback((observableResult: ObservableResult) => {
// Generate a random number between 0 and 99.
let randomNumber = Math.floor(Math.random() * 100);
// Set the value of the gauge metric to the random number.
observableResult.observe(randomNumber, {"testKey": "testValue"});
});
# Import the necessary packages.
from typing import Iterable
import os
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
from opentelemetry.metrics import CallbackOptions, Observation
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# Get a meter provider and a meter with the name "otel_azure_monitor_gauge_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_gauge_demo")
# Define two observable gauge generators.
# The first generator yields a single observation with the value 9.
# The second generator yields a sequence of 10 observations with the value 9 and a different dimension value for each observation.
def observable_gauge_generator(options: CallbackOptions) -> Iterable[Observation]:
yield Observation(9, {"test_key": "test_value"})
def observable_gauge_sequence(options: CallbackOptions) -> Iterable[Observation]:
observations = []
for i in range(10):
observations.append(
Observation(9, {"test_key": i})
)
return observations
# Create two observable gauges using the defined generators.
gauge = meter.create_observable_gauge("gauge", [observable_gauge_generator])
gauge2 = meter.create_observable_gauge("gauge2", [observable_gauge_sequence])
# Wait for background execution.
input()
사용자 지정 예외 추가
일부 계측 라이브러리는 Application Insights에 대한 예외를 자동으로 보고합니다.
그러나 계측 라이브러리가 보고하는 것 이상의 예외를 수동으로 보고해야 할 수 있습니다.
예를 들어, 코드에서 포착한 예외는 일반적으로 보고되지 않습니다. 실패 섹션 및 엔드투엔드 트랜잭션 보기를 비롯한 관련 환경에서 주의를 끌기 위해 이러한 예외를 보고할 수 있습니다.
작업을 사용하여 예외를 기록하려면:
// Start a new activity named "ExceptionExample".
using (var activity = activitySource.StartActivity("ExceptionExample"))
{
// Try to execute some code.
try
{
throw new Exception("Test exception");
}
// If an exception is thrown, catch it and set the activity status to "Error".
catch (Exception ex)
{
activity?.SetStatus(ActivityStatusCode.Error);
activity?.RecordException(ex);
}
}
ILogger
를 사용하여 예외를 기록하려면:
// Create a logger using the logger factory. The logger category name is used to filter and route log messages.
var logger = loggerFactory.CreateLogger(logCategoryName);
// Try to execute some code.
try
{
throw new Exception("Test Exception");
}
catch (Exception ex)
{
// Log an error message with the exception. The log level is set to "Error" and the event ID is set to 0.
// The log message includes a template and a parameter. The template will be replaced with the value of the parameter when the log message is written.
logger.Log(
logLevel: LogLevel.Error,
eventId: 0,
exception: ex,
message: "Hello {name}.",
args: new object[] { "World" });
}
작업을 사용하여 예외를 기록하려면:
// Start a new activity named "ExceptionExample".
using (var activity = activitySource.StartActivity("ExceptionExample"))
{
// Try to execute some code.
try
{
throw new Exception("Test exception");
}
// If an exception is thrown, catch it and set the activity status to "Error".
catch (Exception ex)
{
activity?.SetStatus(ActivityStatusCode.Error);
activity?.RecordException(ex);
}
}
ILogger
를 사용하여 예외를 기록하려면:
// Create a logger using the logger factory. The logger category name is used to filter and route log messages.
var logger = loggerFactory.CreateLogger("ExceptionExample");
try
{
// Try to execute some code.
throw new Exception("Test Exception");
}
catch (Exception ex)
{
// Log an error message with the exception. The log level is set to "Error" and the event ID is set to 0.
// The log message includes a template and a parameter. The template will be replaced with the value of the parameter when the log message is written.
logger.Log(
logLevel: LogLevel.Error,
eventId: 0,
exception: ex,
message: "Hello {name}.",
args: new object[] { "World" });
}
opentelemetry-api
를 사용하여 범위의 상태를 업데이트하고 예외를 기록할 수 있습니다.
다음과 같이 애플리케이션에 opentelemetry-api-1.0.0.jar
(이상)을 추가합니다.
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
상태를 error
로 설정하고 코드에 예외를 기록합니다.
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
상태를 error
로 설정하고 코드에 예외를 기록합니다.
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
Node.js SDK는 최상위 스팬 또는 원격/내부 스팬의 자식 스팬에 기록된 경우에만 수동으로 기록된 스팬 기반 예외를 Application Insights로 예외로 내보냅니다.
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { trace } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the tracer for the "testTracer" namespace
const tracer = trace.getTracer("testTracer");
// Start a span with the name "hello"
let span = tracer.startSpan("hello");
// Try to throw an error
try {
throw new Error("Test Error");
}
// Catch the error and record it to the span
catch(error){
span.recordException(error);
}
OpenTelemetry Python SDK는 발생한 예외가 자동으로 캡처되고 기록되도록 구현됩니다. 이 동작의 예제는 다음 코드 샘플을 참조하세요.
# Import the necessary packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Get a tracer for the current module.
tracer = trace.get_tracer("otel_azure_monitor_exception_demo")
# Exception events
try:
# Start a new span with the name "hello".
with tracer.start_as_current_span("hello") as span:
# This exception will be automatically recorded
raise Exception("Custom exception message.")
except Exception:
print("Exception raised")
예외를 수동으로 기록하려는 경우 컨텍스트 관리자 내에서 해당 옵션을 사용하지 않도록 설정하고 다음 에제와 같이 record_exception()
을 직접 사용할 수 있습니다.
...
# Start a new span with the name "hello" and disable exception recording.
with tracer.start_as_current_span("hello", record_exception=False) as span:
try:
# Raise an exception.
raise Exception("Custom exception message.")
except Exception as ex:
# Manually record exception
span.record_exception(ex)
...
사용자 지정 범위 추가
두 가지 시나리오에서 사용자 지정 범위를 추가할 수 있습니다. 첫째, 계측 라이브러리에서 아직 수집되지 않은 종속성 요청이 있는 경우입니다. 둘째, 엔드투엔드 트랜잭션 뷰에서 애플리케이션 프로세스를 범위로 모델링하려는 경우입니다.
참고 항목
Activity
네임스페이스의 ActivitySource
및 System.Diagnostics
클래스는 각각 Span
및 Tracer
의 OpenTelemetry 개념을 나타냅니다.
ActivitySource
를 사용하는 대신 생성자를 사용하여 직접 TracerProvider
를 만듭니다. 각 ActivitySource
클래스는 TracerProvider
를 사용하여 AddSource()
에 명시적으로 연결되어야 합니다. OpenTelemetry 추적 API의 일부가 .NET 런타임에 직접 통합되기 때문입니다. 자세한 내용은 OpenTelemetry .NET 추적 API 소개를 참조하세요.
// Define an activity source named "ActivitySourceName". This activity source will be used to create activities for all requests to the application.
internal static readonly ActivitySource activitySource = new("ActivitySourceName");
// Create an ASP.NET Core application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry tracer provider to add a source named "ActivitySourceName". This will ensure that all activities created by the activity source are traced.
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddSource("ActivitySourceName"));
// Add the Azure Monitor telemetry service to the application. This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core application.
var app = builder.Build();
// Map a GET request to the root path ("/") to the specified action.
app.MapGet("/", () =>
{
// Start a new activity named "CustomActivity". This activity will be traced and the trace data will be sent to Azure Monitor.
using (var activity = activitySource.StartActivity("CustomActivity"))
{
// your code here
}
// Return a response message.
return $"Hello World!";
});
// Start the ASP.NET Core application.
app.Run();
StartActivity
의 기본값은 ActivityKind.Internal
이지만 다른 ActivityKind
를 제공할 수 있습니다.
ActivityKind.Client
, ActivityKind.Producer
및 ActivityKind.Internal
은 Application Insights dependencies
에 매핑됩니다.
ActivityKind.Server
및 ActivityKind.Consumer
는 Application Insights requests
에 매핑됩니다.
참고 항목
Activity
네임스페이스의 ActivitySource
및 System.Diagnostics
클래스는 각각 Span
및 Tracer
의 OpenTelemetry 개념을 나타냅니다.
ActivitySource
를 사용하는 대신 생성자를 사용하여 직접 TracerProvider
를 만듭니다. 각 ActivitySource
클래스는 TracerProvider
를 사용하여 AddSource()
에 명시적으로 연결되어야 합니다. OpenTelemetry 추적 API의 일부가 .NET 런타임에 직접 통합되기 때문입니다. 자세한 내용은 OpenTelemetry .NET 추적 API 소개를 참조하세요.
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("ActivitySourceName")
.AddAzureMonitorTraceExporter()
.Build();
// Create an activity source named "ActivitySourceName".
var activitySource = new ActivitySource("ActivitySourceName");
// Start a new activity named "CustomActivity". This activity will be traced and the trace data will be sent to Azure Monitor.
using (var activity = activitySource.StartActivity("CustomActivity"))
{
// your code here
}
StartActivity
의 기본값은 ActivityKind.Internal
이지만 다른 ActivityKind
를 제공할 수 있습니다.
ActivityKind.Client
, ActivityKind.Producer
및 ActivityKind.Internal
은 Application Insights dependencies
에 매핑됩니다.
ActivityKind.Server
및 ActivityKind.Consumer
는 Application Insights requests
에 매핑됩니다.
OpenTelemetry 주석을 사용하세요
고유한 범위를 추가하는 가장 쉬운 방법은 OpenTelemetry의 @WithSpan
주석을 사용하는 것입니다.
범위는 Application Insights의 requests
및 dependencies
테이블을 채웁니다.
다음과 같이 애플리케이션에 opentelemetry-instrumentation-annotations-1.32.0.jar
(이상)을 추가합니다.
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-annotations</artifactId>
<version>1.32.0</version>
</dependency>
@WithSpan
주석을 사용하여 메서드가 실행될 때마다 범위를 내보냅니다.
import io.opentelemetry.instrumentation.annotations.WithSpan;
@WithSpan(value = "your span name")
public void yourMethod() {
}
기본적으로 범위는 종속성 유형이 dependencies
인 InProc
테이블로 지정됩니다.
자동 계측으로 캡처되지 않은 백그라운드 작업을 나타내는 메서드의 경우 kind = SpanKind.SERVER
특성이 Application Insights @WithSpan
테이블에 표시되도록 requests
주석에 적용하는 것이 좋습니다.
OpenTelemetry API 사용
위의 OpenTelemetry @WithSpan
주석이 요구 사항을 충족하지 않는 경우 OpenTelemetry API를 사용하여 범위를 추가할 수 있습니다.
다음과 같이 애플리케이션에 opentelemetry-api-1.0.0.jar
(이상)을 추가합니다.
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
GlobalOpenTelemetry
클래스를 사용하여 Tracer
를 만듭니다.
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = GlobalOpenTelemetry.getTracer("com.example");
범위를 만들고 최신으로 만든 다음, 종료합니다.
Span span = tracer.spanBuilder("my first span").startSpan();
try (Scope ignored = span.makeCurrent()) {
// do stuff within the context of this
} catch (Throwable t) {
span.recordException(t);
} finally {
span.end();
}
OpenTelemetry
를 삽입합니다.
Tracer
를 만듭니다.
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = openTelemetry.getTracer("com.example");
범위를 만들고 최신으로 만든 다음, 종료합니다.
Span span = tracer.spanBuilder("my first span").startSpan();
try (Scope ignored = span.makeCurrent()) {
// do stuff within the context of this
} catch (Throwable t) {
span.recordException(t);
} finally {
span.end();
}
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { trace } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the tracer for the "testTracer" namespace
const tracer = trace.getTracer("testTracer");
// Start a span with the name "hello"
let span = tracer.startSpan("hello");
// End the span
span.end();
OpenTelemetry API를 사용하여 Application Insights의 requests
및 dependencies
테이블에 표시되는 고유한 범위를 추가할 수 있습니다.
이 코드 예제에서는 tracer.start_as_current_span()
메서드를 사용하여 컨텍스트 내에서 범위를 시작하고, 범위를 현재 상태로 만들고, 종료하는 방법을 보여 줍니다.
...
# Import the necessary packages.
from opentelemetry import trace
# Get a tracer for the current module.
tracer = trace.get_tracer(__name__)
# Start a new span with the name "my first span" and make it the current span.
# The "with" context manager starts, makes the span current, and ends the span within it's context
with tracer.start_as_current_span("my first span") as span:
try:
# Do stuff within the context of this span.
# All telemetry generated within this scope will be attributed to this span.
except Exception as ex:
# Record the exception on the span.
span.record_exception(ex)
...
기본적으로 범위는 종속성 유형이 dependencies
인 InProc
테이블에 포함됩니다.
메서드가 자동 계측으로 아직 캡처되지 않은 백그라운드 작업을 나타내는 경우 Application Insights kind = SpanKind.SERVER
테이블에 표시되도록 requests
특성을 설정하는 것이 좋습니다.
...
# Import the necessary packages.
from opentelemetry import trace
from opentelemetry.trace import SpanKind
# Get a tracer for the current module.
tracer = trace.get_tracer(__name__)
# Start a new span with the name "my request span" and the kind set to SpanKind.SERVER.
with tracer.start_as_current_span("my request span", kind=SpanKind.SERVER) as span:
# Do stuff within the context of this span.
...
사용자 지정 이벤트 보내기
Application Insights는 사용자 지정 이벤트를 테이블에 저장합니다 customEvents
.
이를 분석, 필터링 및 시각화하는 한 가지 방법은 Application Insights 사용 환경을 사용하는 것입니다.
클라이언트 쪽 상호 작용 이벤트의 컬렉션을 자동화하려는 경우 JavaScript SDK에서 플러그 인을 사용할 수 있습니다.
사용자 지정 이벤트는 공개 미리 보기로 제공되며 1.3.0-beta.3을 사용합니다 Azure.Monitor.OpenTelemetry.AspNetCore
.
CustomEvent
을 사용하여 ILogger
을 보내려면 메시지 템플릿에서 "microsoft.custom_event.name"
특성을 설정합니다.
// Create a logger factory and configure OpenTelemetry with Azure Monitor
var loggerFactory = LoggerFactory.Create(builder =>
{
builder
.AddOpenTelemetry(options =>
{
options.AddAzureMonitorLogExporter();
});
});
// Create a logger for the specified category
var logger = loggerFactory.CreateLogger(logCategoryName);
// Log a custom event with a custom name and additional attribute
// The 'microsoft.custom_event.name' value will be used as the name of the customEvent
logger.LogInformation("{microsoft.custom_event.name} {additional_attrs}", "test-event-name", "val1");
사용자 지정 이벤트는 공개 미리 보기로 제공되며 1.4.0-beta.3을 사용합니다 Azure.Monitor.OpenTelemetry.Exporter
.
CustomEvent
을 사용하여 ILogger
을 보내려면 메시지 템플릿에서 "microsoft.custom_event.name"
특성을 설정합니다.
// Create a logger factory and configure OpenTelemetry with Azure Monitor
var loggerFactory = LoggerFactory.Create(builder =>
{
builder
.AddOpenTelemetry(options =>
{
options.AddAzureMonitorLogExporter();
});
});
// Create a logger for the specified category
var logger = loggerFactory.CreateLogger(logCategoryName);
// Log a custom event with a custom name and additional attribute
// The 'microsoft.custom_event.name' value will be used as the name of the customEvent
logger.LogInformation("{microsoft.custom_event.name} {additional_attrs}", "test-event-name", "val1");
Java 에이전트를 customEvent
로 보내려면 OpenTelemetry 로그 레코드에서 "microsoft.custom_event.name"
속성을 설정하세요.
Application Insights Java 에이전트가 사용 중인지 또는 자동 구성 SDK에 따라 OpenTelemetry 로거를 가져오는 방식이 약간 다릅니다. 이 세부 정보는 다음 예제에서 자세히 설명합니다.
Application Insights Java 에이전트의 경우:
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.logs.Logger;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.logs.Severity;
Logger logger = GlobalOpenTelemetry.get().getLogsBridge().get("opentelemetry-logger");
logger.logRecordBuilder()
.setAttribute(AttributeKey.stringKey("microsoft.custom_event.name"),"test-event-name")
.setSeverity(Severity.INFO)
.emit();
자동 구성 SDK의 경우:
import com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigure;
import com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigureOptions;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.logs.Logger;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder;
AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder = AutoConfiguredOpenTelemetrySdk.builder();
AzureMonitorAutoConfigureOptions options = new AzureMonitorAutoConfigureOptions();
options.connectionString("<your connection string>");
AzureMonitorAutoConfigure.customize(sdkBuilder, options);
OpenTelemetry openTelemetry = sdkBuilder.build().getOpenTelemetrySdk();
Logger logger = openTelemetry.getLogsBridge().get("opentelemetry-logger");
logger.logRecordBuilder()
.setAttribute(AttributeKey.stringKey("microsoft.custom_event.name"),"test-event-name")
.setSeverity(Severity.INFO)
.emit();
사용자 지정 이벤트를 안정적으로 내보내려면 OpenTelemetry API를 직접 사용합니다. 일부 로깅 프레임워크는 사용자 지정 이벤트 특성 추가 또는 구문 분석을 지원하지 않습니다.
Java 네이티브에서 customEvent
특성을 사용하여 "microsoft.custom_event.name"
을(를) 보낼 수 없습니다.
customEvent
을 사용하여 logger.emit
을 보내려면 로그의 "microsoft.custom_event.name"
객체에서 attributes
속성을 설정하십시오. 필요에 따라 다른 특성을 포함할 수도 있습니다.
// Send a customEvent by including the microsoft attribute key in the log.
// The customEvent name uses the value of that attribute.
logger.emit({
body: 'Hello World!',
attributes: {
"microsoft.custom_event.name": "test-event-name",
"additional_attrs": "val1"
},
});
// You can also populate fields like client_IP with attribute `client.address`
logger.emit({
body: 'This entry will have a custom client_IP',
attributes: {
"microsoft.custom_event.name": "test_event",
"client.address": "192.168.1.1"
},
});
Python에서 customEvent
를 보내려면 "microsoft.custom_event.name"
매개 변수의 extra
특성과 함께 로깅 라이브러리를 사용합니다.
import logging
from azure.monitor.opentelemetry import configure_azure_monitor
# Set up your application logger
logger = logging.getLogger("my-app-logger")
# Configure Azure Monitor to collect logs from the specified logger name
configure_azure_monitor(
logger_name="my-app-logger", # Collect logs from your namespaced logger
)
# Log a custom event with a custom name and additional attribute
# The 'microsoft.custom_event.name' value will be used as the name of the customEvent
logger.warning(
"Hello World!",
extra={
"microsoft.custom_event.name": "test-event-name",
"additional_attrs": "val1"
}
)
# You can also populate fields like client_IP with attribute `client.address`
logger.info(
"This entry will have a custom client_IP",
extra={
"microsoft.custom_event.name": "test_event",
"client.address": "192.168.1.1"
}
)
원격 분석 수정
이 섹션에서는 원격 분석을 수정하는 방법에 대해 설명합니다.
범위 특성 추가
이러한 특성에는 원격 분석에 사용자 지정 속성을 추가하는 것이 포함될 수 있습니다. 특성을 사용하여 클라이언트 IP와 같은 Application Insights 스키마의 선택적 필드를 설정할 수도 있습니다.
범위에 사용자 지정 속성 추가
범위에 추가하는 모든 특성 은 사용자 지정 속성으로 내보내집니다. 요청, 종속성, 추적 또는 예외 테이블의 customDimensions 필드를 채웁니다.
범위 특성을 추가하려면 다음 두 가지 방법 중 하나를 사용합니다.
-
계측 라이브러리에서 제공하는 옵션을 사용합니다.
- 사용자 지정 범위 프로세서를 추가합니다.
팁
사용 가능한 경우 계측 라이브러리에서 제공하는 옵션을 사용하는 이점은 전체 컨텍스트를 사용할 수 있다는 것입니다. 결과적으로 사용자는 더 많은 특성을 추가하거나 필터링하도록 선택할 수 있습니다. 예를 들어 HttpClient 계측 라이브러리의 보강 옵션은 사용자에게 HttpRequestMessage 및 HttpResponseMessage 자체에 대한 액세스 권한을 제공합니다. 여기에서 무엇이든 선택하고 특성으로 저장할 수 있습니다.
많은 계측 라이브러리가 보강 옵션을 제공합니다. 지침은 개별 계측 라이브러리의 추가 정보 파일을 참조하세요.
사용자 지정 프로세서 사용:
팁
Azure Monitor를 추가 하기 전에 여기에 표시된 프로세서를 추가합니다.
// Create an ASP.NET Core application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry tracer provider to add a new processor named ActivityEnrichingProcessor.
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddProcessor(new ActivityEnrichingProcessor()));
// Add the Azure Monitor telemetry service to the application. This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core application.
var app = builder.Build();
// Start the ASP.NET Core application.
app.Run();
다음 코드를 사용하여 프로젝트에 ActivityEnrichingProcessor.cs
를 추가합니다.
public class ActivityEnrichingProcessor : BaseProcessor<Activity>
{
public override void OnEnd(Activity activity)
{
// The updated activity will be available to all processors which are called after this processor.
activity.DisplayName = "Updated-" + activity.DisplayName;
activity.SetTag("CustomDimension1", "Value1");
activity.SetTag("CustomDimension2", "Value2");
}
}
범위 특성을 추가하려면 다음 두 가지 방법 중 하나를 사용합니다.
- 계측 라이브러리에서 제공하는 옵션을 사용합니다.
- 사용자 지정 범위 프로세서를 추가합니다.
팁
사용 가능한 경우 계측 라이브러리에서 제공하는 옵션을 사용하는 이점은 전체 컨텍스트를 사용할 수 있다는 것입니다. 결과적으로 사용자는 더 많은 특성을 추가하거나 필터링하도록 선택할 수 있습니다. 예를 들어 HttpClient 계측 라이브러리의 보강 옵션은 사용자에게 httpRequestMessage 자체에 대한 액세스를 제공합니다. 여기에서 무엇이든 선택하고 특성으로 저장할 수 있습니다.
많은 계측 라이브러리가 보강 옵션을 제공합니다. 지침은 개별 계측 라이브러리의 추가 정보 파일을 참조하세요.
사용자 지정 프로세서 사용:
팁
여기에 표시된 프로세서를 Azure Monitor 내보내기 앞에 추가합니다.
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
// Add a source named "OTel.AzureMonitor.Demo".
.AddSource("OTel.AzureMonitor.Demo") // Add a new processor named ActivityEnrichingProcessor.
.AddProcessor(new ActivityEnrichingProcessor()) // Add the Azure Monitor trace exporter.
.AddAzureMonitorTraceExporter() // Add the Azure Monitor trace exporter.
.Build();
다음 코드를 사용하여 프로젝트에 ActivityEnrichingProcessor.cs
를 추가합니다.
public class ActivityEnrichingProcessor : BaseProcessor<Activity>
{
// The OnEnd method is called when an activity is finished. This is the ideal place to enrich the activity with additional data.
public override void OnEnd(Activity activity)
{
// Update the activity's display name.
// The updated activity will be available to all processors which are called after this processor.
activity.DisplayName = "Updated-" + activity.DisplayName;
// Set custom tags on the activity.
activity.SetTag("CustomDimension1", "Value1");
activity.SetTag("CustomDimension2", "Value2");
}
}
opentelemetry-api
를 사용하여 범위에 특성을 추가할 수 있습니다.
하나 이상의 범위 특성을 추가하면 customDimensions
, requests
, dependencies
또는 traces
테이블의 exceptions
필드가 채워집니다.
다음과 같이 애플리케이션에 opentelemetry-api-1.0.0.jar
(이상)을 추가합니다.
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
코드에 사용자 지정 차원을 추가합니다.
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;
AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");
코드에 사용자 지정 차원을 추가합니다.
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;
AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");
// Import the necessary packages.
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { ReadableSpan, Span, SpanProcessor } = require("@opentelemetry/sdk-trace-base");
const { SemanticAttributes } = require("@opentelemetry/semantic-conventions");
// Create a new SpanEnrichingProcessor class.
class SpanEnrichingProcessor implements SpanProcessor {
forceFlush(): Promise<void> {
return Promise.resolve();
}
shutdown(): Promise<void> {
return Promise.resolve();
}
onStart(_span: Span): void {}
onEnd(span: ReadableSpan) {
// Add custom dimensions to the span.
span.attributes["CustomDimension1"] = "value1";
span.attributes["CustomDimension2"] = "value2";
}
}
// Enable Azure Monitor integration.
const options: AzureMonitorOpenTelemetryOptions = {
// Add the SpanEnrichingProcessor
spanProcessors: [new SpanEnrichingProcessor()]
}
useAzureMonitor(options);
사용자 지정 프로세서 사용:
...
# Import the necessary packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
# Create a SpanEnrichingProcessor instance.
span_enrich_processor = SpanEnrichingProcessor()
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
# Configure the custom span processors to include span enrich processor.
span_processors=[span_enrich_processor],
)
...
다음 코드를 사용하여 프로젝트에 SpanEnrichingProcessor
를 추가합니다.
# Import the SpanProcessor class from the opentelemetry.sdk.trace module.
from opentelemetry.sdk.trace import SpanProcessor
class SpanEnrichingProcessor(SpanProcessor):
def on_end(self, span):
# Prefix the span name with the string "Updated-".
span._name = "Updated-" + span.name
# Add the custom dimension "CustomDimension1" with the value "Value1".
span._attributes["CustomDimension1"] = "Value1"
# Add the custom dimension "CustomDimension2" with the value "Value2".
span._attributes["CustomDimension2"] = "Value2"
사용자 IP 설정
범위에 특성을 설정하여 요청에 대한 client_IP 필드를 채울 수 있습니다. Application Insights는 IP 주소를 사용하여 사용자 위치 특성을 생성한 다음 기본적으로 삭제합니다.
사용자 지정 속성 예제를 사용하지만 다음 코드 줄을 바꿉다.ActivityEnrichingProcessor.cs
// Add the client IP address to the activity as a tag.
// only applicable in case of activity.Kind == Server
activity.SetTag("client.address", "<IP Address>");
사용자 지정 속성 예제를 사용하지만 다음 코드 줄을 바꿉다.ActivityEnrichingProcessor.cs
// Add the client IP address to the activity as a tag.
// only applicable in case of activity.Kind == Server
activity.SetTag("client.address", "<IP Address>");
사용자 지정 속성 예제를 사용하지만 다음 코드 줄을 바꿉다.
...
// Import the SemanticAttributes class from the @opentelemetry/semantic-conventions package.
const { SemanticAttributes } = require("@opentelemetry/semantic-conventions");
// Create a new SpanEnrichingProcessor class.
class SpanEnrichingProcessor implements SpanProcessor {
onEnd(span) {
// Set the HTTP_CLIENT_IP attribute on the span to the IP address of the client.
span.attributes[SemanticAttributes.HTTP_CLIENT_IP] = "<IP Address>";
}
}
사용자 지정 속성 예제를 사용하지만 다음 코드 줄을 바꿉다.SpanEnrichingProcessor.py
# Set the `http.client_ip` attribute of the span to the specified IP address.
span._attributes["http.client_ip"] = "<IP Address>"
사용자 ID 또는 인증된 사용자 ID 설정
다음 지침을 사용하여 요청에 대한 user_Id 또는 user_AuthenticatedId 필드를 채울 수 있습니다. 사용자 ID는 익명 사용자 식별자입니다. 인증된 사용자 ID는 알려진 사용자 식별자입니다.
중요합니다
인증된 사용자 ID를 설정하기 전에 해당 개인 정보 보호법을 참조하세요.
사용자 지정 속성 예제를 사용합니다.
// Add the user ID to the activity as a tag, but only if the activity is not null.
activity?.SetTag("enduser.id", "<User Id>");
사용자 지정 속성 예제를 사용합니다.
// Add the user ID to the activity as a tag, but only if the activity is not null.
activity?.SetTag("enduser.id", "<User Id>");
user ID
, requests
또는 dependencies
테이블의 exceptions
필드를 채웁니다.
다음과 같이 애플리케이션에 opentelemetry-api-1.0.0.jar
(이상)을 추가합니다.
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
코드에 user_Id
를 설정합니다.
import io.opentelemetry.api.trace.Span;
Span.current().setAttribute("enduser.id", "myuser");
user ID
, requests
또는 dependencies
테이블의 exceptions
필드를 채웁니다.
코드에 user_Id
를 설정합니다.
import io.opentelemetry.api.trace.Span;
Span.current().setAttribute("enduser.id", "myuser");
사용자 지정 속성 예제를 사용하지만 다음 코드 줄을 바꿉다.
...
// Import the SemanticAttributes class from the @opentelemetry/semantic-conventions package.
import { SemanticAttributes } from "@opentelemetry/semantic-conventions";
// Create a new SpanEnrichingProcessor class.
class SpanEnrichingProcessor implements SpanProcessor {
onEnd(span: ReadableSpan) {
// Set the ENDUSER_ID attribute on the span to the ID of the user.
span.attributes[SemanticAttributes.ENDUSER_ID] = "<User ID>";
}
}
사용자 지정 속성 예제를 사용하지만 다음 코드 줄을 바꿉다.
# Set the `enduser.id` attribute of the span to the specified user ID.
span._attributes["enduser.id"] = "<User ID>"
로그 특성 추가
OpenTelemetry는 를 사용합니다. NET의 입니다 ILogger
.
메시지 템플릿을 사용하여 로그에 사용자 지정 차원을 연결할 수 있습니다.
OpenTelemetry는 를 사용합니다. NET의 입니다 ILogger
.
메시지 템플릿을 사용하여 로그에 사용자 지정 차원을 연결할 수 있습니다.
Logback, Log4j 및 java.util.logging은 자동으로 계측됩니다. 사용자 지정 차원을 로그에 연결하는 작업은 다음과 같은 방법으로 수행할 수 있습니다.
Spring Boot 네이티브 애플리케이션의 경우 Logback은 기본적으로 계측됩니다.
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const bunyan = require('bunyan');
// Instrumentations configuration
const options: AzureMonitorOpenTelemetryOptions = {
instrumentationOptions: {
// Instrumentations generating logs
bunyan: { enabled: true },
}
};
// Enable Azure Monitor integration
useAzureMonitor(options);
var log = bunyan.createLogger({ name: 'testApp' });
log.info({
"testAttribute1": "testValue1",
"testAttribute2": "testValue2",
"testAttribute3": "testValue3"
}, 'testEvent');
Python 로깅 라이브러리가 자동으로 설치됩니다. 로그의 extra
인수에 사전을 전달하여 사용자 지정 차원을 로그에 연결할 수 있습니다.
...
# Create a warning log message with the properties "key1" and "value1".
logger.warning("WARNING: Warning log with properties", extra={"key1": "value1"})
...
추적 ID 또는 범위 ID를 가져옵니다.
다음 단계를 사용하여 현재 활성 상태인 Span의 Trace ID
및 Span ID
를 가져올 수 있습니다.
참고 항목
Activity
네임스페이스의 ActivitySource
및 System.Diagnostics
클래스는 각각 Span
및 Tracer
의 OpenTelemetry 개념을 나타냅니다. OpenTelemetry 추적 API의 일부가 .NET 런타임에 직접 통합되기 때문입니다. 자세한 내용은 OpenTelemetry .NET 추적 API 소개를 참조하세요.
// Get the current activity.
Activity activity = Activity.Current;
// Get the trace ID of the activity.
string traceId = activity?.TraceId.ToHexString();
// Get the span ID of the activity.
string spanId = activity?.SpanId.ToHexString();
참고 항목
Activity
네임스페이스의 ActivitySource
및 System.Diagnostics
클래스는 각각 Span
및 Tracer
의 OpenTelemetry 개념을 나타냅니다. OpenTelemetry 추적 API의 일부가 .NET 런타임에 직접 통합되기 때문입니다. 자세한 내용은 OpenTelemetry .NET 추적 API 소개를 참조하세요.
// Get the current activity.
Activity activity = Activity.Current;
// Get the trace ID of the activity.
string traceId = activity?.TraceId.ToHexString();
// Get the span ID of the activity.
string spanId = activity?.SpanId.ToHexString();
opentelemetry-api
를 사용하여 추적 ID 또는 범위 ID를 가져올 수 있습니다.
다음과 같이 애플리케이션에 opentelemetry-api-1.0.0.jar
(이상)을 추가합니다.
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
코드에서 요청 추적 ID 및 범위 ID를 가져옵니다.
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
코드에서 요청 추적 ID 및 범위 ID를 가져옵니다.
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
코드에서 요청 추적 ID 및 범위 ID를 가져옵니다.
// Import the trace module from the OpenTelemetry API.
const { trace } = require("@opentelemetry/api");
// Get the span ID and trace ID of the active span.
let spanId = trace.getActiveSpan().spanContext().spanId;
let traceId = trace.getActiveSpan().spanContext().traceId;
코드에서 요청 추적 ID 및 범위 ID를 가져옵니다.
# Import the necessary libraries.
from opentelemetry import trace
# Get the trace ID and span ID of the current span.
trace_id = trace.get_current_span().get_span_context().trace_id
span_id = trace.get_current_span().get_span_context().span_id
다음 단계