이 가이드에서는 Azure Monitor OpenTelemetry 배포판으로 Azure Monitor Application Insights 에서 OTel(OpenTelemetry)을 구성하는 방법을 설명합니다. 적절한 구성은 .NET, Java, Node.js및 Python 애플리케이션에서 일관된 원격 분석 데이터 수집을 보장하여 보다 안정적인 모니터링 및 진단을 가능하게 합니다.
연결 문자열
Application Insights의 연결 문자열은 원격 분석 데이터를 보내기 위한 대상 위치를 정의합니다.
다음 세 가지 방법 중 하나를 사용하여 연결 문자열을 구성합니다.
UseAzureMonitor()
파일에 program.cs
를 추가합니다.
var builder = WebApplication.CreateBuilder(args);
// Add the OpenTelemetry telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor(options => {
options.ConnectionString = "<Your Connection String>";
});
var app = builder.Build();
app.Run();
환경 변수를 설정합니다.
APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
appsettings.json
구성 파일에 다음 섹션을 추가합니다.
{
"AzureMonitor": {
"ConnectionString": "<Your Connection String>"
}
}
참고
둘 이상의 위치에서 연결 문자열을 설정하는 경우 다음 우선순위를 준수합니다.
- 코드
- 환경 변수
- 구성 파일
다음 두 가지 방법 중 하나를 사용하여 연결 문자열을 구성합니다.
애플리케이션 시작 시 각 OpenTelemetry 신호에 Azure Monitor Exporter를 추가해야 합니다.
// Create a new OpenTelemetry tracer provider.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddAzureMonitorTraceExporter(options =>
{
options.ConnectionString = "<Your Connection String>";
})
.Build();
// Create a new OpenTelemetry meter provider.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
.AddAzureMonitorMetricExporter(options =>
{
options.ConnectionString = "<Your Connection String>";
})
.Build();
// Create a new logger factory.
// It is important to keep the LoggerFactory instance active throughout the process lifetime.
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddOpenTelemetry(logging =>
{
logging.AddAzureMonitorLogExporter(options =>
{
options.ConnectionString = "<Your Connection String>";
});
});
});
환경 변수를 설정합니다.
APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
참고
둘 이상의 위치에서 연결 문자열을 설정하는 경우 다음 우선순위를 준수합니다.
- 코드
- 환경 변수
다음 두 가지 방법 중 하나를 사용하여 연결 문자열을 구성합니다.
다음 두 가지 방법 중 하나를 사용하여 연결 문자열을 구성합니다.
환경 변수를 설정합니다.
APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
구성 개체를 사용합니다.
// Import the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions class from the @azure/monitor-opentelemetry package.
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
// Create a new AzureMonitorOpenTelemetryOptions object.
const options: AzureMonitorOpenTelemetryOptions = {
azureMonitorExporterOptions: {
connectionString: "<your connection string>"
}
};
// Enable Azure Monitor integration using the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions object.
useAzureMonitor(options);
다음 두 가지 방법 중 하나를 사용하여 연결 문자열을 구성합니다.
# Import the `configure_azure_monitor()` function from the `azure.monitor.opentelemetry` package.
from azure.monitor.opentelemetry import configure_azure_monitor
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string of your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
클라우드 역할 이름 및 클라우드 역할 인스턴스 설정
지원되는 언어의 경우 Azure Monitor OpenTelemetry Distro는 리소스 컨텍스트를 자동으로 검색하고 구성 요소의 클라우드 역할 이름 및 클라우드 역할 인스턴스 속성에 대한 기본값을 제공합니다. 그러나 기본값을 팀에 적합한 값으로 재정의하는 것이 좋습니다. 클라우드 역할 이름 값은 애플리케이션 맵의 노드 아래에 이름으로 표시됩니다.
리소스 특성을 통해 클라우드 역할 이름 및 클라우드 역할 인스턴스를 설정합니다. Cloud 역할 이름은 service.namespace
및 service.name
특성을 사용하지만 service.name
가 설정되지 않은 경우 service.namespace
으로 대체됩니다. Cloud Role Instance는 service.instance.id
특성 값을 사용합니다. 리소스의 표준 특성에 대한 자세한 내용은 OpenTelemetry 의미 규칙을 참조하세요.
// Setting role name and role instance
// Create a dictionary of resource attributes.
var resourceAttributes = new Dictionary<string, object> {
{ "service.name", "my-service" },
{ "service.namespace", "my-namespace" },
{ "service.instance.id", "my-instance" }};
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Add the OpenTelemetry telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry()
.UseAzureMonitor()
// Configure the ResourceBuilder to add the custom resource attributes to all signals.
// Custom resource attributes should be added AFTER AzureMonitor to override the default ResourceDetectors.
.ConfigureResource(resourceBuilder => resourceBuilder.AddAttributes(resourceAttributes));
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
리소스 특성을 통해 클라우드 역할 이름 및 클라우드 역할 인스턴스를 설정합니다. Cloud 역할 이름은 service.namespace
및 service.name
특성을 사용하지만 service.name
가 설정되지 않은 경우 service.namespace
으로 대체됩니다. Cloud Role Instance는 service.instance.id
특성 값을 사용합니다. 리소스의 표준 특성에 대한 자세한 내용은 OpenTelemetry 의미 규칙을 참조하세요.
// Setting role name and role instance
// Create a dictionary of resource attributes.
var resourceAttributes = new Dictionary<string, object> {
{ "service.name", "my-service" },
{ "service.namespace", "my-namespace" },
{ "service.instance.id", "my-instance" }};
// Create a resource builder.
var resourceBuilder = ResourceBuilder.CreateDefault().AddAttributes(resourceAttributes);
// Create a new OpenTelemetry tracer provider and set the resource builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
var tracerProvider = Sdk.CreateTracerProviderBuilder()
// Set ResourceBuilder on the TracerProvider.
.SetResourceBuilder(resourceBuilder)
.AddAzureMonitorTraceExporter()
.Build();
// Create a new OpenTelemetry meter provider and set the resource builder.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
// Set ResourceBuilder on the MeterProvider.
.SetResourceBuilder(resourceBuilder)
.AddAzureMonitorMetricExporter()
.Build();
// Create a new logger factory and add the OpenTelemetry logger provider with the resource builder.
// It is important to keep the LoggerFactory instance active throughout the process lifetime.
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddOpenTelemetry(logging =>
{
// Set ResourceBuilder on the Logging config.
logging.SetResourceBuilder(resourceBuilder);
logging.AddAzureMonitorLogExporter();
});
});
클라우드 역할 이름을 설정하려면 다음을 수행합니다.
- Spring Boot 네이티브 이미지 애플리케이션에 대해
spring.application.name
사용
- Quarkus 네이티브 이미지 애플리케이션에 대해
quarkus.application.name
사용
리소스 특성을 통해 클라우드 역할 이름 및 클라우드 역할 인스턴스를 설정합니다. Cloud 역할 이름은 service.namespace
및 service.name
특성을 사용하지만 service.name
가 설정되지 않은 경우 service.namespace
으로 대체됩니다. Cloud Role Instance는 service.instance.id
특성 값을 사용합니다. 리소스의 표준 특성에 대한 자세한 내용은 OpenTelemetry 의미 규칙을 참조하세요.
// Import the useAzureMonitor function, the AzureMonitorOpenTelemetryOptions class, the Resource class, and the SemanticResourceAttributes class from the @azure/monitor-opentelemetry, @opentelemetry/resources, and @opentelemetry/semantic-conventions packages, respectively.
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
const { Resource } = require("@opentelemetry/resources");
const { SemanticResourceAttributes } = require("@opentelemetry/semantic-conventions");
// Create a new Resource object with the following custom resource attributes:
//
// * service_name: my-service
// * service_namespace: my-namespace
// * service_instance_id: my-instance
const customResource = new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: "my-service",
[SemanticResourceAttributes.SERVICE_NAMESPACE]: "my-namespace",
[SemanticResourceAttributes.SERVICE_INSTANCE_ID]: "my-instance",
});
// Create a new AzureMonitorOpenTelemetryOptions object and set the resource property to the customResource object.
const options: AzureMonitorOpenTelemetryOptions = {
resource: customResource
};
// Enable Azure Monitor integration using the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions object.
useAzureMonitor(options);
리소스 특성을 통해 클라우드 역할 이름 및 클라우드 역할 인스턴스를 설정합니다. Cloud 역할 이름은 service.namespace
및 service.name
특성을 사용하지만 service.name
가 설정되지 않은 경우 service.namespace
으로 대체됩니다. Cloud Role Instance는 service.instance.id
특성 값을 사용합니다. 리소스의 표준 특성에 대한 자세한 내용은 OpenTelemetry 의미 규칙을 참조하세요.
OTEL_RESOURCE_ATTRIBUTES
및/또는 OTEL_SERVICE_NAME
환경 변수를 사용하여 리소스 특성을 설정합니다.
OTEL_RESOURCE_ATTRIBUTES
는 쉼표로 구분된 일련의 키-값 쌍을 사용합니다. 예를 들어 클라우드 역할 이름을 my-namespace.my-helloworld-service
로 설정하고 클라우드 역할 인스턴스를 my-instance
로 설정하려면 다음과 같이 OTEL_RESOURCE_ATTRIBUTES
및 OTEL_SERVICE_NAME
을 설정할 수 있습니다.
export OTEL_RESOURCE_ATTRIBUTES="service.namespace=my-namespace,service.instance.id=my-instance"
export OTEL_SERVICE_NAME="my-helloworld-service"
service.namespace
리소스 특성을 설정하지 않으면 OTEL_SERVICE_NAME 환경 변수 또는 service.name
리소스 특성만 사용하여 클라우드 역할 이름을 설정할 수 있습니다. 예를 들어 클라우드 역할 이름을 my-helloworld-service
로 설정하고 클라우드 역할 인스턴스를 my-instance
로 설정하려면 다음과 같이 OTEL_RESOURCE_ATTRIBUTES
및 OTEL_SERVICE_NAME
을 설정할 수 있습니다.
export OTEL_RESOURCE_ATTRIBUTES="service.instance.id=my-instance"
export OTEL_SERVICE_NAME="my-helloworld-service"
샘플링 활성화
샘플링을 사용하도록 설정하고 데이터 수집 볼륨을 줄여서 비용을 절감할 수 있습니다. Azure Monitor는 Application Insights가 로 변환하는 샘플링 비율로 이벤트를 채우는 사용자 지정 ItemCount
샘플러를 제공합니다.
고정 속도 샘플러는 정확한 경험과 이벤트 수를 보장합니다. 샘플러는 서비스 전반에서 추적을 보존하도록 설계되었으며 이전 Application Insights SDK(소프트웨어 개발 키트)와 상호 운용 가능합니다. 자세한 내용은 샘플링에 대해 자세히 알아보기를 참조하세요.
참고
메트릭과 로그는 샘플링의 영향을 받지 않습니다.
Application Insights에서 예기치 않은 요금 또는 높은 비용이 표시되는 경우 이 가이드가 도움이 될 수 있습니다. 높은 원격 분석 볼륨, 데이터 수집 급증 및 잘못 구성된 샘플링과 같은 일반적인 원인을 다룹니다. 비용 급증, 원격 분석 볼륨, 샘플링이 작동하지 않음, 데이터 한도, 높은 수집 또는 예기치 않은 청구와 관련된 문제를 해결하는 경우에 특히 유용합니다. 시작하려면 Application Insights에서 높은 데이터 수집 문제 해결을 참조하세요.
샘플러는 0과 1 사이의 샘플 속도를 예상합니다. 0.1의 속도는 추적의 약 10%가 전송됨을 의미합니다.
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Add the OpenTelemetry telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor(options =>
{
// Set the sampling ratio to 10%. This means that 10% of all traces will be sampled and sent to Azure Monitor.
options.SamplingRatio = 0.1F;
});
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
샘플러는 0과 1 사이의 샘플 속도를 예상합니다. 0.1의 속도는 추적의 약 10%가 전송됨을 의미합니다.
// Create a new OpenTelemetry tracer provider.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddAzureMonitorTraceExporter(options =>
{
// Set the sampling ratio to 10%. This means that 10% of all traces will be sampled and sent to Azure Monitor.
options.SamplingRatio = 0.1F;
})
.Build();
3.4.0부터 속도 제한 샘플링을 사용할 수 있으며 이제 기본값입니다. 샘플링에 대한 자세한 내용은 Java 샘플링을 참조하세요.
샘플러는 0과 1 사이의 샘플 속도를 예상합니다. 0.1의 속도는 추적의 약 10%가 전송됨을 의미합니다.
// Import the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions class from the @azure/monitor-opentelemetry package.
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
// Create a new AzureMonitorOpenTelemetryOptions object and set the samplingRatio property to 0.1.
const options: AzureMonitorOpenTelemetryOptions = {
samplingRatio: 0.1
};
// Enable Azure Monitor integration using the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions object.
useAzureMonitor(options);
configure_azure_monitor()
함수는 Application Insights SDK와의 호환성을 위해 ApplicationInsightsSampler를 자동으로 활용하고 원격 분석을 샘플링합니다.
OTEL_TRACES_SAMPLER_ARG
환경 변수를 사용하여 0에서 1까지의 유효한 범위로 샘플링 속도를 지정할 수 있습니다. 여기서 0은 0%이고 1은 100%입니다.
예를 들어 값이 0.1이면 추적의 10%가 전송됩니다.
export OTEL_TRACES_SAMPLER_ARG=0.1
팁
고정 비율/백분율 샘플링을 사용하는 경우 샘플링 속도를 설정해야 할 항목이 확실하지 않은 경우 5%에서 시작합니다. (0.05 샘플링 비율) 오류 및 성능 창에 표시된 작업의 정확도에 따라 속도를 조정합니다. 일반적으로 비율이 높을수록 정확도가 높아집니다. 그러나 ANY 샘플링은 정확도에 영향을 주므로 샘플링의 영향을 받지 않는 OpenTelemetry 메트릭에 대해 경고하는 것이 좋습니다.
라이브 메트릭
라이브 메트릭은 애플리케이션 작업 및 성능에 대한 인사이트를 제공하는 실시간 분석 대시보드를 제공합니다.
이 기능은 기본적으로 활성화되어 있습니다.
사용자는 배포판을 구성할 때 라이브 메트릭을 사용하지 않도록 설정할 수 있습니다.
builder.Services.AddOpenTelemetry().UseAzureMonitor(options => {
// Disable the Live Metrics feature.
options.EnableLiveMetrics = false;
});
이 기능은 Azure Monitor .NET 내보내기 도구에서는 사용할 수 없습니다.
라이브 메트릭은 현재 GraalVM 네이티브 애플리케이션에 사용할 수 없습니다.
사용자는 enableLiveMetrics
속성을 사용하여 배포판을 구성할 때 라이브 메트릭을 사용하거나 사용하지 않도록 설정할 수 있습니다.
const options: AzureMonitorOpenTelemetryOptions = {
azureMonitorExporterOptions: {
connectionString:
process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<your connection string>",
},
enableLiveMetrics: false
};
useAzureMonitor(options);
다음과 같이 Python용 Azure Monitor OpenTelemetry 배포판을 사용하여 라이브 메트릭을 사용하도록 설정할 수 있습니다.
...
configure_azure_monitor(
enable_live_metrics=True
)
...
Azure에 대한 보다 안전한 연결을 위해 Microsoft Entra 인증을 사용하도록 설정하여 권한 없는 원격 분석이 구독에 수집되지 않도록 할 수 있습니다.
자세한 내용은 지원되는 각 언어에 연결된 전용 Microsoft Entra 인증 페이지를 참조하세요.
Entra ID 인증을 구성하는 방법에 대한 자세한 내용은 Application Insights에 대한 Microsoft Entra 인증을 참조 하세요.
Entra ID 인증을 구성하는 방법에 대한 자세한 내용은 Application Insights에 대한 Microsoft Entra 인증을 참조 하세요.
Entra ID 인증을 구성하는 방법에 대한 자세한 내용은 Application Insights에 대한 Microsoft Entra 인증을 참조 하세요.
GraalVM 네이티브 애플리케이션에는 Microsoft Entra ID 인증을 사용할 수 없습니다.
Entra ID 인증을 구성하는 방법에 대한 자세한 내용은 Application Insights에 대한 Microsoft Entra 인증을 참조 하세요.
Entra ID 인증을 구성하는 방법에 대한 자세한 내용은 Application Insights에 대한 Microsoft Entra 인증을 참조 하세요.
오프라인 스토리지 및 자동 다시 시도
Azure Monitor OpenTelemetry 기반 제품은 애플리케이션이 Application Insights에서 연결을 끊고 최대 48시간 동안 전송을 다시 시도하면 원격 분석을 캐시합니다. 데이터 처리 권장 사항은 개인 데이터 내보내기 및 삭제를 참조하세요. 고부하 애플리케이션은 허용되는 시간을 초과하거나 최대 파일 크기를 초과하는 두 가지 이유로 원격 분석을 삭제하는 경우도 있습니다. 필요한 경우 제품은 이전 이벤트보다 최근 이벤트의 우선 순위를 지정합니다.
배포판 패키지에는 기본적으로 오프라인 스토리지에 다음 위치 중 하나를 사용하는 AzureMonitorExporter가 포함되어 있습니다(우선순위에 따라 나열됨).
- Windows
- %LOCALAPPDATA%\Microsoft\AzureMonitor
- %TEMP%\Microsoft\AzureMonitor
- 윈도우가 아닌
- %TMPDIR%/Microsoft/AzureMonitor
- /var/tmp/Microsoft/AzureMonitor
- /tmp/Microsoft/AzureMonitor
기본 디렉터리를 재정의하려면 AzureMonitorOptions.StorageDirectory
를 설정해야 합니다.
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Add the OpenTelemetry telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor(options =>
{
// Set the Azure Monitor storage directory to "C:\\SomeDirectory".
// This is the directory where the OpenTelemetry SDK will store any telemetry data that cannot be sent to Azure Monitor immediately.
options.StorageDirectory = "C:\\SomeDirectory";
});
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
이 기능을 사용하지 않도록 설정하려면 AzureMonitorOptions.DisableOfflineStorage = true
를 설정해야 합니다.
기본적으로 AzureMonitorExporter는 오프라인 스토리지에 대해 다음 위치 중 하나를 사용합니다(우선 순위에 따라 나열됨).
- Windows
- %LOCALAPPDATA%\Microsoft\AzureMonitor
- %TEMP%\Microsoft\AzureMonitor
- 윈도우가 아닌
- %TMPDIR%/Microsoft/AzureMonitor
- /var/tmp/Microsoft/AzureMonitor
- /tmp/Microsoft/AzureMonitor
기본 디렉터리를 재정의하려면 AzureMonitorExporterOptions.StorageDirectory
를 설정해야 합니다.
// Create a new OpenTelemetry tracer provider and set the storage directory.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddAzureMonitorTraceExporter(options =>
{
// Set the Azure Monitor storage directory to "C:\\SomeDirectory".
// This is the directory where the OpenTelemetry SDK will store any trace data that cannot be sent to Azure Monitor immediately.
options.StorageDirectory = "C:\\SomeDirectory";
})
.Build();
// Create a new OpenTelemetry meter provider and set the storage directory.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
.AddAzureMonitorMetricExporter(options =>
{
// Set the Azure Monitor storage directory to "C:\\SomeDirectory".
// This is the directory where the OpenTelemetry SDK will store any metric data that cannot be sent to Azure Monitor immediately.
options.StorageDirectory = "C:\\SomeDirectory";
})
.Build();
// Create a new logger factory and add the OpenTelemetry logger provider with the storage directory.
// It is important to keep the LoggerFactory instance active throughout the process lifetime.
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddOpenTelemetry(logging =>
{
logging.AddAzureMonitorLogExporter(options =>
{
// Set the Azure Monitor storage directory to "C:\\SomeDirectory".
// This is the directory where the OpenTelemetry SDK will store any log data that cannot be sent to Azure Monitor immediately.
options.StorageDirectory = "C:\\SomeDirectory";
});
});
});
이 기능을 사용하지 않도록 설정하려면 AzureMonitorExporterOptions.DisableOfflineStorage = true
를 설정해야 합니다.
에이전트가 Azure Monitor에 원격 분석을 보낼 수 없는 경우 원격 분석 파일을 디스크에 저장합니다. 파일은 시스템 속성으로 telemetry
지정된 디렉터리 아래의 폴더에 java.io.tmpdir
저장됩니다. 각 파일 이름은 타임스탬프로 시작하고 확장명으로 .trn
끝납니다. 이 오프라인 저장 메커니즘은 네트워크가 일시적으로 중단되거나 수집이 실패할 때도 원격 측정 데이터가 보존되도록 합니다.
에이전트는 기본적으로 최대 50MB의 원격 분석 데이터를 저장하고 스토리지 제한을 구성할 수 있습니다. 주기적으로 저장된 원격 분석 데이터를 보내려고 합니다. 48시간보다 오래된 원격 분석 파일이 삭제되고 스토리지 제한에 도달하면 가장 오래된 이벤트가 삭제됩니다.
사용 가능한 구성의 전체 목록은 구성 옵션을 참조하세요.
에이전트가 Azure Monitor에 원격 분석을 보낼 수 없는 경우 원격 분석 파일을 디스크에 저장합니다. 파일은 시스템 속성으로 telemetry
지정된 디렉터리 아래의 폴더에 java.io.tmpdir
저장됩니다. 각 파일 이름은 타임스탬프로 시작하고 확장명으로 .trn
끝납니다. 이 오프라인 저장 메커니즘은 네트워크가 일시적으로 중단되거나 수집이 실패할 때도 원격 측정 데이터가 보존되도록 합니다.
에이전트는 기본적으로 최대 50MB의 원격 분석 데이터를 저장합니다. 주기적으로 저장된 원격 분석 데이터를 보내려고 합니다. 48시간보다 오래된 원격 분석 파일이 삭제되고 스토리지 제한에 도달하면 가장 오래된 이벤트가 삭제됩니다.
기본적으로 AzureMonitorExporter는 오프라인 스토리지에 대해 다음 위치 중 하나를 사용합니다.
- Windows
- %TEMP%\Microsoft\AzureMonitor
- 윈도우가 아닌
- %TMPDIR%/Microsoft/AzureMonitor
- /var/tmp/Microsoft/AzureMonitor
기본 디렉터리를 재정의하려면 storageDirectory
를 설정해야 합니다.
예시:
// Import the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions class from the @azure/monitor-opentelemetry package.
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
// Create a new AzureMonitorOpenTelemetryOptions object and set the azureMonitorExporterOptions property to an object with the following properties:
//
// * connectionString: The connection string for your Azure Monitor Application Insights resource.
// * storageDirectory: The directory where the Azure Monitor OpenTelemetry exporter will store telemetry data when it is offline.
// * disableOfflineStorage: A boolean value that specifies whether to disable offline storage.
const options: AzureMonitorOpenTelemetryOptions = {
azureMonitorExporterOptions: {
connectionString: "<Your Connection String>",
storageDirectory: "C:\\SomeDirectory",
disableOfflineStorage: false
}
};
// Enable Azure Monitor integration using the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions object.
useAzureMonitor(options);
이 기능을 사용하지 않도록 설정하려면 disableOfflineStorage = true
를 설정해야 합니다.
기본적으로 Azure Monitor 내보내기는 다음 경로를 사용합니다.
<tempfile.gettempdir()>/Microsoft/AzureMonitor/opentelemetry-python-<your-instrumentation-key>
기본 디렉터리를 재정의하려면 storage_directory
를 원하는 디렉터리로 설정해야 합니다.
예시:
...
# Configure OpenTelemetry to use Azure Monitor with the specified connection string and storage directory.
# Replace `your-connection-string` with the connection string to your Azure Monitor Application Insights resource.
# Replace `C:\\SomeDirectory` with the directory where you want to store the telemetry data before it is sent to Azure Monitor.
configure_azure_monitor(
connection_string="your-connection-string",
storage_directory="C:\\SomeDirectory",
)
...
이 기능을 사용하지 않도록 설정하려면 disable_offline_storage
를 True
로 설정해야 합니다. 기본값은 False
입니다.
예시:
...
# Configure OpenTelemetry to use Azure Monitor with the specified connection string and disable offline storage.
# Replace `your-connection-string` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="your-connection-string",
disable_offline_storage=True,
)
...
OTLP Exporter 활성화
OTLP(OpenTelemetry Protocol) Exporter를 Azure Monitor Exporter와 함께 활성화하여 원격 분석을 두 곳으로 전송하는 것이 좋습니다.
참고
OTLP Exporter는 편의를 위해서만 표시됩니다. Microsoft는 공식적으로 OTLP Exporter 또는 그 다운스트림의 구성 요소 또는 타사 환경을 지원하지 않습니다.
프로젝트에 OpenTelemetry.Exporter.OpenTelemetryProtocol 패키지를 설치합니다.
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
다음 코드 조각을 추가합니다. 이 예에서는 OTLP 수신기가 실행 중인 OpenTelemetry Collector가 있다고 가정합니다. 자세한 내용은 GitHub의 예를 참조하세요.
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Add the OpenTelemetry telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Add the OpenTelemetry OTLP exporter to the application.
// This exporter will send telemetry data to an OTLP receiver, such as Prometheus
builder.Services.AddOpenTelemetry().WithTracing(builder => builder.AddOtlpExporter());
builder.Services.AddOpenTelemetry().WithMetrics(builder => builder.AddOtlpExporter());
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
프로젝트에 OpenTelemetry.Exporter.OpenTelemetryProtocol 패키지를 설치합니다.
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
다음 코드 조각을 추가합니다. 이 예에서는 OTLP 수신기가 실행 중인 OpenTelemetry Collector가 있다고 가정합니다. 자세한 내용은 GitHub의 예를 참조하세요.
// Create a new OpenTelemetry tracer provider and add the Azure Monitor trace exporter and the OTLP trace exporter.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddAzureMonitorTraceExporter()
.AddOtlpExporter()
.Build();
// Create a new OpenTelemetry meter provider and add the Azure Monitor metric exporter and the OTLP metric exporter.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
.AddAzureMonitorMetricExporter()
.AddOtlpExporter()
.Build();
Azure Monitor Exporter와 OTLP(OpenTelemetry Protocol) Exporter를 동시에 사용하여 원격 분석을 두 위치로 보낼 수 없습니다.
프로젝트에 OpenTelemetry 수집기 추적 내보내기 및 기타 OpenTelemetry 패키지를 설치합니다.
npm install @opentelemetry/api
npm install @opentelemetry/exporter-trace-otlp-http
npm install @opentelemetry/sdk-trace-base
npm install @opentelemetry/sdk-trace-node
다음 코드 조각을 추가합니다. 이 예에서는 OTLP 수신기가 실행 중인 OpenTelemetry Collector가 있다고 가정합니다. 자세한 내용은 GitHub의 예를 참조하세요.
// Import the useAzureMonitor function, the AzureMonitorOpenTelemetryOptions class, the trace module, the ProxyTracerProvider class, the BatchSpanProcessor class, the NodeTracerProvider class, and the OTLPTraceExporter class from the @azure/monitor-opentelemetry, @opentelemetry/api, @opentelemetry/sdk-trace-base, @opentelemetry/sdk-trace-node, and @opentelemetry/exporter-trace-otlp-http packages, respectively.
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
const { BatchSpanProcessor } = require('@opentelemetry/sdk-trace-base');
const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-http');
// Create a new OTLPTraceExporter object.
const otlpExporter = new OTLPTraceExporter();
// Enable Azure Monitor integration.
const options: AzureMonitorOpenTelemetryOptions = {
// Add the SpanEnrichingProcessor
spanProcessors: [new BatchSpanProcessor(otlpExporter)]
}
useAzureMonitor(options);
opentelemetry-exporter-otlp 패키지를 설치합니다.
다음 코드 조각을 추가합니다. 이 예에서는 OTLP 수신기가 실행 중인 OpenTelemetry Collector가 있다고 가정합니다. 자세한 내용은 이 README를 참조하세요.
# Import the `configure_azure_monitor()`, `trace`, `OTLPSpanExporter`, and `BatchSpanProcessor` classes from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace.export import BatchSpanProcessor
# 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 the tracer for the current module.
tracer = trace.get_tracer(__name__)
# Create an OTLP span exporter that sends spans to the specified endpoint.
# Replace `http://localhost:4317` with the endpoint of your OTLP collector.
otlp_exporter = OTLPSpanExporter(endpoint="http://localhost:4317")
# Create a batch span processor that uses the OTLP span exporter.
span_processor = BatchSpanProcessor(otlp_exporter)
# Add the batch span processor to the tracer provider.
trace.get_tracer_provider().add_span_processor(span_processor)
# Start a new span with the name "test".
with tracer.start_as_current_span("test"):
print("Hello world!")
OpenTelemetry 구성
Azure Monitor OpenTelemetry 배포판을 사용하는 동안 환경 변수를 통해 다음 OpenTelemetry 구성에 액세스할 수 있습니다.
환경 변수 |
설명 |
APPLICATIONINSIGHTS_CONNECTION_STRING |
Application Insights 리소스에 대한 연결 문자열로 설정합니다. |
APPLICATIONINSIGHTS_STATSBEAT_DISABLED |
true (으)로 설정하여 내부 메트릭 컬렉션을 옵트아웃하도록 설정하세요. |
OTEL_RESOURCE_ATTRIBUTES |
리소스 특성으로 사용할 키-값 쌍입니다. 리소스 특성에 대한 자세한 내용은 리소스 SDK 사양을 참조하세요. |
OTEL_SERVICE_NAME |
service.name 리소스 특성의 값을 설정합니다.
service.name 도 OTEL_RESOURCE_ATTRIBUTES 에 제공된 경우 OTEL_SERVICE_NAME 이 우선적으로 적용됩니다. |
환경 변수 |
설명 |
APPLICATIONINSIGHTS_CONNECTION_STRING |
Application Insights 리소스에 대한 연결 문자열로 설정합니다. |
APPLICATIONINSIGHTS_STATSBEAT_DISABLED |
true (으)로 설정하여 내부 메트릭 컬렉션을 옵트아웃하도록 설정하세요. |
OTEL_RESOURCE_ATTRIBUTES |
리소스 특성으로 사용할 키-값 쌍입니다. 리소스 특성에 대한 자세한 내용은 리소스 SDK 사양을 참조하세요. |
OTEL_SERVICE_NAME |
service.name 리소스 특성의 값을 설정합니다.
service.name 도 OTEL_RESOURCE_ATTRIBUTES 에 제공된 경우 OTEL_SERVICE_NAME 이 우선적으로 적용됩니다. |
URL 쿼리 문자열 수정
URL 쿼리 문자열을 수정하려면 쿼리 문자열 컬렉션을 해제합니다. SAS 토큰을 사용하여 Azure Storage를 호출하는 경우 이 설정을 사용하는 것이 좋습니다.
Azure.Monitor.OpenTelemetry.AspNetCore 배포판 패키지를 사용하는 경우 ASP.NET Core 및 HttpClient Instrumentation 라이브러리가 모두 포함됩니다.
배포판 패키지는 기본적으로 쿼리 문자열 편집을 해제합니다.
이 동작을 변경하려면 환경 변수를 둘 중 하나 true
또는 false
로 설정해야 합니다.
- ASP.NET Core 계측:
OTEL_DOTNET_EXPERIMENTAL_ASPNETCORE_DISABLE_URL_QUERY_REDACTION
쿼리 문자열 수정은 기본적으로 사용하지 않도록 설정되어 있습니다. 사용하도록 설정하려면 이 환경 변수를 .로 false
설정합니다.
- Http 클라이언트 계측:
OTEL_DOTNET_EXPERIMENTAL_HTTPCLIENT_DISABLE_URL_QUERY_REDACTION
쿼리 문자열 수정은 기본적으로 사용하지 않도록 설정되어 있습니다. 사용하도록 설정하려면 이 환경 변수를 .로 false
설정합니다.
Azure.Monitor.OpenTelemetry.Exporter를 사용하는 경우 OpenTelemetry 구성에 ASP.NET Core 또는 HttpClient Instrumentation 라이브러리를 수동으로 포함해야 합니다.
이러한 계측 라이브러리에는 기본적으로 QueryString 편집이 사용하도록 설정되어 있습니다.
이 동작을 변경하려면 환경 변수를 둘 중 하나 true
또는 false
로 설정해야 합니다.
- ASP.NET Core 계측:
OTEL_DOTNET_EXPERIMENTAL_ASPNETCORE_DISABLE_URL_QUERY_REDACTION
쿼리 문자열 편집은 기본적으로 사용하도록 설정되어 있습니다. 사용하지 않도록 설정하려면 이 환경 변수를 .로 true
설정합니다.
- Http 클라이언트 계측:
OTEL_DOTNET_EXPERIMENTAL_HTTPCLIENT_DISABLE_URL_QUERY_REDACTION
쿼리 문자열 처리 기능은 기본적으로 활성화되어 있습니다. 사용하지 않도록 설정하려면 이 환경 변수를 .로 true
설정합니다.
구성 파일 applicationinsights.json
에 다음을 추가합니다.
{
"preview": {
"processors": [
{
"type": "attribute",
"actions": [
{
"key": "url.query",
"pattern": "^.*$",
"replace": "REDACTED",
"action": "mask"
}
]
},
{
"type": "attribute",
"actions": [
{
"key": "url.full",
"pattern": "[?].*$",
"replace": "?REDACTED",
"action": "mask"
}
]
}
]
}
}
우리는 편집을 지원하기 위해 OpenTelemetry 커뮤니티에서 적극적으로 작업하고 있습니다.
Azure Monitor OpenTelemetry 배포판 패키지를 사용하는 경우, 배포 구성에 범위 프로세서를 만들고 적용하여 쿼리 문자열을 삭제할 수 있습니다.
import { useAzureMonitor, AzureMonitorOpenTelemetryOptions } from "@azure/monitor-opentelemetry";
import { Context } from "@opentelemetry/api";
import { ReadableSpan, Span, SpanProcessor } from "@opentelemetry/sdk-trace-base";
import { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET, SEMATTRS_HTTP_URL } from "@opentelemetry/semantic-conventions";
class RedactQueryStringProcessor implements SpanProcessor {
forceFlush(): Promise<void> {
return Promise.resolve();
}
onStart(span: Span, parentContext: Context): void {
return;
}
shutdown(): Promise<void> {
return Promise.resolve();
}
onEnd(span: ReadableSpan) {
const httpRouteIndex: number = String(span.attributes[SEMATTRS_HTTP_ROUTE]).indexOf('?');
const httpUrlIndex: number = String(span.attributes[SEMATTRS_HTTP_URL]).indexOf('?');
const httpTargetIndex: number = String(span.attributes[SEMATTRS_HTTP_TARGET]).indexOf('?');
if (httpRouteIndex !== -1) {
span.attributes[SEMATTRS_HTTP_ROUTE] = String(span.attributes[SEMATTRS_HTTP_ROUTE]).substring(0, httpRouteIndex);
}
if (httpUrlIndex !== -1) {
span.attributes[SEMATTRS_HTTP_URL] = String(span.attributes[SEMATTRS_HTTP_URL]).substring(0, httpUrlIndex);
}
if (httpTargetIndex !== -1) {
span.attributes[SEMATTRS_HTTP_TARGET] = String(span.attributes[SEMATTRS_HTTP_TARGET]).substring(0, httpTargetIndex);
}
}
}
const options: AzureMonitorOpenTelemetryOptions = {
azureMonitorExporterOptions: {
connectionString: <YOUR_CONNECTION_STRING>,
},
spanProcessors: [new RedactQueryStringProcessor()]
};
useAzureMonitor(options);
우리는 편집을 지원하기 위해 OpenTelemetry 커뮤니티에서 적극적으로 작업하고 있습니다.