.NET を使用した Application Insights のログ

この記事では、Microsoft.Extensions.Logging.ApplicationInsights プロバイダー パッケージを使用して .NET アプリの Application Insights でログをキャプチャする方法について説明します。 このプロバイダーを使用する場合は、Application Insights ツールを使ってクエリを実行し、ログを分析できます。

Note

以下のドキュメントは、Application Insights クラシック API に関するものです。 Application Insights の長期的な計画は、OpenTelemetry を使用してデータを収集することです。 詳しくは、「.NET、Node.js、Python、Java アプリケーション用の Azure Monitor OpenTelemetry を有効にする」をご覧ください。

Note

Application Insights テレメトリ全部とログ記録を実装する場合、「ASP.NET Web サイトの Application Insights を構成する」か「ASP.NET Core アプリケーションの Application Insights」を参照してください。

ヒント

バックグラウンド サービス用の Application Insights を有効にするために使用される Microsoft.ApplicationInsights.WorkerService NuGet パッケージは対象範囲外です。 詳細については、ワーカー サービス アプリケーション向け Application Insights に関するページを参照してください。

ASP.NET Core アプリケーション

ASP.NET Core アプリケーションに Application Insights ログを追加するには:

  1. Microsoft.Extensions.Logging.ApplicationInsightsをインストールします。

  2. ApplicationInsightsLoggerProvider を追加します。

using Microsoft.Extensions.Logging.ApplicationInsights;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Logging.AddApplicationInsights(
        configureTelemetryConfiguration: (config) => 
            config.ConnectionString = builder.Configuration.GetConnectionString("APPLICATIONINSIGHTS_CONNECTION_STRING"),
            configureApplicationInsightsLoggerOptions: (options) => { }
    );

builder.Logging.AddFilter<ApplicationInsightsLoggerProvider>("your-category", LogLevel.Trace);

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

NuGet パッケージがインストールされ、プロバイダーが依存関係の挿入によって登録されているので、アプリをログに記録する準備ができました。 コンストラクターの挿入では、ILogger またはジェネリック型の代替である ILogger<TCategoryName> のいずれかが必要になります。 これらの実装が解決されると、ApplicationInsightsLoggerProvider によってこれらが提供されるようになります。 ログされたメッセージや例外は、Application Insights に送信されます。

たとえば、次のコントローラーの例を考えてみましょう。

public class ValuesController : ControllerBase
{
    private readonly ILogger _logger;

    public ValuesController(ILogger<ValuesController> logger)
    {
        _logger = logger;
    }

    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        _logger.LogWarning("An example of a Warning trace..");
        _logger.LogError("An example of an Error level message");

        return new string[] { "value1", "value2" };
    }
}

詳細については、ASP.NET Coreでのログに関するページ、および「ILogger ログからはどのような種類の Application Insights テレメトリが生成されますか? Application Insights ではどこで ILogger ログを見ることができますか?」を参照してください。

コンソール アプリケーション

Application Insights ログ記録をコンソール アプリケーションに追加するには、最初に 以下のNuGet パッケージをインストールします:

次の例では、Microsoft.Extensions.Logging.ApplicationInsights パッケージを使用し、コンソール アプリケーションの既定の動作を示しています。 Microsoft.Extensions.Logging.ApplicationInsights パッケージは、コンソール アプリケーションで、または完全な機能セット (メトリック、分散トレース、サンプリング、テレメトリ初期化子など) を使用せずに Application Insights の最小限の実装が必要なときに常に、使用する必要があります。

using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

using var channel = new InMemoryChannel();

try
{
    IServiceCollection services = new ServiceCollection();
    services.Configure<TelemetryConfiguration>(config => config.TelemetryChannel = channel);
    services.AddLogging(builder =>
    {
        // Only Application Insights is registered as a logger provider
        builder.AddApplicationInsights(
            configureTelemetryConfiguration: (config) => config.ConnectionString = "<YourConnectionString>",
            configureApplicationInsightsLoggerOptions: (options) => { }
        );
    });

    IServiceProvider serviceProvider = services.BuildServiceProvider();
    ILogger<Program> logger = serviceProvider.GetRequiredService<ILogger<Program>>();

    logger.LogInformation("Logger is working...");
}
finally
{
    // Explicitly call Flush() followed by Delay, as required in console apps.
    // This ensures that even if the application terminates, telemetry is sent to the back end.
    channel.Flush();

    await Task.Delay(TimeSpan.FromMilliseconds(1000));
}

詳細については、「ILogger ログからはどのような種類の Application Insights テレメトリが生成されますか? Application Insights ではどこで ILogger ログを見ることができますか?」を参照してください。

ログのスコープ

ApplicationInsightsLoggingProvider では、ログ スコープがサポートされます。 スコープは既定で有効になっています。

スコープの型が IReadOnlyCollection<KeyValuePair<string,object>> の場合、コレクション内のキーと値の各ペアが、カスタム プロパティとして、Application Insights テレメトリに追加されます。 次の例では、ログは TraceTelemetry としてキャプチャされ、プロパティに ("MyKey", "MyValue") が含まれています。

using (_logger.BeginScope(new Dictionary<string, object> { ["MyKey"] = "MyValue" }))
{
    _logger.LogError("An example of an Error level message");
}

他の型がスコープとして使用される場合は、Application Insights テレメトリのプロパティ Scope に格納されます。 次の例では、TraceTelemetry に、スコープを含む Scope という名前のプロパティが設定されます。

    using (_logger.BeginScope("hello scope"))
    {
        _logger.LogError("An example of an Error level message");
    }

よく寄せられる質問

ILogger ログからはどのような種類の Application Insights テレメトリが生成されますか? Application Insights ではどこで ILogger ログを見ることができますか?

ApplicationInsightsLoggerProvider は、ILogger ログをキャプチャし、それから TraceTelemetry を作成します。 Exception オブジェクトが ILoggerLog メソッドに渡されると、TraceTelemetry の代わりに ExceptionTelemetry が作成されます。

ILogger テレメトリを表示する

Azure Portal で確認:

  1. Azure Portal に移動し、Application Insights リソースにアクセスします。
  2. Application Insights 内の [ログ] セクションをクリックします。
  3. Kusto 照会言語 (KQL) を使用して、ILogger メッセージ (通常は traces テーブルに保存されています) のクエリを実行します。
    • クエリの例: traces | where message contains "YourSearchTerm"
  4. クエリを絞り込み、重要度、時間範囲、または特定のメッセージ コンテンツによって ILogger データをフィルター処理します。

Visual Studio (ローカル デバッガー):

  1. Visual Studio 内で、アプリケーションをデバッグ モードで実行します。
  2. アプリケーションの実行中に [診断ツール] ウィンドウを開きます。
  3. [イベント] タブには、ILogger ログが他のテレメトリ データと共に表示されます。
  4. [診断ツール] ウィンドウで、検索とフィルターの機能を使用して特定の ILogger メッセージを見つけます。

常に TraceTelemetry を送信する場合は、このスニペットを使用します。

builder.AddApplicationInsights(
    options => options.TrackExceptionsAsExceptionTelemetry = false);

一部の ILogger ログのプロパティが他と同じではないのはなぜですか?

Application Insights では、他のすべてのテレメトリに使用されるのと同じ TelemetryConfiguration情報を使用して、ILogger ログのキャプチャと送信が行われます。 ただし、例外があります。 既定では、Program.cs または Startup.cs からログを記録するとき、TelemetryConfiguration は完全には設定されません。 これらの場所からのログには既定の構成がないため、すべての TelemetryInitializer インスタンスおよび TelemetryProcessor インスタンスは実行されません。

スタンドアロン パッケージ Microsoft.Extensions.Logging.ApplicationInsights を使用しており、カスタム テレメトリをさらに手動でログに記録しようと考えています。 どうすればよいですか?

スタンドアロン パッケージを使用するとき、TelemetryClient は依存関係挿入 (DI) コンテナーに挿入されません。 次のコードに示すように、TelemetryClient の新しいインスタンスを作成し、ロガー プロバイダーが使用しているのと同じ構成を使用する必要があります。 この要件により、カスタム テレメトリと、ILogger のテレメトリのすべてに、同じ構成が使われることが保証されます。

public class MyController : ApiController
{
   // This TelemetryClient instance can be used to track additional telemetry through the TrackXXX() API.
   private readonly TelemetryClient _telemetryClient;
   private readonly ILogger _logger;

   public MyController(IOptions<TelemetryConfiguration> options, ILogger<MyController> logger)
   {
        _telemetryClient = new TelemetryClient(options.Value);
        _logger = logger;
   }  
}

Note

Microsoft.ApplicationInsights.AspNetCore パッケージを使用して Application Insights を有効にする場合は、このコードを変更して、コンストラクター内で直接 TelemetryClient を取得します。

SDK をインストールせず、Azure Web Apps 拡張機能を使用して ASP.NET Core アプリケーションの Application Insights を有効にしています。 新しいプロバイダーを使用するにはどうすればよいですか?

Azure Web Apps の Application Insights 拡張機能は、新しいプロバイダーを使用します。 フィルタリング規則は、アプリケーションの appsettings.json ファイルで変更することができます。

次のステップ