適用於背景工作服務 (非 HTTP 應用程式) 的 Application Insights 應用程式

適用於背景工作角色服務的 Application Insights SDK 是全新的軟體開發套件,最適合非 HTTP 工作負載,例如傳訊、背景工作以及主控台應用程式。 這些應用程式類型沒有傳入 HTTP 要求的概念,例如傳統 ASP.NET/ASP.NET Core Web 應用程式。 因此,未支援針對 ASP.NETASP.NET Core 應用程式使用 Application Insights 套件。

注意

下列文件以 Application Insights 傳統 API 為依據。 Application Insights 的長期計劃是使用 OpenTelemetry 收集資料。 如需詳細資訊,請參閱為 .NET、Node.js、Python 和 Java 應用程式啟用 Azure 監視器 OpenTelemetry

新的 SDK 本身不會進行任何遙測收集作業。 作為替代,其會帶入其他知名的 Application Insights 自動收集器,例如 DependencyCollectorPerfCounterCollectorApplicationInsightsLoggingProvider。 此軟體開發套件會公開 IServiceCollection 上的擴充方法,以啟用和設定遙測集合物件。

支援的案例

適用於背景工作服務的 Application Insights SDK 最適合用於非 HTTP 應用程式,無論其執行位置或方式為何。 如果您的應用程式正在執行且具有 Azure 的網路連線能力,則可以收集遙測。 支援 .NET Core 的位置都支援 Application Insights 監視。 此套件可用於新引進的 .NET Core 背景工作角色服務ASP.NET Core 中的背景工作以及主控台應用程式,如 .NET Core 和 .NET Framework。

必要條件

您必須擁有有效的 Application Insights 連接字串。 您需要此字串才能將任何遙測傳送至 Application Insights。 如果您需要建立新的 Application Insights 資源以取得連接字串,請參閱連接字串

注意

針對檢測金鑰擷取的支援將在 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 背景工作角色服務應用程式

完整的範例會在 NuGet 網站上共享。

  1. 下載並安裝 .NET SDK.

  2. 使用 Visual Studio 新專案範本或命令列 dotnet new worker 建立新的背景工作服務專案。

  3. Microsoft.ApplicationInsights.WorkerService 套件新增至應用程式。

  4. services.AddApplicationInsightsTelemetryWorkerService(); 新增至 Program.cs 類別中的 CreateHostBuilder() 方法,如下列範例所示:

        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.

    注意

    建議您在設定中指定連接字串。 下列程式碼範例顯示如何在 appsettings.json 中指定連接字串。 務必在發佈期間將 appsettings.json 複製到應用程式根資料夾。

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

或者,在 APPLICATIONINSIGHTS_CONNECTION_STRING 環境變數中指定連接字串。

一般而言,APPLICATIONINSIGHTS_CONNECTION_STRING 會針對部署至 Web 應用程式作為 Web 工作的應用程式指定連接字串。

注意

程式碼中所指定的連接字串,其優先順序高於 APPLICATIONINSIGHTS_CONNECTION_STRING 環境變數,而此環境變數的優先順序高於其他選項。

使用託管服務的 ASP.NET Core 背景工作

本文件說明如何在 ASP.NET Core 應用程式中建立背景工作。

完整的範例會在此 GitHub 分頁中共享。

  1. Microsoft.ApplicationInsights.WorkerService 套件安裝至應用程式。

  2. services.AddApplicationInsightsTelemetryWorkerService(); 新增至 ConfigureServices() 方法,如下列範例所示:

        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 背景工作角色服務範例中的相同 appsettings.json

.NET Core/.NET Framework 主控台應用程式

如本文開頭所述,新的套件可用於從一般主控台應用程式啟用 Application Insights 遙測。 本套件的目標對象為 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 進行一次 HTTP 呼叫,並使用 ILogger 發出一些記錄。 這幾行會包裝在 TelemetryClientStartOperation 呼叫內部,其用於建立作業。 在此範例中,RequestTelemetry 名為「作業」。

Application Insights 會收集這些 ILogger 記錄,其嚴重性預設為「警告」或更高層級,並具有相依性。 這些紀錄與父子系關聯性相互關聯的 RequestTelemetry。 相互關聯也適用於跨流程/網路界限。 例如,如果系統向另一個受監視元件進行呼叫,則其也會與此父代相互關聯。

RequestTelemetry 的這項自訂作業可被視為一般 Web 應用程式中傳入 Web 要求的對等項目。 不需要使用作業,但其最適用於 Application Insights 相互關聯資料模型RequestTelemetry 會充當父代作業,在背景工作角色反覆項目中生成的每個遙測資料在邏輯上都被視為屬於同一作業。

此方法也可確保所有自動和手動產生的遙測都會具有相同的 operation_id。 由於取樣是以 operation_id 為基礎,取樣演算法會保留或卸除單一反覆運算的所有遙測。

以下章節列出 Application Insights 自動收集的完整遙測。

即時計量

即時計量可用於快速驗證 Application Insights 監視是否設定正確。 雖然遙測可能需要幾分鐘的時間才會出現在入口網站和分析中,但即時計量會以近乎即時的方式,顯示執行中處理序的 CPU 使用率。 即時計量也可以顯示其他遙測,例如要求、相依性、追蹤等。

ILogger 記錄

會自動擷取透過 ILogger 發出的嚴重性「警告」或更高層級紀錄。 若要變更此行為,請如下列程式碼所示,明確覆寫提供者 ApplicationInsights 的記錄設定。 下列設定可讓 Application Insights 擷取所有 Information 記錄和更嚴重的記錄。

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

請務必注意,下列範例不會造成 Application Insights 提供者擷取 Information 記錄。 它不會擷取紀錄,因為 SDK 會新增預設記錄篩選器,指示 ApplicationInsights 僅擷取 Warning 記錄和更嚴重的記錄。 Application Insights 需要明確覆寫。

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

如需詳細資訊,請遵循 ILogger 文件來自訂 Application Insights 所擷取的記錄層級。

相依性

預設會啟用相依性收集功能。 Application Insights 中的相依性追蹤一文說明自動收集的相依性,也包含進行手動追蹤的步驟。

EventCounter

EventCounterCollectionModule 預設會啟用,其會從 .NET 應用程式收集一組預設的計數器。 EventCounter 教學課程會列出所收集的預設計數器集。 該文也提供如何自訂清單的指示。

手動追蹤其他遙測

雖然 SDK 會自動收集先前說明的遙測,但在大多數情況下,您將需要將其他遙測傳送至 Application Insights。 追蹤其他遙測的建議方法是從相依性插入取得 TelemetryClient 的執行個體,然後在該執行個體上呼叫其中一個支援的 TrackXXX()API 方法。 另一個典型的使用案例是自訂作業追蹤。 上述背景工作範例示範了此方法。

設定 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() 區段中進行幾乎所有的組態變更。

注意

使用此軟體開發套件時,未支援藉由修改 TelemetryConfiguration.Active 來變更設定,而且不會反映變更。

使用 ApplicationInsightsServiceOptions

您可以將 ApplicationInsightsServiceOptions 傳遞至 AddApplicationInsightsTelemetryWorkerService 來修改一些常見的設定,如下列範例所示:

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 位於命名空間 Microsoft.ApplicationInsights.WorkerService,而不是 ASP.NET Core SDK 中的 Microsoft.ApplicationInsights.AspNetCore.Extensions

下表列出在 ApplicationInsightsServiceOptions 常用的設定。

設定 描述 預設
EnableQuickPulseMetricStream 啟用/停用即時計量功能。 True
EnableAdaptiveSampling 啟用/停用調適型取樣。 True
EnableHeartbeat 啟用/停用活動訊號功能,此功能會定期 (15 分鐘預設值) 傳送名為 “HeartBeatState” 的自訂計量,其中包含 .NET 版本、Azure 環境 (若適用) 等執行階段的資訊。 True
AddAutoCollectedMetricExtractor 啟用/停用 AutoCollectedMetrics 擷取器,這是一種遙測資料中央處理器,可在取樣發生之前傳送有關要求/相依性的預先彙總計量。 True
EnableDiagnosticsTelemetryModule 啟用/停用 DiagnosticsTelemetryModule。 停用此設定會導致系統忽略下列設定:EnableHeartbeatEnableAzureInstanceMetadataTelemetryModuleEnableAppServicesHeartbeatTelemetryModule True

如需最新的清單,請參閱 ApplicationInsightsServiceOptions 中可設定的設定。

取樣

適用於背景工作服務的 Application Insights SDK 支援固定速率取樣調適型取樣。 預設會啟用調適型取樣。 使用 ApplicationInsightsServiceOptions 中的 EnableAdaptiveSampling 選項可以停用取樣作業。

若要調整其他取樣設定,可以使用下列範例:

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 容器中,軟體開發套件會自動將其新增至 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));
   }

新增遙測資料中央處理器

您可以在 IServiceCollection 上使用擴充方法 AddApplicationInsightsTelemetryProcessor,將自訂遙測處理器新增至 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 問題 1689。)
  • AzureInstanceMetadataTelemetryModule

若要設定任何預設遙測模組,請在 IServiceCollection 上使用擴充方法 ConfigureTelemetryModule<T>,如下列範例所示:

    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 監視器 Application Insights 代理程式 (先前稱為狀態監視器 v2) 之類的工具來啟用 Application Insights 監視嗎?

否。 Azure 監視器 Application Insights 代理程式目前僅支援 .NET

如果我在 Linux 中執行我的應用程式,則是否支援所有功能?

是。 此 SDK 的功能支援在所有平台上都一樣,但有下列例外狀況:

  • 效能計數器僅在 Windows 中提供支援,即時計量中顯示的程序 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 或更新版本) 撰寫的主控台應用程式,則請使用此範例。

使用 HostedServices 的 ASP.NET Core 背景工作:如果您在 ASP.NET Core 中,並依據官方指導建立背景工作,則請使用此範例。

.NET Core 背景工作角色服務:如果依據官方指導,您擁有 .NET 背景工作角色服務應用程式,則使用此範例。

開放原始碼 SDK

讀取和貢獻程式碼

如需即時的更新和錯誤 (bug) 修正,請參閱版本資訊

下一步