ワーカー サービス アプリケーション (非 HTTP アプリケーション) 向け Application Insights

ワーカー サービス向け Application Insights SDK は、メッセージング、バックグラウンド タスク、コンソール アプリケーションなどの非 HTTP ワークロードに最適な新しい SDK です。 これらの種類のアプリケーションには、従来の ASP.NET/ASP.NET Core Web アプリケーションのような受信 HTTP 要求の概念がありません。 そのため、ASP.NET または ASP.NET Core アプリケーションの Application Insights パッケージの使用はサポートされていません。

Note

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

新しい SDK では、単独でテレメトリは収集されません。 代わりに、DependencyCollectorPerfCounterCollectorApplicationInsightsLoggingProvider など、他の既知の Application Insights 自動コレクターを利用できます。 この SDK では IServiceCollection の拡張メソッドを公開し、テレメトリの収集を有効にして構成します。

サポートされるシナリオ

ワーカー サービス向け Application Insights SDK は、実行されている場所や方法に関係なく、非 HTTP アプリケーションに最適です。 アプリケーションが実行されていて、Azure へのネットワーク接続がある場合は、テレメトリを収集することができます。 Application Insights の監視は、.NET Core がサポートされているすべての場所でサポートされます。 このパッケージは、新しく導入された .NET Core ワーカー サービスASP.NET Core のバックグラウンド タスク、コンソール アプリ (.NET Core、.NET Framework など) で使用できます。

前提条件

Application Insights の有効な接続文字列が必要です。 Application Insights にテレメトリを送信するには、この文字列が必要です。 接続文字列を取得するために新しい Application Insights リソースを作成する必要がある場合は、「接続文字列」を参照してください。

Note

インストルメンテーション キーのインジェストのサポートは、2025 年 3 月 31 日に終了します。 インストルメンテーション キーのインジェストは引き続き機能しますが、この機能の更新プログラムやサポートは提供されなくなります。 接続文字列に移行することで、新機能をご利用いただけます。

ワーカー サービス向け Application Insights SDK を使用する

  1. アプリケーションに Microsoft.ApplicationInsights.WorkerService パッケージをインストールします。 次のスニペットは、プロジェクトの .csproj ファイルに追加する必要がある変更を示しています。

        <ItemGroup>
            <PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.22.0" />
        </ItemGroup>
    
  2. 接続文字列を、APPLICATIONINSIGHTS_CONNECTION_STRING 環境変数または構成 (appsettings.json) で設定します。

    Screenshot displaying Application Insights overview and connection string.

  3. serviceProvider.GetRequiredService<TelemetryClient>(); を呼び出すか、コンストラクターの挿入を使用して、依存関係の挿入 (DI) コンテナーから ILogger インスタンスまたは TelemetryClient インスタンスを取得します。 この手順により、TelemetryConfiguration および自動収集モジュールの設定がトリガーされます。

各種類のアプリケーションの具体的な手順については、次のセクションで説明します。

.NET Core Worker サービス アプリケーション

完全な例は、NuGet Web サイトで共有されています。

  1. .NET SDK をダウンロードしてインストールします

  2. Visual Studio の新しいプロジェクト テンプレートまたはコマンド ライン dotnet new worker を使用して、新しいワーカー サービス プロジェクトを作成します。

  3. アプリケーションに Microsoft.ApplicationInsights.WorkerService パッケージを追加します。

  4. この例のように、Program.cs クラスで CreateHostBuilder() メソッドに services.AddApplicationInsightsTelemetryWorkerService(); を追加します。

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                    services.AddApplicationInsightsTelemetryWorkerService();
                });
    
  5. 次の例に従って、Worker.cs を変更します。

        using Microsoft.ApplicationInsights;
        using Microsoft.ApplicationInsights.DataContracts;
    
        public class Worker : BackgroundService
        {
            private readonly ILogger<Worker> _logger;
            private TelemetryClient _telemetryClient;
            private static HttpClient _httpClient = new HttpClient();
    
            public Worker(ILogger<Worker> logger, TelemetryClient tc)
            {
                _logger = logger;
                _telemetryClient = tc;
            }
    
            protected override async Task ExecuteAsync(CancellationToken stoppingToken)
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
    
                    using (_telemetryClient.StartOperation<RequestTelemetry>("operation"))
                    {
                        _logger.LogWarning("A sample warning message. By default, logs with severity Warning or higher is captured by Application Insights");
                        _logger.LogInformation("Calling bing.com");
                        var res = await _httpClient.GetAsync("https://bing.com");
                        _logger.LogInformation("Calling bing completed with status:" + res.StatusCode);
                        _telemetryClient.TrackEvent("Bing call event completed");
                    }
    
                    await Task.Delay(1000, stoppingToken);
                }
            }
        }
    
  6. 接続文字列を設定します。

    Screenshot that shows Application Insights overview and connection string.

    Note

    構成で接続文字列を指定することをお勧めします。 appsettings.json で接続文字列を指定する方法は、次のコード サンプルのようになります。 発行の間に、appsettings.json がアプリケーションのルート フォルダーにコピーされるようにします。

        {
            "ApplicationInsights":
            {
                "ConnectionString" : "InstrumentationKey=00000000-0000-0000-0000-000000000000;"
            },
            "Logging":
            {
                "LogLevel":
                {
                    "Default": "Warning"
                }
            }
        }
    

または、APPLICATIONINSIGHTS_CONNECTION_STRING 環境変数に接続文字列を指定します。

通常、APPLICATIONINSIGHTS_CONNECTION_STRING は Web ジョブとして Web Apps にデプロイされるアプリケーションの接続文字列を指定します。

注意

コードで指定された接続文字列は、他のオプションより優先される環境変数 APPLICATIONINSIGHTS_CONNECTION_STRING より優先されます。

ホステッド サービスを使用した ASP.NET Core のバックグラウンド タスク

ASP.NET Core アプリケーションでのバックグラウンド タスクの作成方法については、こちらのドキュメントで説明されています。

完全な例は、こちらの GitHub ページで共有されています。

  1. アプリケーションに Microsoft.ApplicationInsights.WorkerService パッケージをインストールします。

  2. この例のように、ConfigureServices() メソッドに services.AddApplicationInsightsTelemetryWorkerService(); を追加します。

        public static async Task Main(string[] args)
        {
            var host = new HostBuilder()
                .ConfigureAppConfiguration((hostContext, config) =>
                {
                    config.AddJsonFile("appsettings.json", optional: true);
                })
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddLogging();
                    services.AddHostedService<TimedHostedService>();
    
                    // connection string is read automatically from appsettings.json
                    services.AddApplicationInsightsTelemetryWorkerService();
                })
                .UseConsoleLifetime()
                .Build();
    
            using (host)
            {
                // Start the host
                await host.StartAsync();
    
                // Wait for the host to shutdown
                await host.WaitForShutdownAsync();
            }
        }
    

    次のコードは、バックグラウンド タスク ロジックが存在する TimedHostedService 用のものです。

        using Microsoft.ApplicationInsights;
        using Microsoft.ApplicationInsights.DataContracts;
    
        public class TimedHostedService : IHostedService, IDisposable
        {
            private readonly ILogger _logger;
            private Timer _timer;
            private TelemetryClient _telemetryClient;
            private static HttpClient httpClient = new HttpClient();
    
            public TimedHostedService(ILogger<TimedHostedService> logger, TelemetryClient tc)
            {
                _logger = logger;
                this._telemetryClient = tc;
            }
    
            public Task StartAsync(CancellationToken cancellationToken)
            {
                _logger.LogInformation("Timed Background Service is starting.");
    
                _timer = new Timer(DoWork, null, TimeSpan.Zero,
                    TimeSpan.FromSeconds(1));
    
                return Task.CompletedTask;
            }
    
            private void DoWork(object state)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
    
                using (_telemetryClient.StartOperation<RequestTelemetry>("operation"))
                {
                    _logger.LogWarning("A sample warning message. By default, logs with severity Warning or higher is captured by Application Insights");
                    _logger.LogInformation("Calling bing.com");
                    var res = httpClient.GetAsync("https://bing.com").GetAwaiter().GetResult();
                    _logger.LogInformation("Calling bing completed with status:" + res.StatusCode);
                    _telemetryClient.TrackEvent("Bing call event completed");
                }
            }
        }
    
  3. 接続文字列を設定します。 上記の .NET Worker サービスの例と同じ appsettings.json を使用します。

.NET Core/.NET Framework コンソール アプリケーション

この記事の冒頭で説明したように、新しいパッケージを使用して、通常のコンソール アプリケーションからでも Application Insights Telemetry を有効にすることができます。 このパッケージは netstandard2.0 を対象としているため、.NET Core 以上と、.NET Framework 以上のコンソール アプリで使用できます。

完全な例は、こちらの GitHub ページで共有されています。

  1. アプリケーションに Microsoft.ApplicationInsights.WorkerService パッケージをインストールします。

  2. 次の例に示すように Program.cs を変更します。

        using Microsoft.ApplicationInsights;
        using Microsoft.ApplicationInsights.DataContracts;
        using Microsoft.ApplicationInsights.WorkerService;
        using Microsoft.Extensions.DependencyInjection;
        using Microsoft.Extensions.Logging;
        using System;
        using System.Net.Http;
        using System.Threading.Tasks;
    
        namespace WorkerSDKOnConsole
        {
            class Program
            {
                static async Task Main(string[] args)
                {
                    // Create the DI container.
                    IServiceCollection services = new ServiceCollection();
    
                    // Being a regular console app, there is no appsettings.json or configuration providers enabled by default.
                    // Hence instrumentation key/ connection string and any changes to default logging level must be specified here.
                    services.AddLogging(loggingBuilder => loggingBuilder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>("Category", LogLevel.Information));
                    services.AddApplicationInsightsTelemetryWorkerService((ApplicationInsightsServiceOptions options) => options.ConnectionString = "InstrumentationKey=<instrumentation key here>");
    
                    // To pass a connection string
                    // - aiserviceoptions must be created
                    // - set connectionstring on it
                    // - pass it to AddApplicationInsightsTelemetryWorkerService()
    
                    // Build ServiceProvider.
                    IServiceProvider serviceProvider = services.BuildServiceProvider();
    
                    // Obtain logger instance from DI.
                    ILogger<Program> logger = serviceProvider.GetRequiredService<ILogger<Program>>();
    
                    // Obtain TelemetryClient instance from DI, for additional manual tracking or to flush.
                    var telemetryClient = serviceProvider.GetRequiredService<TelemetryClient>();
    
                    var httpClient = new HttpClient();
    
                    while (true) // This app runs indefinitely. Replace with actual application termination logic.
                    {
                        logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
    
                        // Replace with a name which makes sense for this operation.
                        using (telemetryClient.StartOperation<RequestTelemetry>("operation"))
                        {
                            logger.LogWarning("A sample warning message. By default, logs with severity Warning or higher is captured by Application Insights");
                            logger.LogInformation("Calling bing.com");                    
                            var res = await httpClient.GetAsync("https://bing.com");
                            logger.LogInformation("Calling bing completed with status:" + res.StatusCode);
                            telemetryClient.TrackEvent("Bing call event completed");
                        }
    
                        await Task.Delay(1000);
                    }
    
                    // Explicitly call Flush() followed by sleep is required in console apps.
                    // This is to ensure that even if application terminates, telemetry is sent to the back-end.
                    telemetryClient.Flush();
                    Task.Delay(5000).Wait();
                }
            }
        }
    

このコンソール アプリケーションでも、同じ既定の TelemetryConfiguration が使用されます。 これは、前のセクションの例と同じ方法でカスタマイズできます。

アプリケーションを実行する

アプリケーションを実行します。 上記の例のすべてのワーカーでは、bing.com に対して 1 秒ごとに HTTP 呼び出しを行い、また、ILogger を使用していくつかのログを出力します。 これらの行は、操作を作成するために使用される、TelemetryClientStartOperation 呼び出し内にラップされます。 この例では、RequestTelemetry は "operation" という名前です。

Application Insights では、これらの ILogger ログ (既定では警告以上の重大度) と依存関係が収集されます。 これらは、親子関係を持つ RequestTelemetry に関連付けられます。 プロセス/ネットワーク境界を越える関連付けも機能します。 たとえば、別の監視対象コンポーネントに対して呼び出しが行われた場合、この親にも関連付けられます。

RequestTelemetry のこのカスタム操作は、一般的な Web アプリケーションでの受信 Web 要求に相当するものと考えることができます。 操作を使用する必要はありませんが、これは Application Insights の関連付けデータ モデルに最適です。 RequestTelemetry は親操作として機能し、ワーカー イテレーション内で生成されるすべてのテレメトリは、論理的に同じ操作に属しているものとして扱われます。

また、この方法では、生成されるすべてのテレメトリ (自動と手動の両方) の operation_id が確実に同じになります。 サンプリングは operation_id に基づいているため、サンプリング アルゴリズムでは、単一のイテレーションからのすべてのテレメトリが保持または削除されます。

以下のセクションでは、Application Insights によって自動的に収集されるすべてのテレメトリの一覧を示します。

ライブ メトリック

Live Metrics を使用すると、Application Insights の監視が正しく構成されているかどうかをすばやく確認できます。 テレメトリがポータルと分析に表示されるまで数分かかることがありますが、Live Metrics では、実行中のプロセスの CPU 使用率がほぼリアルタイムで示されます。 また、要求、依存関係、トレースなどの他のテレメトリも表示できます。

ILogger ログ

ILogger から警告以上の重大度で出力されたログは、自動的にキャプチャされます。 この動作を変更するには、次のコードで示すように、プロバイダー ApplicationInsights のログ構成を明示的にオーバーライドします。 次の構成を使用すると、Application Insights で Information ログ以上の重大度のすべてのログをキャプチャできます。

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    },
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Information"
      }
    }
  }
}

次の例では、Application Insights プロバイダーによって Information ログがキャプチャされないことに注意してください。 キャプチャされないのは、Warning ログ以上の重大度のログのみをキャプチャするように ApplicationInsights に指示する既定のログ フィルターが、SDK によって追加されるためです。 Application Insights には明示的なオーバーライドが必要です。

{
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  }
}

詳細については、Application Insights によってキャプチャされるログ レベルのカスタマイズに関する ILogger のドキュメントに従ってください。

依存関係

依存関係の収集は既定で有効になっています。 「Application Insights での依存関係の追跡」の記事では、自動収集される依存関係について説明されており、手動で追跡するための手順も含まれます。

EventCounter

EventCounterCollectionModule は既定で有効になっており、.NET アプリから既定のカウンター セットが収集されます。 EventCounter チュートリアルには、収集される既定のカウンター セットがリスト表示されています。 また、リストのカスタマイズ方法についても説明されています。

その他のテレメトリを手動で追跡する

SDK では、上記の説明のとおり、テレメトリが自動的に収集されますが、ほとんどの場合、ユーザーが Application Insights に他のテレメトリを送信する必要があります。 他のテレメトリを追跡する場合は、依存関係の挿入から TelemetryClient のインスタンスを取得し、サポートされている TrackXXX()API メソッドのいずれかを呼び出すことをお勧めします。 もう 1 つの一般的なユース ケースは、操作のカスタム追跡です。 この方法は、上記のワーカーの例に示されています。

Application Insights SDK を構成する

ワーカー サービス SDK で使用される既定の TelemetryConfiguration は、ASP.NET または ASP.NET Core アプリケーションで使用される自動構成に似ています (HttpContext からのテレメトリを強化するために使用されるテレメトリ初期化子を除く)。

ワーカー サービス向け Application Insights SDK をカスタマイズして、既定の構成を変更することができます。 Application Insights ASP.NET Core SDK のユーザーであれば、ASP.NET Core の組み込みの依存関係の挿入を使用する構成の変更に慣れている場合があります。 また、ワーカー サービス SDK は同様の原則に基づいています。 次のセクションで説明されているように、IServiceCollection で適切なメソッドを呼び出して、ConfigureServices() セクションのほとんどすべての構成変更を行います。

Note

この SDK を使用するときは、TelemetryConfiguration.Active の変更による構成の変更がサポートされず、変更は反映されません。

ApplicationInsightsServiceOptions を使用する

次の例のように ApplicationInsightsServiceOptionsAddApplicationInsightsTelemetryWorkerService に渡すことで、いくつかの一般的な設定を変更できます。

using Microsoft.ApplicationInsights.WorkerService;

public void ConfigureServices(IServiceCollection services)
{
    var aiOptions = new ApplicationInsightsServiceOptions();
    // Disables adaptive sampling.
    aiOptions.EnableAdaptiveSampling = false;

    // Disables QuickPulse (Live Metrics stream).
    aiOptions.EnableQuickPulseMetricStream = false;
    services.AddApplicationInsightsTelemetryWorkerService(aiOptions);
}

この SDK の ApplicationInsightsServiceOptions は、ASP.NET Core SDK の Microsoft.ApplicationInsights.AspNetCore.Extensions ではなく、名前空間 Microsoft.ApplicationInsights.WorkerService にあります。

ApplicationInsightsServiceOptions で一般的に使用される設定を次の表に示します。

設定 説明 Default
EnableQuickPulseMetricStream Live Metrics 機能を有効または無効にします。
EnableAdaptiveSampling アダプティブ サンプリングを有効または無効にします。
EnableHeartbeat ハートビート機能を有効または無効にします。この機能は、"HeartBeatState" という名前のカスタム メトリックを、.NET バージョン、Azure 環境 (該当する場合) などのランタイムに関する情報と共に定期的に (既定では 15 分) 送信します。
AddAutoCollectedMetricExtractor AutoCollectedMetrics エクストラクターを有効または無効にします。これは、サンプリングが行われる前に要求/依存関係に関する事前に集計されたメトリックを送信するテレメトリ プロセッサです。
EnableDiagnosticsTelemetryModule DiagnosticsTelemetryModule を有効または無効にします。 この設定を無効にすると、次の設定が無視されます: EnableHeartbeatEnableAzureInstanceMetadataTelemetryModuleEnableAppServicesHeartbeatTelemetryModule

最新の一覧については、ApplicationInsightsServiceOptions の構成可能な設定を参照してください。

サンプリング

ワーカー サービス向け Application Insights SDK では、固定レートのサンプリングアダプティブ サンプリングの両方がサポートされます。 アダプティブ サンプリングは、既定で有効になっています。 サンプリングは、ApplicationInsightsServiceOptionsEnableAdaptiveSampling オプションを使用して無効にすることができます。

その他のサンプリング設定を構成するには、次の例を使用できます。

using Microsoft.ApplicationInsights.AspNetCore.Extensions;
using Microsoft.ApplicationInsights.Extensibility;

var builder = WebApplication.CreateBuilder(args);

builder.Services.Configure<TelemetryConfiguration>(telemetryConfiguration =>
{
   var telemetryProcessorChainBuilder = telemetryConfiguration.DefaultTelemetrySink.TelemetryProcessorChainBuilder;

   // Using adaptive sampling
   telemetryProcessorChainBuilder.UseAdaptiveSampling(maxTelemetryItemsPerSecond: 5);

   // Alternately, the following configures adaptive sampling with 5 items per second, and also excludes DependencyTelemetry from being subject to sampling:
   // telemetryProcessorChainBuilder.UseAdaptiveSampling(maxTelemetryItemsPerSecond:5, excludedTypes: "Dependency");
});

builder.Services.AddApplicationInsightsTelemetry(new ApplicationInsightsServiceOptions
{
   EnableAdaptiveSampling = false,
});

var app = builder.Build();

詳細については、サンプリングのドキュメントを参照してください。

テレメトリ初期化子を追加する

すべてのテレメトリと共に送信されるプロパティを定義する場合は、テレメトリ初期化子を使用します。

新しいテレメトリ初期化子を DependencyInjection コンテナーに追加すると、SDK によって、それらが TelemetryConfiguration に自動的に追加されます。

    using Microsoft.ApplicationInsights.Extensibility;

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<ITelemetryInitializer, MyCustomTelemetryInitializer>();
        services.AddApplicationInsightsTelemetryWorkerService();
    }

テレメトリ初期化子を削除する

テレメトリ初期化子は既定で存在します。 すべてまたは特定のテレメトリ初期化子を削除するには、AddApplicationInsightsTelemetryWorkerService() を呼び出した "後" で、次のサンプル コードを使用します。

   public void ConfigureServices(IServiceCollection services)
   {
        services.AddApplicationInsightsTelemetryWorkerService();
        // Remove a specific built-in telemetry initializer.
        var tiToRemove = services.FirstOrDefault<ServiceDescriptor>
                            (t => t.ImplementationType == typeof(AspNetCoreEnvironmentTelemetryInitializer));
        if (tiToRemove != null)
        {
            services.Remove(tiToRemove);
        }

        // Remove all initializers.
        // This requires importing namespace by using Microsoft.Extensions.DependencyInjection.Extensions;
        services.RemoveAll(typeof(ITelemetryInitializer));
   }

テレメトリ プロセッサを追加する

拡張メソッド AddApplicationInsightsTelemetryProcessorIServiceCollection で使用することで、カスタム テレメトリ プロセッサを TelemetryConfiguration に追加できます。 高度なフィルター処理シナリオでテレメトリ プロセッサを使用して、Application Insights に送信するテレメトリに何を含めて何を除外するかを、より直接的に制御できるようにします。 次の例を使用してください。

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetryWorkerService();
        services.AddApplicationInsightsTelemetryProcessor<MyFirstCustomTelemetryProcessor>();
        // If you have more processors:
        services.AddApplicationInsightsTelemetryProcessor<MySecondCustomTelemetryProcessor>();
    }

既定のテレメトリ モジュールを構成または削除する

Application Insights では、テレメトリ モジュールを使用して、手動の追跡を必要とせずに特定のワークロードに関するテレメトリが自動収集されます。

次の自動収集モジュールが既定で有効になります。 これらのモジュールでは、自動的にテレメトリが収集されます。 それらを無効にするか構成して、既定の動作を変更できます。

  • DependencyTrackingTelemetryModule
  • PerformanceCollectorModule
  • QuickPulseTelemetryModule
  • AppServicesHeartbeatTelemetryModule (現在、このテレメトリ モジュールに関連する問題があります。一時的な回避策については、GitHub Issue 1689 を参照してください。)
  • AzureInstanceMetadataTelemetryModule

既定のテレメトリ モジュールを構成するには、下の画像のように、拡張メソッド ConfigureTelemetryModule<T>IServiceCollection で使用します。

    using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse;
    using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector;

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetryWorkerService();

            // The following configures QuickPulseTelemetryModule.
            // Similarly, any other default modules can be configured.
            services.ConfigureTelemetryModule<QuickPulseTelemetryModule>((module, o) =>
            {
                module.AuthenticationApiKey = "keyhere";
            });

            // The following removes PerformanceCollectorModule to disable perf-counter collection.
            // Similarly, any other default modules can be removed.
            var performanceCounterService = services.FirstOrDefault<ServiceDescriptor>
                                        (t => t.ImplementationType == typeof(PerformanceCollectorModule));
            if (performanceCounterService != null)
            {
                services.Remove(performanceCounterService);
            }
    }

テレメトリ チャネルを構成する

既定のチャネルは ServerTelemetryChannel です。 次の例のようにしてオーバーライドできます。

using Microsoft.ApplicationInsights.Channel;

    public void ConfigureServices(IServiceCollection services)
    {
        // Use the following to replace the default channel with InMemoryChannel.
        // This can also be applied to ServerTelemetryChannel.
        services.AddSingleton(typeof(ITelemetryChannel), new InMemoryChannel() {MaxTelemetryBufferCapacity = 19898 });

        services.AddApplicationInsightsTelemetryWorkerService();
    }

テレメトリを動的に無効にする

テレメトリを条件付きで動的に無効にする必要がある場合は、コードの任意の場所で ASP.NET Core の依存関係挿入コンテナーを使用して TelemetryConfiguration インスタンスを解決し、それに DisableTelemetry フラグを設定することができます。

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetryWorkerService();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, TelemetryConfiguration configuration)
    {
        configuration.DisableTelemetry = true;
        ...
    }

よく寄せられる質問

このセクションでは、一般的な質問への回答を示します。

どのパッケージを使えばよいのですか?

.NET Core アプリのシナリオ パッケージ
HostedServices なし WorkerService
HostedServices を使用する AspNetCore (WorkerService ではない)
HostedServices では、HostedServices のみを監視します WorkerService (まれなシナリオ)

AspNetCore パッケージを使用する .NET Core アプリ内の HostedServices に TelemetryClient を挿入できますか?

はい。 構成は、Web アプリケーションの残りの部分と共有されます。

自動的に収集されないテレメトリを追跡するにはどうすればよいですか?

コンストラクター インジェクションを使用して TelemetryClient のインスタンスを取得し、そのインスタンスで必須の TrackXXX() メソッドを呼び出します。 新しい TelemetryClient インスタンスを作成することはお勧めできません。 TelemetryClient のシングルトン インスタンスが DependencyInjection コンテナーに既に登録されており、それによって TelemetryConfiguration がテレメトリの残りの部分と共有されます。 新しい TelemetryClient インスタンスの作成は、残りのテレメトリとは別の構成が必要な場合にのみ推奨されます。

Visual Studio IDE を使用して、ワーカー サービス プロジェクトに Application Insights をオンボードすることはできますか?

現在、Visual Studio IDE のオンボードは ASP.NET/ASP.NET Core アプリケーションでのみサポートされています。 このドキュメントは、Visual Studio のリリースでワーカー サービス アプリケーションのオンボードがサポートされるようになったときに更新されます。

Azure Monitor Application Insights エージェント (旧名 Status Monitor v2) のようなツールを使用して、Application Insights 監視を有効にできますか?

いいえ。 Azure Monitor Application Insights エージェントでは現在、.NET のみがサポートされています。

Linux でアプリケーションを実行する場合、すべての機能がサポートされますか?

はい。 この SDK の機能サポートは、次の例外を除き、すべてのプラットフォームで同じです。

  • パフォーマンス カウンターは、Windows でのみサポートされます。ただし、Live Metrics に表示されるプロセス CPU/メモリは例外です。

  • ServerTelemetryChannel が既定で有効になっていても、アプリケーションが Linux または macOS で実行されているときは、ネットワークに問題がある場合に、チャネルによってテレメトリを一時的に保持するためのローカル ストレージ フォルダーが自動的に作成されることはありません。 この制限のため、ネットワークやサーバーに一時的に問題が発生すると、テレメトリが失われます。 この問題を回避するには、チャネル用のローカル フォルダーを構成します。

    using Microsoft.ApplicationInsights.Channel;
    using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel;
    
        public void ConfigureServices(IServiceCollection services)
        {
            // The following will configure the channel to use the given folder to temporarily
            // store telemetry items during network or Application Insights server issues.
            // User should ensure that the given folder already exists
            // and that the application has read/write permissions.
            services.AddSingleton(typeof(ITelemetryChannel),
                                    new ServerTelemetryChannel () {StorageFolder = "/tmp/myfolder"});
            services.AddApplicationInsightsTelemetryWorkerService();
        }
    

サンプル アプリケーション

.NET Core コンソール アプリケーション: .NET Core (2.0 以上) または .NET Framework (4.7.2 以上) で記述されたコンソール アプリケーションを使用している場合は、このサンプルを使用します。

HostedService を使用した ASP.NET Core バックグラウンド タスク: ASP.NET Core を使用していて、公式のガイダンスに従ってバックグラウンド タスクを作成する場合は、このサンプルを使用します。

.NET Core Worker サービス: 公式のガイダンスに従って .NET Worker サービス アプリケーションを作成した場合は、このサンプルを使用します。

オープンソース SDK

コードを読んで協力してください。

最新の更新プログラムとバグ修正については、リリース ノートを参照してください。

次のステップ