.NET、Node.js、Python、Java アプリケーション用の Azure Monitor OpenTelemetry を有効にする
[アーティクル]
05/24/2023
23 人の共同作成者
フィードバック
この記事の内容
この記事では、OpenTelemetry ベースのデータ収集を有効にして、Azure Monitor Application Insights 内のエクスペリエンスを強化するように構成する方法について説明します。 「Azure Monitor OpenTelemetry Distro」のインストール方法を説明します。 OpenTelemetry の概念の詳細については、「OpenTelemetry の概要」 または「OpenTelemetry FAQ 」をご覧ください。
OpenTelemetry のリリースの状態
OpenTelemetry オファリングは、.NET、Node.js、Python、Java アプリケーションで使用できます。
Language
リリースの状態
Java
✅1
.NET
⚠️ 2
Node.js
⚠️ 2
Python
⚠️ 2
脚注
作業の開始
このセクションの手順に従い、OpenTelemetry を使用してアプリケーションをインストルメント化します。
前提条件
Java 8 以降を使う Java アプリケーション
Python 3.7 以上を使用する Python アプリケーション
注意事項
OpenTelemetry コミュニティ パッケージと並行して実行されている Azure Monitor OpenTelemetry Distro はテストされていません。 Distro をインストールする前に、OpenTelemetry 関連のパッケージをアンインストールすることをお勧めします。
クライアント ライブラリをインストールする
次のパッケージをインストールします。
npm install applicationinsights@beta
次のパッケージは、この記事で後述する特定のシナリオにも使用されます。
npm install @opentelemetry/api
npm install @opentelemetry/sdk-metrics
npm install @opentelemetry/resources
npm install @opentelemetry/semantic-conventions
npm install @opentelemetry/sdk-trace-base
Azure Monitor Application Insights を有効にする
Azure Monitor Application Insights を有効にするには、アプリケーションに軽微な変更を加え、"接続文字列" を設定します。 接続文字列は、Distro が収集するテレメトリを送信する場所をアプリケーションに通知します。これはユーザーに固有です。
アプリケーションを変更する
アプリケーション スタートアップに UseAzureMonitor()
を追加します。 .NET のバージョンに応じて、これは startup.cs
または program.cs
クラスのいずれかになります。
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenTelemetry().UseAzureMonitor();
var app = builder.Build();
app.Run();
アプリケーション起動時の各 OpenTelemetry シグナルに Azure Monitor エクスポーターを追加します。 .NET のバージョンに応じて、これは startup.cs
または program.cs
クラスのいずれかになります。
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddAzureMonitorTraceExporter();
var metricsProvider = Sdk.CreateMeterProviderBuilder()
.AddAzureMonitorMetricExporter();
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddOpenTelemetry(options =>
{
options.AddAzureMonitorLogExporter();
});
});
Java の自動インストルメンテーションは、構成の変更によって有効になります。コードの変更は必要ありません。
アプリケーションの JVM 引数に -javaagent:"path/to/applicationinsights-agent-3.4.13.jar"
を追加して、JVM が jar ファイルを指すようにします。
const { ApplicationInsightsClient, ApplicationInsightsConfig } = require("applicationinsights");
const config = new ApplicationInsightsConfig();
const appInsights = new ApplicationInsightsClient(config);
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
configure_azure_monitor(
connection_string="<Your Connection String>",
)
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span("hello"):
print("Hello, World!")
input()
Application Insights リソースから接続文字列をコピーします
一意の接続文字列をコピーするには:
Application Insights リソースの [概要] ペインにアクセスしてください。
接続文字列 を見つけます。
接続文字列をポイントし、[クリップボードにコピー] アイコンを選択します。
環境に接続文字列を貼り付ける
接続文字列を貼り付けるには、次のオプションから選択します。
A. 環境変数を使用して設定する (推奨)
次のコマンドの <Your Connection String>
を、独自 の一意の接続文字列に置き換えます。
APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
B. 構成ファイルを使用して設定する - Java のみ (推奨)
次のコンテンツを使って、applicationinsights.json
という名前の構成ファイルを作成し、applicationinsights-agent-3.4.13.jar
と同じディレクトリに配置します。
{
"connectionString": "<Your Connection String>"
}
上記の JSON の <Your Connection String>
を、独自 の一意の接続文字列に置き換えます。
C. コードを使用して設定 - ASP.NET Core、Node.js、Python のみ (非推奨)
コードを使用した接続文字列の設定の例については、「接続文字列の構成 」をご覧ください。
Note
接続文字列を複数の場所に設定する場合は、次の優先順位に従います。
コード
環境変数
構成ファイル
データが流れていることを確認する
アプリケーションを実行し、Azure portal で [Application Insights リソース] タブを開きます。 データがポータルに表示されるまでに数分かかる場合があります。
これで終了です。 アプリケーションは現在、Application Insights によって監視されています。 以下にあるその他すべてはオプションであり、さらにカスタマイズすることができます。
動作していませんか? ASP.NET Core 、Java 、Node.js 、または Python のトラブルシューティング ページを確認してください。
重要
同じ Application Insights リソースにテレメトリを出力しているサービスが 2 つ以上ある場合は、アプリケーション マップ上で正しく表すために、クラウド ロール名を設定する 必要があります。
Application Insights インストルメンテーションの使用時に、診断データが収集され、Microsoft に送信されます。 このデータは、Application Insights の実行と改善に役立ちます。 詳細については、「Azure Application Insights の Statsbeat 」を参照してください。
自動データ収集
ディストリビューションは、OpenTelemetry の「インストルメンテーション ライブラリ」にバンドルすることでデータを自動的に収集します。
インストルメンテーション ライブラリを含む
Azure Monitor エクスポーターにはインストルメンテーション ライブラリは含まれていません。
Requests
JMS コンシューマー
Kafka コンシューマー
Netty
Quartz
RabbitMQ
Servlets
Spring スケジュール
注意
サーブレットおよび 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 クライアント
Jetty HttpClient
JMS
Kafka
Netty クライアント
OkHttp
RabbitMQ
依存関係 (ダウンストリームへの分散トレースの伝達なし):
Cassandra
JDBC
MongoDB (非同期および同期)
Redis (Lettuce および Jedis)
メトリック
Micrometer メトリック (Spring Boot アクチュエータ メトリックを含む)
JMX メトリック
ログ
Logback (MDC のプロパティを含む)1 3
Log4j (MDC/スレッド コンテキストのプロパティを含む)1 3
JBoss ログ (MDC のプロパティを含む)1 3
java.util.logging 1 3
次の Azure SDK によって出力されるテレメトリは、既定で自動収集されます。
Azure Monitor Application Insights Distro の一部として、以下の OpenTelemetry Instrumentation ライブラリが含まれています。
Requests
依存関係
ログ
Requests
依存関係
ログ
Python ログ ライブラリの使用例は、 [GitHub] にあります。
脚注
1 : ハンドルされない例外の自動レポートをサポートします
2 : OpenTelemetry メトリクスをサポートする
3 : デフォルトでは、ログは INFO レベル以上でのみ収集されます。 この設定を変更するには、「構成オプション 」に関する記事を参照してください。
4 : デフォルトでは、ログは WARNING レベル以上でのみ収集されます。
ヒント
現在、OpenTelemetry ベースのオファリングは、すべての OpenTelemetry メトリックをカスタム メトリック とパフォーマンス カウンター としてメトリックス エクスプローラーに出力します。 .NET、Node.js、Python の場合、測定名として設定したものはすべてメトリックの名前空間になります。
OpenTelemetry コミュニティからインストルメンテーション ライブラリを含めると、より多くのデータを自動的に収集できます。
Note
コミュニティインストルメンテーション ライブラリの品質はサポートされておらず、保証できません。 コミュニティインストルメンテーション ライブラリを提案する場合は、 フィードバック コミュニティ にアイデアを投稿またはアップ投票します。
注意事項
インストルメンテーション ライブラリの一部は、試験的な OpenTelemetry のセマンティック仕様に基づいています。 追加すると、将来の破壊的変更に対して脆弱になる可能性があります。
コミュニティ ライブラリを追加するには、 ConfigureOpenTelemetryMeterProvider
メソッドまたは ConfigureOpenTelemetryTraceProvider
メソッドを使用します。
次の例では、追加のメトリックを収集するためにランタイム インストルメンテーション を追加する方法を示します。
var builder = WebApplication.CreateBuilder(args);
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddRuntimeInstrumentation());
builder.Services.AddOpenTelemetry().UseAzureMonitor();
var app = builder.Build();
app.Run();
次の例では、追加のメトリックを収集するためにランタイム インストルメンテーション を追加する方法を示します。
var metricsProvider = Sdk.CreateMeterProviderBuilder()
.AddRuntimeInstrumentation()
.AddAzureMonitorMetricExporter();
コミュニティ インストルメンテーション ライブラリを使用して Java Distro を拡張することはできません。 別のインストルメンテーション ライブラリを含めるように要求するには、GitHub ページで問題を開いてください。 GitHub ページへのリンクについては、[次の手順] を参照してください。
その他の OpenTelemetry インストルメンテーションについては、ApplicationInsightsClient の TraceHandler を使用して追加できます。
const { ApplicationInsightsClient, ApplicationInsightsConfig } = require("applicationinsights");
const { ExpressInstrumentation } = require('@opentelemetry/instrumentation-express');
const appInsights = new ApplicationInsightsClient(new ApplicationInsightsConfig());
const traceHandler = appInsights.getTraceHandler();
traceHandler.addInstrumentation(new ExpressInstrumentation());
カスタム テレメトリを収集する
このセクションでは、アプリケーションからカスタム テレメトリを収集する方法について説明します。
言語とシグナルの種類によって、次のようにさまざまなカスタム テレメトリの収集方法があります。
OpenTelemetry API
言語固有のログとメトリックのライブラリ
Application Insights Classic API
次の表は、現在サポートされているカスタム テレメトリの種類をまとめたものです。
言語
[カスタム イベント]
カスタム メトリック
依存関係
例外
ページ ビュー
Requests
トレース
ASP.NET Core
OpenTelemetry API
はい
Yes
Yes
はい
iLogger API
はい
AI Classic API
Java
OpenTelemetry API
はい
はい
はい
はい
Logback、Log4j、JUL
はい
はい
Micrometer メトリック
はい
AI Classic API
はい
Yes
Yes
Yes
はい
Yes
はい
Node.js
OpenTelemetry API
はい
Yes
Yes
はい
コンソール、Winston、Bunyan
はい
AI Classic API
はい
Yes
Yes
Yes
Yes
Yes
はい
Python
OpenTelemetry API
はい
はい
はい
はい
Python ログ モジュール
はい
Note
Application Insights Java 3.x は、Application Insights Classic API に送信されたテレメトリをリッスンします。 同様に、Application Insights Node.js 3.x は、Application Insights Classic API で作成されたイベントを収集します。 そのため、アップグレードは容易であり、すべてのカスタム テレメトリの種類が OpenTelemetry API 経由でサポートされるまで、カスタム テレメトリ サポートのギャップを埋めることができます。
カスタム メトリックを追加する
Note
カスタム メトリックは、Azure Monitor Application Insights でプレビュー段階にあります。 ディメンションのないカスタム メトリックは、既定で使用できます。 ディメンションを表示してアラートを表示するには、オプトイン する必要があります。
インストルメンテーション ライブラリによって提供されるメトリックを超えた、より多くのメトリックを収集することを検討してください。
OpenTelemetry API には、さまざまなメトリック シナリオに対応する 6 つのメトリック "インストルメント" が用意されており、メトリックス エクスプローラーでメトリックを視覚化する場合は、適切な "集計の種類" を選択する必要があります。 この要件は、OpenTelemetry Metric API を使用してメトリックを送信する場合と、インストルメンテーション ライブラリを使用する場合に当てはまります。
次の表は、OpenTelemetry メトリック インストルメントごとに推奨される 集計の種類 を示しています。
OpenTelemetry インストルメント
Azure Monitor の集計の種類
カウンタ
SUM
非同期カウンター
SUM
ヒストグラム
Min、Max、Average、Sum、Count
非同期ゲージ
Average
UpDownCounter
SUM
非同期 UpDownCounter
SUM
注意
通常、表に表示される以外の集計の種類は意味がありません。
「OpenTelemetry の仕様 」では、インストルメントについて説明し、それぞれを使用する場合の例を示します。
ヒント
ヒストグラムは最も汎用性が高く、Application Insights GetMetric Classic API と最も近いものです。 Azure Monitor では現在、ヒストグラム インストルメントがサポートされている 5 種類の集計にフラット化されており、パーセンタイルのサポートが進行中です。 汎用性は低くなりますが、他の OpenTelemetry インストルメントはアプリケーションのパフォーマンスに与える影響が少なくなります。
ヒストグラム例
アプリケーションの起動では、名前による測定をサブスクライブする必要があります。
var builder = WebApplication.CreateBuilder(args);
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));
builder.Services.AddOpenTelemetry().UseAzureMonitor();
var app = builder.Build();
app.Run();
Meter
は 、同じ名前を使用して初期化する必要があります。
var meter = new Meter("OTel.AzureMonitor.Demo");
Histogram<long> myFruitSalePrice = meter.CreateHistogram<long>("FruitSalePrice");
var rand = new Random();
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
{
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
Histogram<long> myFruitSalePrice = meter.CreateHistogram<long>("FruitSalePrice");
var rand = new Random();
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"));
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);
}
}
const { ApplicationInsightsClient, ApplicationInsightsConfig } = require("applicationinsights");
const appInsights = new ApplicationInsightsClient(new ApplicationInsightsConfig());
const customMetricsHandler = appInsights.getMetricHandler().getCustomMetricsHandler();
const meter = customMetricsHandler.getMeter();
let histogram = meter.createHistogram("histogram");
histogram.record(1, { "testKey": "testValue" });
histogram.record(30, { "testKey": "testValue2" });
histogram.record(100, { "testKey2": "testValue" });
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
configure_azure_monitor(
connection_string="<your-connection-string>",
)
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_histogram_demo")
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"})
input()
カウンターの例
アプリケーションの起動では、名前による測定をサブスクライブする必要があります。
var builder = WebApplication.CreateBuilder(args);
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));
builder.Services.AddOpenTelemetry().UseAzureMonitor();
var app = builder.Build();
app.Run();
Meter
は 、同じ名前を使用して初期化する必要があります。
var meter = new Meter("OTel.AzureMonitor.Demo");
Counter<long> myFruitCounter = meter.CreateCounter<long>("MyFruitCounter");
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
{
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
Counter<long> myFruitCounter = meter.CreateCounter<long>("MyFruitCounter");
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"));
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"));
}
}
const { ApplicationInsightsClient, ApplicationInsightsConfig } = require("applicationinsights");
const appInsights = new ApplicationInsightsClient(new ApplicationInsightsConfig());
const customMetricsHandler = appInsights.getMetricHandler().getCustomMetricsHandler();
const meter = customMetricsHandler.getMeter();
let counter = meter.createCounter("counter");
counter.add(1, { "testKey": "testValue" });
counter.add(5, { "testKey2": "testValue" });
counter.add(3, { "testKey": "testValue2" });
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
configure_azure_monitor(
connection_string="<your-connection-string>",
)
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_counter_demo")
counter = meter.create_counter("counter")
counter.add(1.0, {"test_key": "test_value"})
counter.add(5.0, {"test_key2": "test_value"})
counter.add(3.0, {"test_key": "test_value2"})
input()
ゲージの例
アプリケーションの起動では、名前による測定をサブスクライブする必要があります。
var builder = WebApplication.CreateBuilder(args);
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));
builder.Services.AddOpenTelemetry().UseAzureMonitor();
var app = builder.Build();
app.Run();
Meter
は 、同じ名前を使用して初期化する必要があります。
var process = Process.GetCurrentProcess();
var meter = new Meter("OTel.AzureMonitor.Demo");
ObservableGauge<int> myObservableGauge = meter.CreateObservableGauge("Thread.State", () => GetThreadState(process));
private static IEnumerable<Measurement<int>> GetThreadState(Process process)
{
foreach (ProcessThread thread in process.Threads)
{
yield return new((int)thread.ThreadState, new("ProcessId", process.Id), new("ThreadId", thread.Id));
}
}
public class Program
{
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
var process = Process.GetCurrentProcess();
ObservableGauge<int> myObservableGauge = meter.CreateObservableGauge("Thread.State", () => GetThreadState(process));
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
private static IEnumerable<Measurement<int>> GetThreadState(Process process)
{
foreach (ProcessThread thread in process.Threads)
{
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"));
});
}
}
const { ApplicationInsightsClient, ApplicationInsightsConfig } = require("applicationinsights");
const appInsights = new ApplicationInsightsClient(new ApplicationInsightsConfig());
const customMetricsHandler = appInsights.getMetricHandler().getCustomMetricsHandler();
const meter = customMetricsHandler.getMeter();
let gauge = meter.createObservableGauge("gauge");
gauge.addCallback((observableResult: ObservableResult) => {
let randomNumber = Math.floor(Math.random() * 100);
observableResult.observe(randomNumber, {"testKey": "testValue"});
});
from typing import Iterable
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
from opentelemetry.metrics import CallbackOptions, Observation
configure_azure_monitor(
connection_string="<your-connection-string>",
)
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_gauge_demo")
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
gauge = meter.create_observable_gauge("gauge", [observable_gauge_generator])
gauge2 = meter.create_observable_gauge("gauge2", [observable_gauge_sequence])
input()
カスタム例外の追加
インストルメンテーション ライブラリを選ぶと、Application Insights の例外が自動的に報告されます。
ただし、インストルメンテーション ライブラリで報告される以外の例外を手動で報告することもできます。
たとえば、コードによってキャッチされた例外は、通常は報告されません。 エラー セクションやエンド ツー エンドのトランザクション ビューなど、関連するエクスペリエンスに注意を引くためにそれらを報告することができます。
アクティビティを使用して例外をログに記録するには: using (var activity = activitySource.StartActivity("ExceptionExample"))
{
try
{
throw new Exception("Test exception");
}
catch (Exception ex)
{
activity?.SetStatus(ActivityStatusCode.Error);
activity?.RecordException(ex);
}
}
ILogger を使用して例外をログに記録するには: var logger = loggerFactory.CreateLogger(logCategoryName);
try
{
throw new Exception("Test Exception");
}
catch (Exception ex)
{
logger.Log(
logLevel: LogLevel.Error,
eventId: 0,
exception: ex,
message: "Hello {name}.",
args: new object[] { "World" });
}
アクティビティを使用して例外をログに記録するには: using (var activity = activitySource.StartActivity("ExceptionExample"))
{
try
{
throw new Exception("Test exception");
}
catch (Exception ex)
{
activity?.SetStatus(ActivityStatusCode.Error);
activity?.RecordException(ex);
}
}
ILogger を使用して例外をログに記録するには: var logger = loggerFactory.CreateLogger("ExceptionExample");
try
{
throw new Exception("Test Exception");
}
catch (Exception ex)
{
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.instrumentation</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);
const { ApplicationInsightsClient, ApplicationInsightsConfig } = require("applicationinsights");
const appInsights = new ApplicationInsightsClient(new ApplicationInsightsConfig());
const tracer = appInsights.getTraceHandler().getTracer();
let span = tracer.startSpan("hello");
try{
throw new Error("Test Error");
}
catch(error){
span.recordException(error);
}
OpenTelemetry Python SDK は、スローされた例外が自動的に取り込まれ、記録されるように実装されています。 この動作の例については、次のコード サンプルを参照してください。
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
configure_azure_monitor(
connection_string="<your-connection-string>",
)
tracer = trace.get_tracer("otel_azure_monitor_exception_demo")
# Exception events
try:
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()
を直接使用できます。
...
with tracer.start_as_current_span("hello", record_exception=False) as span:
try:
raise Exception("Custom exception message.")
except Exception as ex:
# Manually record exception
span.record_exception(ex)
...
カスタム スパンを追加する
2 つのシナリオでカスタム スパンを追加することもできます。 最初に、インストルメンテーション ライブラリによってまだ収集されていない依存関係要求がある場合です。 2 つ目は、アプリケーション プロセスをエンドツーエンドのトランザクション ビューのスパンとしてモデル化する場合です。
Note
System.Diagnostics
名前空間の Activity
および ActivitySource
クラスは、それぞれ Span
と Tracer
の OpenTelemetry での概念を表しています。 TracerProvider
を使用する代わりに、コンストラクターを使用して ActivitySource
を直接作成します。 各 ActivitySource
クラスは、AddSource()
を使用して TracerProvider
に明示的に接続する必要があります。 これは、OpenTelemetry トレース API の一部が .NET ランタイムに直接組み込まれているためです。 詳細については、「Introduction to OpenTelemetry .NET Tracing API 」 (OpenTelemetry .NET Tracing API の概要) を参照してください。
internal static readonly ActivitySource activitySource = new("ActivitySourceName");
var builder = WebApplication.CreateBuilder(args);
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddSource("ActivitySourceName"));
builder.Services.AddOpenTelemetry().UseAzureMonitor();
var app = builder.Build();
app.MapGet("/", () =>
{
using (var activity = activitySource.StartActivity("CustomActivity"))
{
// your code here
}
return $"Hello World!";
});
app.Run();
既定では、アクティビティは依存関係の種類が InProc
の Application Insights dependencies
テーブルに配置されます。
インストルメンテーション ライブラリによってキャプチャされないバックグラウンド ジョブを表すコードの場合は、Application Insights の requests
テーブルに確実に表示されるように、StartActivity
メソッドで ActivityKind.Server
を設定することをお勧めします。
Note
System.Diagnostics
名前空間の Activity
および ActivitySource
クラスは、それぞれ Span
と Tracer
の OpenTelemetry での概念を表しています。 TracerProvider
を使用する代わりに、コンストラクターを使用して ActivitySource
を直接作成します。 各 ActivitySource
クラスは、AddSource()
を使用して TracerProvider
に明示的に接続する必要があります。 これは、OpenTelemetry トレース API の一部が .NET ランタイムに直接組み込まれているためです。 詳細については、「Introduction to OpenTelemetry .NET Tracing API 」 (OpenTelemetry .NET Tracing API の概要) を参照してください。
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("ActivitySourceName")
.AddAzureMonitorTraceExporter()
.Build();
var activitySource = new ActivitySource("ActivitySourceName");
using (var activity = activitySource.StartActivity("CustomActivity"))
{
// your code here
}
OpenTelemetry の注釈を使う
独自のスパンを追加する最も簡単な方法は、OpenTelemetry の @WithSpan
注釈を使用することです。
スパンによって、Application Insights の requests
と dependencies
テーブルが入力されます。
opentelemetry-instrumentation-annotations-1.21.0.jar
(以降) をアプリケーションに追加します。
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-annotations</artifactId>
<version>1.21.0</version>
</dependency>
@WithSpan
注釈を使用して、メソッドが実行されるたびにスパンを出力します。
import io.opentelemetry.instrumentation.annotations.WithSpan;
@WithSpan(value = "your span name")
public void yourMethod() {
}
既定では、スパンは最終的に依存関係の種類 InProc
で dependencies
テーブルに入ります。
自動インスツルメンテーションによってキャプチャされないバックグラウンド ジョブを表すメソッドの場合は、属性 kind = SpanKind.SERVER
を @WithSpan
アノテーションに適用して、Application Insights の requests
テーブルに確実に表示されるようにすることをお勧めします。
OpenTelemetry API を使う
前述の OpenTelemetry @WithSpan
注釈がニーズを満たさない場合は、OpenTelemetry API を使用してスパンを追加できます。
opentelemetry-api-1.0.0.jar
(以降) をアプリケーションに追加します。
<dependency>
<groupId>io.opentelemetry.instrumentation</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();
}
const { ApplicationInsightsClient, ApplicationInsightsConfig } = require("applicationinsights");
const appInsights = new ApplicationInsightsClient(new ApplicationInsightsConfig());
const tracer = appInsights.getTraceHandler().getTracer();
let span = tracer.startSpan("hello");
span.end();
OpenTelemetry API を使用して、Application Insights の requests
テーブルと dependencies
テーブルに表示される独自のスパンを追加できます。
このコード例では、tracer.start_as_current_span()
メソッドの使用を開始する方法、スパンを現在のスパンにする方法、およびそのコンテキスト内で終了する方法を示します。
...
from opentelemetry import trace
tracer = trace.get_tracer(__name__)
# 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
except Exception as ex:
span.record_exception(ex)
...
既定では、スパンは依存関係の種類 InProc
で dependencies
テーブルに入ります。
メソッドが自動インスツルメンテーションによってまだキャプチャされていないバックグラウンド ジョブを表す場合は、属性 kind = SpanKind.SERVER
を設定して、Application Insights の requests
テーブルに確実に表示されるようにすることをお勧めします。
...
from opentelemetry import trace
from opentelemetry.trace import SpanKind
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span("my request span", kind=SpanKind.SERVER) as span:
...
Application Insights Classic API を使ってカスタム テレメトリを送信する
可能な限り OpenTelemetry API を使うことをお勧めしますが、Application Insights Classic API を使う必要があるシナリオもいくつかあります。
アプリケーションに applicationinsights-core
を追加します:
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>applicationinsights-core</artifactId>
<version>3.4.13</version>
</dependency>
TelemetryClient
インスタンスを作成します。
static final TelemetryClient telemetryClient = new TelemetryClient();
クライアントを使用してカスタム テレメトリを送信します。
events
telemetryClient.trackEvent("WinGame");
メトリック
telemetryClient.trackMetric("queueLength", 42.0);
依存関係
boolean success = false;
long startTime = System.currentTimeMillis();
try {
success = dependency.call();
} finally {
long endTime = System.currentTimeMillis();
RemoteDependencyTelemetry telemetry = new RemoteDependencyTelemetry();
telemetry.setSuccess(success);
telemetry.setTimestamp(new Date(startTime));
telemetry.setDuration(new Duration(endTime - startTime));
telemetryClient.trackDependency(telemetry);
}
ログ
telemetryClient.trackTrace(message, SeverityLevel.Warning, properties);
例外
try {
...
} catch (Exception e) {
telemetryClient.trackException(e);
}
Get LogHandler
:
const { ApplicationInsightsClient, ApplicationInsightsConfig } = require("applicationinsights");
const appInsights = new ApplicationInsightsClient(new ApplicationInsightsConfig());
const logHandler = appInsights.getLogHandler();
LogHandler
を使用して次のカスタム テレメトリを送信します。
イベント
let eventTelemetry = {
name: "testEvent"
};
logHandler.trackEvent(eventTelemetry);
ログ
let traceTelemetry = {
message: "testMessage",
severity: "Information"
};
logHandler.trackTrace(traceTelemetry);
例外
try {
...
} catch (error) {
let exceptionTelemetry = {
exception: error,
severity: "Critical"
};
logHandler.trackException(exceptionTelemetry);
}
テレメトリの変更
このセクションでは、テレメトリを変更する方法について説明します。
スパン属性を追加する
これらの属性には、テレメトリへのカスタム プロパティの追加が含まれる可能性があります。 また、属性を使用して、Application Insights スキーマに [クライアント IP] などのオプション フィールドを設定することもできます。
スパンにカスタム プロパティを追加する
スパンに追加した属性 は、カスタム プロパティとしてエクスポートされます。 これらは、要求、依存関係、トレース、または例外テーブルの customDimensions フィールドに設定されます。
スパン属性を追加するには、次の 2 つの方法のいずれかを使用します。
ヒント
インストルメンテーション ライブラリで提供されるオプションを使用できる利点は、コンテキスト全体を使用できることです。 その結果、ユーザーは、追加する属性を選択したり、フィルター処理したりできます。 たとえば、HttpClient インストルメンテーション ライブラリの enrich オプションを使用すると、ユーザーは HttpRequestMessage や HttpResponseMessage 自体にアクセスできます。 そこからは何でも選択して、属性として保存できます。
多くのインストルメンテーション ライブラリには、強化オプションが用意されています。 ガイダンスについては、個々のインストルメンテーション ライブラリの Readme ファイルを参照してください。
カスタム プロセッサの使用:
ヒント
ここに示すプロセッサを、Azure Monitor を追加する前に 追加します。
var builder = WebApplication.CreateBuilder(args);
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddProcessor(new ActivityEnrichingProcessor()));
builder.Services.AddOpenTelemetry().UseAzureMonitor();
var app = builder.Build();
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");
}
}
スパン属性を追加するには、次の 2 つの方法のいずれかを使用します。
インストルメンテーション ライブラリで提供されるオプションを使用する。
カスタム スパン プロセッサを追加する。
ヒント
インストルメンテーション ライブラリで提供されるオプションを使用できる利点は、コンテキスト全体を使用できることです。 その結果、ユーザーは、追加する属性を選択したり、フィルター処理したりできます。 たとえば、HttpClient インストルメンテーション ライブラリの enrich オプションを使用すると、ユーザーは httpRequestMessage 自体にアクセスできます。 そこからは何でも選択して、属性として保存できます。
多くのインストルメンテーション ライブラリには、強化オプションが用意されています。 ガイダンスについては、個々のインストルメンテーション ライブラリの Readme ファイルを参照してください。
カスタム プロセッサの使用:
ヒント
ここに示すプロセッサを、Azure Monitor エクスポーターの前に 追加します。
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("OTel.AzureMonitor.Demo")
.AddProcessor(new ActivityEnrichingProcessor())
.AddAzureMonitorTraceExporter()
.Build();
次のコードを使用して、プロジェクトに 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");
}
}
opentelemetry-api
を使用して、スパンに属性を追加することができます。
1 つ以上のスパン属性を追加すると、requests
、dependencies
、traces
、または exceptions
テーブル内の customDimensions
フィールドにデータが入力されます。
opentelemetry-api-1.0.0.jar
(以降) をアプリケーションに追加します。
<dependency>
<groupId>io.opentelemetry.instrumentation</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");
const { ApplicationInsightsClient, ApplicationInsightsConfig } = require("applicationinsights");
const { ReadableSpan, Span, SpanProcessor } = require("@opentelemetry/sdk-trace-base");
const { SemanticAttributes } = require("@opentelemetry/semantic-conventions");
const appInsights = new ApplicationInsightsClient(new ApplicationInsightsConfig());
class SpanEnrichingProcessor implements SpanProcessor{
forceFlush(): Promise<void>{
return Promise.resolve();
}
shutdown(): Promise<void>{
return Promise.resolve();
}
onStart(_span: Span): void{}
onEnd(span: ReadableSpan){
span.attributes["CustomDimension1"] = "value1";
span.attributes["CustomDimension2"] = "value2";
}
}
appInsights.getTraceHandler().addSpanProcessor(new SpanEnrichingProcessor());
カスタム プロセッサの使用:
...
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
configure_azure_monitor(
connection_string="<your-connection-string>",
)
span_enrich_processor = SpanEnrichingProcessor()
# Add the processor shown below to the current `TracerProvider`
trace.get_tracer_provider().add_span_processor(span_enrich_processor)
...
次のコードを使用して、プロジェクトに SpanEnrichingProcessor.py
を追加します。
from opentelemetry.sdk.trace import SpanProcessor
class SpanEnrichingProcessor(SpanProcessor):
def on_end(self, span):
span._name = "Updated-" + span.name
span._attributes["CustomDimension1"] = "Value1"
span._attributes["CustomDimension2"] = "Value2"
ユーザー IP を設定する
スパンに http.client_ip
属性を設定することで、要求の client_IP フィールドにデータを入力できます。 Application Insights では、この IP アドレスを使用してユーザーの位置属性を生成した後、既定でそれを破棄します 。
カスタム プロパティの追加の例 を使用しますが、次の ActivityEnrichingProcessor.cs
のコード行を置き換えます。
// only applicable in case of activity.Kind == Server
activity.SetTag("http.client_ip", "<IP Address>");
カスタム プロパティの追加の例 を使用しますが、次の ActivityEnrichingProcessor.cs
のコード行を置き換えます。
// only applicable in case of activity.Kind == Server
activity.SetTag("http.client_ip", "<IP Address>");
このフィールドは Java によって自動的に設定されます。
カスタム プロパティの追加の例 を使用しますが、次のコード行を置き換えます。
...
const { SemanticAttributes } = require("@opentelemetry/semantic-conventions");
class SpanEnrichingProcessor implements SpanProcessor{
...
onEnd(span){
span.attributes[SemanticAttributes.HTTP_CLIENT_IP] = "<IP Address>";
}
}
カスタム プロパティの追加の例 を使用しますが、次の SpanEnrichingProcessor.py
のコード行を置き換えます。
span._attributes["http.client_ip"] = "<IP Address>"
ユーザー ID または認証されたユーザー ID を設定する
次のガイダンスを参考にして、要求の user_Id または user_AuthenticatedId フィールドを設定できます。 ユーザー ID は匿名のユーザー識別子です。 認証されたユーザー ID は既知のユーザー識別子です。
重要
認証されたユーザー ID を設定する前に、該当するプライバシーに関する法律を調べてください。
[カスタム プロパティの例] の追加を使用します。
activity?.SetTag("enduser.id", "<User Id>");
[カスタム プロパティの例] の追加を使用します。
activity?.SetTag("enduser.id", "<User Id>");
requests
、dependencies
、または exceptions
テーブルの user ID
フィールドに入力します。
opentelemetry-api-1.0.0.jar
(以降) をアプリケーションに追加します。
<dependency>
<groupId>io.opentelemetry.instrumentation</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");
カスタム プロパティの追加の例 を使用しますが、次のコード行を置き換えます。
...
import { SemanticAttributes } from "@opentelemetry/semantic-conventions";
class SpanEnrichingProcessor implements SpanProcessor{
...
onEnd(span: ReadableSpan){
span.attributes[SemanticAttributes.ENDUSER_ID] = "<User ID>";
}
}
カスタム プロパティの追加の例 を使用しますが、次のコード行を置き換えます。
span._attributes["enduser.id"] = "<User ID>"
ログ属性を追加する
OpenTelemetry は .NET の ILogger を使用します。
カスタム ディメンションをログに添付するには、 [メッセージ テンプレート] を使用します。
OpenTelemetry は .NET の ILogger を使用します。
カスタム ディメンションをログに添付するには、 [メッセージ テンプレート] を使用します。
Logback、Log4j、および java.util.logging は自動的にインストルメント化 されます。 カスタム ディメンションのログへのアタッチは、次の方法で実行できます。
属性は、手動で追跡の API を呼び出す場合にのみ追加できます。console、bunyan、winston のログ属性は現在サポートされていません。
const config = new ApplicationInsightsConfig();
config.instrumentations.http = httpInstrumentationConfig;
const appInsights = new ApplicationInsightsClient(config);
const logHandler = appInsights.getLogHandler();
const attributes = {
"testAttribute1": "testValue1",
"testAttribute2": "testValue2",
"testAttribute3": "testValue3"
};
logHandler.trackEvent({
name: "testEvent",
properties: attributes
});
Python ログ ライブラリは、自動インストルメント化 されます。 ログの extra
引数にディクショナリを渡すことで、カスタム ディメンションをログに添付できます。
...
logger.warning("WARNING: Warning log with properties", extra={"key1": "value1"})
...
テレメトリのフィルター処理
テレメトリがアプリケーションから離れる前に、次の方法を使用してテレメトリをフィルター処理できます。
多くのインストルメンテーション ライブラリには、フィルター オプションが用意されています。 ガイダンスについては、個々のインストルメンテーション ライブラリの Readme ファイルを参照してください。
カスタム プロセッサの使用:
ヒント
ここに示すプロセッサを、Azure Monitor を追加する前に 追加します。
var builder = WebApplication.CreateBuilder(args);
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddProcessor(new ActivityFilteringProcessor()));
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddSource("ActivitySourceName"));
builder.Services.AddOpenTelemetry().UseAzureMonitor();
var app = builder.Build();
app.Run();
次のコードを使用して、プロジェクトに ActivityFilteringProcessor.cs
を追加します。
public class ActivityFilteringProcessor : BaseProcessor<Activity>
{
public override void OnStart(Activity activity)
{
// prevents all exporters from exporting internal activities
if (activity.Kind == ActivityKind.Internal)
{
activity.IsAllDataRequested = false;
}
}
}
AddSource("ActivitySourceName")
を使用して特定のソースが明示的に追加されていない場合、そのソースを使用して作成されたアクティビティはエクスポートされません。
多くのインストルメンテーション ライブラリには、フィルター オプションが用意されています。 ガイダンスについては、個々のインストルメンテーション ライブラリの Readme ファイルを参照してください。
カスタム プロセッサの使用:
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("OTel.AzureMonitor.Demo")
.AddProcessor(new ActivityFilteringProcessor())
.AddAzureMonitorTraceExporter()
.Build();
次のコードを使用して、プロジェクトに ActivityFilteringProcessor.cs
を追加します。
public class ActivityFilteringProcessor : BaseProcessor<Activity>
{
public override void OnStart(Activity activity)
{
// prevents all exporters from exporting internal activities
if (activity.Kind == ActivityKind.Internal)
{
activity.IsAllDataRequested = false;
}
}
}
AddSource("ActivitySourceName")
を使用して特定のソースが明示的に追加されていない場合、そのソースを使用して作成されたアクティビティはエクスポートされません。
多くの HTTP インストルメンテーション ライブラリによって提供される URL オプションを除外します。
次の例では、HTTP/HTTPS インストルメンテーション ライブラリ を使用して、特定の URL を追跡から除外する方法を示しています。
const { ApplicationInsightsClient, ApplicationInsightsConfig } = require("applicationinsights");
const { IncomingMessage } = require("http");
const { RequestOptions } = require("https");
const { HttpInstrumentationConfig }= require("@opentelemetry/instrumentation-http");
const httpInstrumentationConfig: HttpInstrumentationConfig = {
enabled: true,
ignoreIncomingRequestHook: (request: IncomingMessage) => {
// Ignore OPTIONS incoming requests
if (request.method === 'OPTIONS') {
return true;
}
return false;
},
ignoreOutgoingRequestHook: (options: RequestOptions) => {
// Ignore outgoing requests with /test path
if (options.path === '/test') {
return true;
}
return false;
}
};
const config = new ApplicationInsightsConfig();
config.instrumentations.http = httpInstrumentationConfig;
const appInsights = new ApplicationInsightsClient(config);
カスタム プロセッサを使用します。 カスタム スパン プロセッサを使用して、特定のスパンをエクスポートから除外できます。 スパンをエクスポートされないようにマークするには、TraceFlag
を DEFAULT
に設定します。
カスタム プロパティの追加の例 を使用しますが、次のコード行を置き換えます。
const { SpanKind, TraceFlags } = require("@opentelemetry/api");
class SpanEnrichingProcessor {
...
onEnd(span) {
if(span.kind == SpanKind.INTERNAL){
span.spanContext().traceFlags = TraceFlags.NONE;
}
}
}
OTEL_PYTHON_EXCLUDED_URLS
環境変数を使用して URL を除外します。
export OTEL_PYTHON_EXCLUDED_URLS="http://localhost:8080/ignore"
これにより、次の Flask の例に示すエンドポイントが除外されます。
...
import flask
from azure.monitor.opentelemetry import configure_azure_monitor
# Configure Azure monitor collection telemetry pipeline
configure_azure_monitor(
connection_string="<your-connection-string>",
)
app = flask.Flask(__name__)
# Requests sent to this endpoint will not be tracked due to
# flask_config configuration
@app.route("/ignore")
def ignore():
return "Request received but not tracked."
...
カスタム プロセッサを使用します。 カスタム スパン プロセッサを使用して、特定のスパンをエクスポートから除外できます。 スパンをエクスポートされないようにマークするには、TraceFlag
を DEFAULT
に設定します。
...
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
configure_azure_monitor(
connection_string="<your-connection-string>",
)
trace.get_tracer_provider().add_span_processor(SpanFilteringProcessor())
...
次のコードを使用して、プロジェクトに SpanFilteringProcessor.py
を追加します。
from opentelemetry.trace import SpanContext, SpanKind, TraceFlags
from opentelemetry.sdk.trace import SpanProcessor
class SpanFilteringProcessor(SpanProcessor):
# prevents exporting spans from internal activities
def on_start(self, span):
if span._kind is SpanKind.INTERNAL:
span._context = SpanContext(
span.context.trace_id,
span.context.span_id,
span.context.is_remote,
TraceFlags.DEFAULT,
span.context.trace_state,
)
トレース ID またはスパン ID を取得する
トレース ID またはスパン ID の取得をお勧めする場合があります。 Application Insights 以外の宛先にログを送信する場合は、トレース ID またはスパン ID を追加することを検討してください。 これにより、問題のデバッグと診断時の相関関係が向上します。
Note
System.Diagnostics
名前空間の Activity
および ActivitySource
クラスは、それぞれ Span
と Tracer
の OpenTelemetry での概念を表しています。 これは、OpenTelemetry トレース API の一部が .NET ランタイムに直接組み込まれているためです。 詳細については、「Introduction to OpenTelemetry .NET Tracing API 」 (OpenTelemetry .NET Tracing API の概要) を参照してください。
Activity activity = Activity.Current;
string traceId = activity?.TraceId.ToHexString();
string spanId = activity?.SpanId.ToHexString();
Note
System.Diagnostics
名前空間の Activity
および ActivitySource
クラスは、それぞれ Span
と Tracer
の OpenTelemetry での概念を表しています。 これは、OpenTelemetry トレース API の一部が .NET ランタイムに直接組み込まれているためです。 詳細については、「Introduction to OpenTelemetry .NET Tracing API 」 (OpenTelemetry .NET Tracing API の概要) を参照してください。
Activity activity = Activity.Current;
string traceId = activity?.TraceId.ToHexString();
string spanId = activity?.SpanId.ToHexString();
opentelemetry-api
を使用して、トレース ID またはスパン ID を取得することができます。
opentelemetry-api-1.0.0.jar
(以降) をアプリケーションに追加します。
<dependency>
<groupId>io.opentelemetry.instrumentation</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 を取得します。
const { trace } = require("@opentelemetry/api");
let spanId = trace.getActiveSpan().spanContext().spanId;
let traceId = trace.getActiveSpan().spanContext().traceId;
コードで要求のトレース ID とスパン ID を取得します。
from opentelemetry import trace
trace_id = trace.get_current_span().get_span_context().trace_id
span_id = trace.get_current_span().get_span_context().span_id
サポート
OpenTelemetry のフィードバック
フィードバックを提供するには:
次のステップ