このガイドでは、Azure Monitor OpenTelemetry ディストリビューションを使用して Azure Monitor Application Insights で OpenTelemetry (OTel) を構成する方法について説明します。 適切な構成により、.NET、Java、Node.js、Python アプリケーション間で一貫したテレメトリ データ収集が保証され、より信頼性の高い監視と診断が可能になります。
接続文字列
Application Insights 内の接続文字列は、テレメトリ データを送信するためのターゲットの場所を定義します。
接続文字列を構成するには、次の 3 つの方法のいずれかを使用します。
以下のように 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
config ファイルに追加します。
{
"AzureMonitor": {
"ConnectionString": "<Your Connection String>"
}
}
注
接続文字列を複数の場所に設定した場合は、次の優先順位に従います。
- コード
- 環境変数
- 構成ファイル
接続文字列を構成するには、次の 2 つの方法のいずれかを使用します。
アプリケーション起動時の各 OpenTelemetry シグナルに Azure Monitor エクスポーターを追加します。
// 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>
注
接続文字列を複数の場所に設定した場合は、次の優先順位に従います。
- コード
- 環境変数
接続文字列を設定するには、「接続文字列 」を参照してください。
接続文字列を構成するには、次の 2 つの方法のいずれかを使用します。
接続文字列を構成するには、次の 2 つの方法のいずれかを使用します。
環境変数を設定します。
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);
接続文字列を構成するには、次の 2 つの方法のいずれかを使用します。
# 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 はリソース コンテキストを自動的に検出し、コンポーネントのクラウド ロール名とクラウド ロール インスタンスプロパティの既定値を提供します。 ただし、既定値をチームにとって意味のある値にオーバーライドしたい場合があります。 クラウド ロール名の値は、アプリケーション マップでノードの下に名前として表示されます。
リソース属性を使用して、クラウド ロール名とクラウド ロール インスタンスを設定します。 クラウド ロール名は service.namespace
および service.name
属性を使用しますが、service.name
が設定されていない場合は service.namespace
にフォールバックします。 クラウド ロール インスタンスは 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();
リソース属性を使用して、クラウド ロール名とクラウド ロール インスタンスを設定します。 クラウド ロール名は service.namespace
および service.name
属性を使用しますが、service.name
が設定されていない場合は service.namespace
にフォールバックします。 クラウド ロール インスタンスは 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
を使用する
リソース属性を使用して、クラウド ロール名とクラウド ロール インスタンスを設定します。 クラウド ロール名は service.namespace
および service.name
属性を使用しますが、service.name
が設定されていない場合は service.namespace
にフォールバックします。 クラウド ロール インスタンスは 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);
リソース属性を使用して、クラウド ロール名とクラウド ロール インスタンスを設定します。 クラウド ロール名は service.namespace
および service.name
属性を使用しますが、service.name
が設定されていない場合は service.namespace
にフォールバックします。 クラウド ロール インスタンスは 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()
関数は、ApplicationInsightsSampler を自動的に利用して、Application Insights SDK との互換性を確保し、テレメトリをサンプリングします。 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 Distro を使用して有効にすることができます。
...
configure_azure_monitor(
enable_live_metrics=True
)
...
Azure への接続をより安全にするために、Microsoft Entra 認証を有効にすることができます。これにより、不正なテレメトリがサブスクリプションに取り込まれるのを防ぐことができます。
詳細については、サポートされている言語ごとにリンクされている専用の Microsoft Entra 認証ページを参照してください。
Microsoft Entra ID 認証は、GraalVM ネイティブ アプリケーションでは使用できません。
オフライン ストレージと自動再試行
Azure Monitor OpenTelemetry ベースのオファリングでは、アプリケーションが Application Insights から切断されると、テレメトリがキャッシュされ、送信が最大 48 時間再試行されます。 データ処理の推奨事項については、「 プライベート データのエクスポートと削除」を参照してください。 負荷の高いアプリケーションでは、許容時間を超えるか最大ファイル サイズを超えるという 2 つの理由でテレメトリが削除される場合があります。 必要に応じて、製品は古いイベントよりも最近のイベントに優先順位を付けます。
Distro パッケージには AzureMonitorExporter が含まれています。既定では、オフライン ストレージには次のいずれかの場所が使用されます (優先順位の高い順に記載されています)。
- ウィンドウズ
- %LOCALAPPDATA%\Microsoft\AzureMonitor
- %TEMP%\Microsoft\AzureMonitor
- Windows 以外
- %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 はオフライン ストレージに次のいずれかの場所を使用します (優先順位に従って一覧表示されます)。
- ウィンドウズ
- %LOCALAPPDATA%\Microsoft\AzureMonitor
- %TEMP%\Microsoft\AzureMonitor
- Windows 以外
- %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
拡張子で終わります。 このオフライン ストレージ メカニズムは、一時的なネットワークの停止またはインジェストの失敗時にテレメトリが保持されるようにするのに役立ちます。
エージェントは、既定で最大 50 MB のテレメトリ データを格納し、 ストレージ制限の構成を許可します。 保存されているテレメトリの送信が定期的に試行されます。 48 時間より前のテレメトリ ファイルは削除され、ストレージの上限に達すると最も古いイベントが破棄されます。
使用可能な構成の完全な一覧については、「 構成オプション」を参照してください。
エージェントは、Azure Monitor にテレメトリを送信できない場合、テレメトリ ファイルをディスクに格納します。 ファイルは、telemetry
システム プロパティで指定されたディレクトリの下のjava.io.tmpdir
フォルダーに保存されます。 各ファイル名はタイムスタンプで始まり、 .trn
拡張子で終わります。 このオフライン ストレージ メカニズムは、一時的なネットワークの停止またはインジェストの失敗時にテレメトリが保持されるようにするのに役立ちます。
エージェントは、既定で最大 50 MB のテレメトリ データを格納します。 保存されているテレメトリの送信が定期的に試行されます。 48 時間より前のテレメトリ ファイルは削除され、ストレージの上限に達すると最も古いイベントが破棄されます。
既定では、AzureMonitorExporter はオフライン ストレージに次のいずれかの場所を使用します。
- ウィンドウズ
- %TEMP%\Microsoft\AzureMonitor
- Windows 以外
- %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 エクスポーターを有効にする
2 つの場所にテレメトリを送信する場合、Azure Monitor エクスポーターと一緒に OpenTelemetry プロトコル (OTLP) エクスポーターを有効にする必要があります。
注
OTLP エクスポーターは、便宜上表示されているだけです。 Microsoft では、OTLP エクスポーターや、そのすべてのコンポーネントまたはサードパーティ エクスペリエンス ダウンストリームを正式にサポートしていません。
プロジェクトに OpenTelemetry.Exporter.OpenTelemetryProtocol パッケージをインストールします。
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
次のコード スニペットを追加します。 この例では、OpenTelemetry コレクターが OTLP レシーバーと共に実行されることを前提にしています。 詳細については、 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
次のコード スニペットを追加します。 この例では、OpenTelemetry コレクターが OTLP レシーバーと共に実行されることを前提にしています。 詳細については、 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();
2 つの場所にテレメトリを送信する場合、Azure Monitor エクスポーターと一緒に OpenTelemetry プロトコル (OTLP) エクスポーターを有効にできません。
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
次のコード スニペットを追加します。 この例では、OpenTelemetry コレクターが OTLP レシーバーと共に実行されることを前提にしています。 詳細については、 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 パッケージをインストールします。
次のコード スニペットを追加します。 この例では、OpenTelemetry コレクターが OTLP レシーバーと共に実行されることを前提にしています。 詳細については、この 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 の構成
次の OpenTelemetry 構成は、Azure Monitor OpenTelemetry Distros の使用中に環境変数を介してアクセスできます。
環境変数 |
説明 |
APPLICATIONINSIGHTS_CONNECTION_STRING |
これを Application Insights リソースの接続文字列に設定します。 |
APPLICATIONINSIGHTS_STATSBEAT_DISABLED |
これを true に設定して、内部メトリック収集をオプトアウトします。 |
OTEL_RESOURCE_ATTRIBUTES |
リソース属性として使用するキーと値のペア。 リソース属性の詳細については、 Resource 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 |
リソース属性として使用するキーと値のペア。 リソース属性の詳細については、 Resource SDK の仕様を参照してください。 |
OTEL_SERVICE_NAME |
service.name リソース属性の値を設定します。 service.name が OTEL_RESOURCE_ATTRIBUTES でも指定されている場合は、OTEL_SERVICE_NAME が優先されます。 |
URL クエリ文字列を編集する
URL クエリ文字列を編集するには、クエリ文字列コレクションをオフにします。 SAS トークンを使用して Azure ストレージを呼び出す場合は、この設定をお勧めします。
Azure.Monitor.OpenTelemetry.AspNetCore ディストリビューション パッケージを使用している場合は、ASP.NET Core ライブラリと HttpClient インストルメンテーション ライブラリの両方が含まれます。
Microsoft のディストリビューション パッケージでは、クエリ文字列の編集は既定でオフに設定されています。
この動作を変更するには、環境変数を true
か false
のどちらかに設定する必要があります。
- ASP.NET Core インストルメンテーション:
OTEL_DOTNET_EXPERIMENTAL_ASPNETCORE_DISABLE_URL_QUERY_REDACTION
クエリ文字列の編集は既定で無効になっています。 有効にするには、この環境変数を false
に設定します。
- Http Client インストルメンテーション:
OTEL_DOTNET_EXPERIMENTAL_HTTPCLIENT_DISABLE_URL_QUERY_REDACTION
クエリ文字列の編集は既定で無効になっています。 有効にするには、この環境変数を false
に設定します。
Azure.Monitor.OpenTelemetry.Exporter を使用する場合は、ASP.NET Core または HttpClient インストルメンテーション ライブラリを OpenTelemetry 構成に手動で含める必要があります。
これらのインストルメンテーション ライブラリは、既定で QueryString Redaction が有効になっています。
この動作を変更するには、環境変数を true
か false
のどちらかに設定する必要があります。
- ASP.NET Core インストルメンテーション:
OTEL_DOTNET_EXPERIMENTAL_ASPNETCORE_DISABLE_URL_QUERY_REDACTION
クエリ文字列の編集は既定で有効になっています。 無効にするには、この環境変数を true
に設定します。
- Http Client インストルメンテーション:
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 コミュニティでは、編集のサポートに積極的に取り組んでいます。