次の方法で共有


.NET、Java、Node.js、Python アプリケーション用の Azure Monitor OpenTelemetry を追加および変更する

このガイドでは、 Azure Monitor Application Insights 内で OpenTelemetry (OTel) インストルメンテーションを統合およびカスタマイズする方法について説明します。

OpenTelemetry の概念の詳細については、OpenTelemetry の概要または OpenTelemetry に関する FAQ に関する記事を参照してください。

注意

Azure Function Apps については、「 Azure Functions で OpenTelemetry を使用する」を参照してください。

自動データ収集

ディストリビューションは、OpenTelemetry のインストルメンテーション ライブラリをバンドルすることでデータを自動的に収集します。

インストルメンテーション ライブラリを含む

要求数

依存関係

ログ

  • ILogger

Azure Monitor に送信されるログの数を減らすか増やすには、適切なログ レベルを設定するか、フィルターを適用するようにログ記録を構成します。 たとえば、 Warning ログと Error ログのみを OpenTelemetry/Azure Monitor に送信するように選択できます。 OpenTelemetry では、ログ ルーティングやフィルター処理は制御されません。 ILogger 構成によってこれらの決定が行われます。 ILoggerの構成の詳細については、「ログ記録の構成」を参照してください。

ILogger の詳細については、「C# および .NET でのログ記録」と「コード例」を参照してください。

脚注

  • ¹: "ハンドルされない/キャッチされない" 例外の自動レポートをサポートします
  • ²: OpenTelemetry メトリックをサポートします

注意

Azure Monitor OpenTelemetry Distros には、 Application Insights 標準メトリックを自動的に出力するためのカスタム マッピングとロジックが含まれています。

ヒント

インストルメンテーション ライブラリから自動的に収集されたか、またはカスタム コーディングから手動で収集されたかに関係なく、すべての OpenTelemetry メトリックは、現在、課金目的で Application Insights の "カスタム メトリック" と見なされます。 詳細情報。

コミュニティ インストルメンテーション ライブラリを追加する

OpenTelemetry コミュニティからインストルメンテーション ライブラリを含めると、より多くのデータを自動的に収集できます。

注意事項

コミュニティ インストルメンテーション ライブラリの品質は、サポートおよび保証していません。 ディストリビューションについてのご提案は、フィードバック コミュニティで投稿するか賛成に投票してください。 一部は実験的な OpenTelemetry 仕様に基づいており、今後、破壊的変更が生じる可能性があることにご注意ください。

コミュニティ ライブラリを追加するには、ライブラリの NuGet パッケージを追加した後、ConfigureOpenTelemetryMeterProvider または ConfigureOpenTelemetryTracerProvider メソッドを使用します。

次の例では、追加のメトリックを収集するためにランタイム インストルメンテーションを追加する方法を示します。

dotnet add package OpenTelemetry.Instrumentation.Runtime 
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);

// Configure the OpenTelemetry meter provider to add runtime instrumentation.
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddRuntimeInstrumentation());

// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();

// Build the ASP.NET Core web application.
var app = builder.Build();

// Start the ASP.NET Core web application.
app.Run();

カスタム テレメトリを収集する

このセクションでは、アプリケーションからカスタム テレメトリを収集する方法について説明します。

言語とシグナルの種類によって、次のようにさまざまなカスタム テレメトリの収集方法があります。

  • OpenTelemetry API(オープンテレメトリーAPI)
  • 言語固有のログとメトリックのライブラリ
  • Application Insights クラシック API

次の表は、現在サポートされているカスタム テレメトリの種類をまとめたものです。

言語 [カスタム イベント] カスタム メトリック 依存関係 例外 ページ ビュー リクエスト トレース
ASP.NET Core
   OpenTelemetry API(オープンテレメトリーAPI) はい はい はい はい
   ILogger API はい
   AI クラシック API
ジャワ
   OpenTelemetry API(オープンテレメトリーAPI) はい はい はい はい
   Logback、Log4j、JUL はい はい
   Micrometer メトリック はい
   AI クラシック API はい はい はい はい はい はい はい
Node.js
   OpenTelemetry API(オープンテレメトリーAPI) はい はい はい はい
パイソン
   OpenTelemetry API(オープンテレメトリーAPI) はい はい はい はい
   Python ログ モジュール はい
   イベント拡張機能 はい はい

注意

Application Insights Java 3.x と Application Insights Node.js 3.x は、Application Insights クラシック API からテレメトリを収集します。 この動作により、OpenTelemetry API にすべてのカスタム テレメトリの種類が含まれるまで、アップグレードが簡略化され、カスタム テレメトリが一時的にサポートされます。

カスタム メトリックを追加する

このコンテキストでは、カスタム メトリック用語とは、OpenTelemetry インストルメンテーション ライブラリが自動的に収集するメトリック以外の追加のメトリックを収集するために、コードを手動でインストルメント化することを指します。

OpenTelemetry API には、さまざまなメトリック シナリオに対応する 6 つのメトリック "インストルメント" が用意されており、メトリックス エクスプローラーでメトリックを視覚化する場合は、適切な "集計の種類" を選択する必要があります。 この要件は、OpenTelemetry Metric API を使用してメトリックを送信する場合と、インストルメンテーション ライブラリを使用する場合に当てはまります。

次の表は、OpenTelemetry メトリック インストルメントごとに推奨される 集計の種類 を示しています。

OpenTelemetry インストルメント Azure Monitor の集計の種類
カウンタ SUM
非同期カウンター SUM
ヒストグラム Min、Max、Average、Sum、Count
非同期ゲージ 平均
アップダウンカウンター SUM
非同期 UpDownCounter SUM

注意事項

他の集計の種類は、ほとんどの場合意味がありません。

OpenTelemetry の仕様」では、インストルメントについて説明し、それぞれを使用する場合の例を示します。

ヒント

ヒストグラムは最も汎用性が高く、Application Insights GetMetric Classic API と最も近いものです。 Azure Monitor では現在、ヒストグラム インストルメントがサポートされている 5 種類の集計にフラット化されており、パーセンタイルのサポートが進行中です。 汎用性は低くなりますが、他の OpenTelemetry 機器はアプリケーションのパフォーマンスに与える影響が小さくなります。

ヒストグラム例

アプリケーションのスタートアップでは、名前で Meter をサブスクライブする必要があります。

// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);

// Configure the OpenTelemetry meter provider to add a meter named "OTel.AzureMonitor.Demo".
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));

// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();

// Build the ASP.NET Core web application.
var app = builder.Build();

// Start the ASP.NET Core web application.
app.Run();

Meter は、同じ名前を使用して初期化する必要があります。

// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");

// Create a new histogram metric named "FruitSalePrice".
Histogram<long> myFruitSalePrice = meter.CreateHistogram<long>("FruitSalePrice");

// Create a new Random object.
var rand = new Random();

// Record a few random sale prices for apples and lemons, with different colors.
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "green"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));

カウンターの例

アプリケーションのスタートアップでは、名前で Meter をサブスクライブする必要があります。

// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);

// Configure the OpenTelemetry meter provider to add a meter named "OTel.AzureMonitor.Demo".
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));

// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();

// Build the ASP.NET Core web application.
var app = builder.Build();

// Start the ASP.NET Core web application.
app.Run();

Meter は、同じ名前を使用して初期化する必要があります。

// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");

// Create a new counter metric named "MyFruitCounter".
Counter<long> myFruitCounter = meter.CreateCounter<long>("MyFruitCounter");

// Record the number of fruits sold, grouped by name and color.
myFruitCounter.Add(1, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(2, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(1, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(2, new("name", "apple"), new("color", "green"));
myFruitCounter.Add(5, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(4, new("name", "lemon"), new("color", "yellow"));

ゲージの例

アプリケーションのスタートアップでは、名前で Meter をサブスクライブする必要があります。

// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);

// Configure the OpenTelemetry meter provider to add a meter named "OTel.AzureMonitor.Demo".
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));

// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();

// Build the ASP.NET Core web application.
var app = builder.Build();

// Start the ASP.NET Core web application.
app.Run();

Meter は、同じ名前を使用して初期化する必要があります。

// Get the current process.
var process = Process.GetCurrentProcess();

// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");

// Create a new observable gauge metric named "Thread.State".
// This metric will track the state of each thread in the current process.
ObservableGauge<int> myObservableGauge = meter.CreateObservableGauge("Thread.State", () => GetThreadState(process));

private static IEnumerable<Measurement<int>> GetThreadState(Process process)
{
    // Iterate over all threads in the current process.
    foreach (ProcessThread thread in process.Threads)
    {
        // Create a measurement for each thread, including the thread state, process ID, and thread ID.
        yield return new((int)thread.ThreadState, new("ProcessId", process.Id), new("ThreadId", thread.Id));
    }
}

カスタム例外の追加

インストルメンテーション ライブラリを選ぶと、Application Insights の例外が自動的に報告されます。 ただし、インストルメンテーション ライブラリで報告される以外の例外を手動で報告することもできます。 たとえば、コードによってキャッチされた例外は、通常は報告されません。 エラー セクションやエンドツーエンドのトランザクション ビューなど、関連するエクスペリエンスで注目を集めるために、それらを報告することができます。

  • アクティビティを使用して例外をログに記録するには:

    // Start a new activity named "ExceptionExample".
    using (var activity = activitySource.StartActivity("ExceptionExample"))
    {
        // Try to execute some code.
        try
        {
            throw new Exception("Test exception");
        }
        // If an exception is thrown, catch it and set the activity status to "Error".
        catch (Exception ex)
        {
            activity?.SetStatus(ActivityStatusCode.Error);
            activity?.RecordException(ex);
        }
    }
    
  • ILogger を使用して例外をログに記録するには:

    // Create a logger using the logger factory. The logger category name is used to filter and route log messages.
    var logger = loggerFactory.CreateLogger(logCategoryName);
    
    // Try to execute some code.
    try
    {
        throw new Exception("Test Exception");
    }
    catch (Exception ex)
    {
        // Log an error message with the exception. The log level is set to "Error" and the event ID is set to 0.
        // The log message includes a template and a parameter. The template will be replaced with the value of the parameter when the log message is written.
        logger.Log(
            logLevel: LogLevel.Error,
            eventId: 0,
            exception: ex,
            message: "Hello {name}.",
            args: new object[] { "World" });
    }
    

カスタム スパンの追加

2 つのシナリオでカスタム スパンを追加することもできます。 最初に、インストルメンテーション ライブラリによってまだ収集されていない依存関係要求がある場合です。 2 つ目は、アプリケーション プロセスをエンドツーエンドのトランザクション ビューのスパンとしてモデル化する場合です。

注意

Activity 名前空間の ActivitySource および System.Diagnostics クラスは、それぞれ SpanTracer の OpenTelemetry での概念を表しています。 ActivitySource を使用する代わりに、コンストラクターを使用して TracerProvider を直接作成します。 各 ActivitySource クラスは、TracerProvider を使用して AddSource() に明示的に接続する必要があります。 これは、OpenTelemetry トレース API の一部が .NET ランタイムに直接組み込まれているためです。 詳細については、「Introduction to OpenTelemetry .NET Tracing API」 (OpenTelemetry .NET Tracing API の概要) を参照してください。

// Define an activity source named "ActivitySourceName". This activity source will be used to create activities for all requests to the application.
internal static readonly ActivitySource activitySource = new("ActivitySourceName");

// Create an ASP.NET Core application builder.
var builder = WebApplication.CreateBuilder(args);

// Configure the OpenTelemetry tracer provider to add a source named "ActivitySourceName". This will ensure that all activities created by the activity source are traced.
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddSource("ActivitySourceName"));

// Add the Azure Monitor telemetry service to the application. This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();

// Build the ASP.NET Core application.
var app = builder.Build();

// Map a GET request to the root path ("/") to the specified action.
app.MapGet("/", () =>
{
    // Start a new activity named "CustomActivity". This activity will be traced and the trace data will be sent to Azure Monitor.
    using (var activity = activitySource.StartActivity("CustomActivity"))
    {
        // your code here
    }

    // Return a response message.
    return $"Hello World!";
});

// Start the ASP.NET Core application.
app.Run();

StartActivity の既定値は ActivityKind.Internalですが、他の ActivityKindを指定することもできます。 ActivityKind.ClientActivityKind.ProducerActivityKind.Internal は、Application Insights の dependencies にマップされます。 ActivityKind.ServerActivityKind.Consumer は Application Insights の requests にマップされます。

カスタム イベントを送信する

Application Insights では、customEvents テーブルにカスタム イベントが格納されます。 それらを 分析、フィルター処理、視覚化 する 1 つの方法は、 Application Insights の使用エクスペリエンスを使用することです。

クライアント側の相互作用イベントの収集を自動化する場合は、 JavaScript SDK でプラグインを使用できます。

カスタム イベントはパブリック プレビュー段階であり、 Azure.Monitor.OpenTelemetry.AspNetCore 1.3.0-beta.3 を使用します。

重要

ベータ版、プレビュー版、または一般提供としてまだリリースされていない Azure の機能に適用される法律条項については、「Microsoft Azure プレビューの追加使用条件」を参照してください。

CustomEventを使用してILoggerを送信するには、メッセージ テンプレートで"microsoft.custom_event.name"属性を設定します。

// Create a logger factory and configure OpenTelemetry with Azure Monitor
var loggerFactory = LoggerFactory.Create(builder =>
{
    builder
        .AddOpenTelemetry(options =>
        {
            options.AddAzureMonitorLogExporter();
        });
});

// Create a logger for the specified category
var logger = loggerFactory.CreateLogger(logCategoryName);

// Log a custom event with a custom name and additional attribute
// The 'microsoft.custom_event.name' value will be used as the name of the customEvent
logger.LogInformation("{microsoft.custom_event.name} {additional_attrs}", "test-event-name", "val1");

テレメトリの変更

このセクションでは、テレメトリを変更する方法について説明します。

スパン属性を追加する

これらの属性には、テレメトリへのカスタム プロパティの追加が含まれる可能性があります。 また、属性を使用して、Application Insights スキーマに [クライアント IP] などのオプション フィールドを設定することもできます。

スパンにカスタム プロパティを追加する

スパンに追加した属性は、カスタム プロパティとしてエクスポートされます。 これらは、要求、依存関係、トレース、または例外テーブルの customDimensions フィールドに設定されます。

スパン属性を追加するには、次の 2 つの方法のいずれかを使用します。

ヒント

インストルメンテーション ライブラリで提供されるオプションを使用できる利点は、コンテキスト全体を使用できることです。 その結果、ユーザーは、追加する属性を選択したり、フィルター処理したりできます。 たとえば、HttpClient インストルメンテーション ライブラリの enrich オプションを使用すると、ユーザーは HttpRequestMessageHttpResponseMessage 自体にアクセスできます。 そこからは何でも選択して、属性として保存できます。

  1. 多くのインストルメンテーション ライブラリには、強化オプションが用意されています。 ガイダンスについては、個々のインストルメンテーション ライブラリの Readme ファイルを参照してください。

  2. カスタム プロセッサの使用:

    ヒント

    ここに示すプロセッサを、Azure Monitor を追加する前に追加します。

    // Create an ASP.NET Core application builder.
    var builder = WebApplication.CreateBuilder(args);
    
    // Configure the OpenTelemetry tracer provider to add a new processor named ActivityEnrichingProcessor.
    builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddProcessor(new ActivityEnrichingProcessor()));
    
    // Add the Azure Monitor telemetry service to the application. This service will collect and send telemetry data to Azure Monitor.
    builder.Services.AddOpenTelemetry().UseAzureMonitor();
    
    // Build the ASP.NET Core application.
    var app = builder.Build();
    
    // Start the ASP.NET Core application.
    app.Run();
    

    次のコードを使用して、プロジェクトに ActivityEnrichingProcessor.cs を追加します。

    public class ActivityEnrichingProcessor : BaseProcessor<Activity>
    {
        public override void OnEnd(Activity activity)
        {
            // The updated activity will be available to all processors which are called after this processor.
            activity.DisplayName = "Updated-" + activity.DisplayName;
            activity.SetTag("CustomDimension1", "Value1");
            activity.SetTag("CustomDimension2", "Value2");
        }
    }
    

ユーザー IP を設定する

スパンに属性を設定することで、要求の client_IP フィールドにデータを入力できます。 Application Insights では、この IP アドレスを使用してユーザーの位置属性を生成した後、既定でそれを破棄します

カスタム プロパティの例を使用しますが、次の ActivityEnrichingProcessor.cs のコード行を置き換えます。

// Add the client IP address to the activity as a tag.
// only applicable in case of activity.Kind == Server
activity.SetTag("client.address", "<IP Address>");

ユーザー ID または認証されたユーザー ID を設定する

次のガイダンスを参考にして、要求の user_Id または user_AuthenticatedId フィールドを設定できます。 ユーザー ID は匿名のユーザー識別子です。 認証されたユーザー ID は既知のユーザー識別子です。

重要

認証されたユーザー ID を設定する前に、該当するプライバシーに関する法律を調べてください。

カスタム プロパティの例を使用します。

// Add the user ID to the activity as a tag, but only if the activity is not null.
activity?.SetTag("enduser.id", "<User Id>");

ログ属性の追加

OpenTelemetry は .NET の ILogger を使用します。 カスタム ディメンションをログに添付するには、 [メッセージ テンプレート] を使用します。

トレース ID またはスパン ID を取得する

次の手順を使って、現在アクティブなスパンの Trace IDSpan ID を取得できます。

注意

Activity 名前空間の ActivitySource および System.Diagnostics クラスは、それぞれ SpanTracer の OpenTelemetry での概念を表しています。 これは、OpenTelemetry トレース API の一部が .NET ランタイムに直接組み込まれているためです。 詳細については、「Introduction to OpenTelemetry .NET Tracing API」 (OpenTelemetry .NET Tracing API の概要) を参照してください。

// Get the current activity.
Activity activity = Activity.Current;
// Get the trace ID of the activity.
string traceId = activity?.TraceId.ToHexString();
// Get the span ID of the activity.
string spanId = activity?.SpanId.ToHexString();

次のステップ