共用方式為


適用於 ASP.NET Core 應用程式的 Application Insights

本文說明如何為 ASP.NET Core 應用程式啟用及設定 Application Insights。

注意

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

Application Insights 可以從 ASP.NET Core 應用程式收集下列遙測:

  • 要求
  • 相依性
  • 例外狀況
  • 效能計數器
  • 活動訊號
  • 記錄

我們將使用 MVC 應用程式範例。 如果您使用背景工作服務,請使用適用於背景工作服務應用程式的 Application Insights 中的指示。

OpenTelemetry 型 .NET 供應項目可供使用。 如需詳細資訊,請參閱 OpenTelemetry 概觀

注意

針對檢測金鑰擷取的支援將在 2025 年 3 月 31 日結束。 檢測金鑰擷取將會繼續運作,但我們不再提供該功能的更新或支援。 轉換至連接字串以利用新功能

注意

如果您想要使用獨立 ILogger 提供者,請使用 Microsoft.Extensions.Logging.ApplicationInsight

支援的案例

ASP.NET Core 的 Application Insights SDK 可以監視應用程式,無論其執行位置或方式為何。 如果您的應用程式正在執行且具有 Azure 的網路連線能力,則可以收集遙測。 支援 .NET Core 的任何地方都支援 Application Insights 監視,並涵蓋以下情節:

  • 作業系統:Windows、Linux 或 Mac
  • 裝載方法:同處理序或跨處理序
  • 部署方法:架構相依或獨立式
  • 網頁伺服器:Internet Information Server (IIS) 或 Kestrel
  • 裝載平台:Azure App Service、Azure 虛擬機器、Docker 和 Azure Kubernetes Service (AKS) 的 Web Apps 功能
  • .NET 版本:所有正式支援的 .NET 版本都未處於預覽狀態
  • IDE:Visual Studio、Visual Studio Code 或命令列

必要條件

您需要:

  • 正常運作的 ASP.NET Core 應用程式。 如果您需要建立 ASP.NET Core 應用程式,請遵循此 ASP.NET Core 教學課程
  • Application Insights NuGet 套件支援版本的參考。
  • 有效的 Application Insights 連接字串。 您需要此字串才能將任何遙測傳送至 Application Insights。 如果您需要建立新的 Application Insights 資源以取得連接字串,請參閱建立 Application Insights 資源

啟用 Application Insights 伺服器端遙測 (Visual Studio)

如需 Visual Studio for Mac,請使用手動指引。 只有 Windows 版本的 Visual Studio 支援此程序。

  1. 在 Visual Studio 中,開啟您的專案。

  2. 移至 [專案]>[新增 Application Insights 遙測]

  3. 選取 [Azure Application Insights]>[下一步]

  4. 選擇您的訂用帳戶和 Application Insights 執行個體。 或者,您可以使用 [建立新的] 來建立新的執行個體。 選取 [下一步]。

  5. 新增或確認 Application Insights 連接字串。 這應該會根據上一個步驟中的選取項目預先填入。 選取 [完成]。

  6. 將 Application Insights 新增至專案之後,請檢查以確認您正在使用最新穩定版本的 SDK。 移至 [專案] > [管理 NuGet 套件] > [Microsoft.ApplicationInsights.AspNetCore]。 如果您有需要,請選取 [更新]

    顯示要在哪裡選取 Application Insights 套件以進行更新的螢幕快照。

啟用 Application Insights 伺服器端遙測 (非 Visual Studio)

  1. 安裝適用於 ASP.NET Core 的 Application Insights SDK NuGet 套件

    建議您一律使用最新穩定版本。 在開放原始碼 GitHub 存放庫上尋找 SDK 的完整版本資訊。

    下列程式碼範例顯示要新增至專案 .csproj 檔案的變更:

    <ItemGroup>
        <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.21.0" />
    </ItemGroup>
    
  2. AddApplicationInsightsTelemetry() 新增至您的 startup.csprogram.cs 類別。 此選擇取決於您的 .NET Core 版本。

    builder.Services.AddApplicationInsightsTelemetry(); 新增至 Program 類別中的 WebApplication.CreateBuilder() 方法之後,如下列範例所示:

    // This method gets called by the runtime. Use this method to add services to the container.
    var builder = WebApplication.CreateBuilder(args);
    
    // The following line enables Application Insights telemetry collection.
    builder.Services.AddApplicationInsightsTelemetry();
    
    // This code adds other services for your application.
    builder.Services.AddMvc();
    
    var app = builder.Build();
    
  3. 設定連接字串。

    雖然您可以在 AddApplicationInsightsTelemetryApplicationInsightsServiceOptions 引數中提供連接字串,但建議您在設定中指定連接字串。 下列程式碼範例顯示如何在 appsettings.json 中指定連接字串。 務必在發佈期間將 appsettings.json 複製到應用程式根資料夾。

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*",
      "ApplicationInsights": {
        "ConnectionString": "Copy connection string from Application Insights Resource Overview"
      }
    }
    

    或者,在 APPLICATIONINSIGHTS_CONNECTION_STRING 環境變數或 JSON 設定檔中的 ApplicationInsights:ConnectionString 中指定連接字串。

    例如:

    • SET ApplicationInsights:ConnectionString = <Copy connection string from Application Insights Resource Overview>
    • SET APPLICATIONINSIGHTS_CONNECTION_STRING = <Copy connection string from Application Insights Resource Overview>
    • 一般而言,APPLICATIONINSIGHTS_CONNECTION_STRING 會用於 Web Apps。 但也可用於支援此 SDK 的所有位置。

    注意

    在程式碼中指定的連接字串會優先於環境變數 APPLICATIONINSIGHTS_CONNECTION_STRING,而該變數優先於其他選項。

使用者祕密和其他設定提供者

如果您想要將連接字串儲存在 ASP.NET Core 使用者祕密中,或從另一個設定提供者擷取連接字串,您可以使用多載搭配 Microsoft.Extensions.Configuration.IConfiguration 參數。 範例參數為 services.AddApplicationInsightsTelemetry(Configuration);

Microsoft.ApplicationInsights.AspNetCore2.15.0 版和更新版本中,呼叫 services.AddApplicationInsightsTelemetry() 會自動從應用程式的 Microsoft.Extensions.Configuration.IConfiguration 中讀取連接字串。 不需要明確提供 IConfiguration

如果 IConfiguration 已從多個提供者載入設定,則不論提供者的新增順序為何,services.AddApplicationInsightsTelemetry 都優先處理來自 appsettings.json 的設定。 使用 services.AddApplicationInsightsTelemetry(IConfiguration) 方法可從 IConfiguration 讀取設定,而不需進行這項 appsettings.json 的優先處理。

執行您的應用程式

執行應用程式並對其提出要求。 遙測現在應該會流向 Application Insights。 Application Insights SDK 會自動收集應用程式的傳入 Web 要求,以及下列遙測。

即時計量

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

ILogger 記錄

預設設定會收集 ILoggerWarning 記錄和更嚴重的記錄。 如需詳細資訊,請檢閱如何自訂 ILogger 記錄收集?

相依性

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

效能計數器

ASP.NET Core 效能計數器的支援受限制:

  • 如果應用程式是在 Web Apps (Windows) 中執行,SDK 版本2.4.1 和以後版本會收集效能計數器。
  • 如果應用程式是在 Windows 中執行,而且目標是 netstandard2.0 或以後版本,SDK 版本2.7.1 和更新版本會收集效能計數器。
  • 對於以 .NET Framework 為目標的應用程式,所有版本的 SDK 都支援效能計數器。
  • SDK 版本 2.8.0 和更新版本支援 Linux 中的 CPU/記憶體計數器。 Linux 不支援其他計數器。 若要在 Linux 和其他非 Windows 環境中取得系統計數器,請使用 EventCounters

EventCounter

預設會啟用 EventCounterCollectionModule。 若要了解如何設定所要收集計數器的清單,請參閱 EventCounters 簡介

透過 HTTP 擴充資料

HttpContext.Features.Get<RequestTelemetry>().Properties["myProp"] = someData

啟用 Web 應用程式的用戶端遙測

上述步驟足以協助您開始收集伺服器端遙測。 如果您的應用程式具有用戶端元件,請遵循後續步驟,開始根據設定,使用「JavaScript (Web) SDK 載入器指令碼」插入來收集使用量遙測

  1. _ViewImports.cshtml 中,新增插入:

    @inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
    
  2. _Layout.cshtml 中,於 <head> 區段結尾插入 HtmlHelper,但需插入在任何其他指令碼之前。 如果您想要從頁面報告任何自訂的 JavaScript 遙測,請將它插入至此程式碼片段之後:

    @Html.Raw(JavaScriptSnippet.FullScript)
    </head>
    

ScriptBody 作為使用 FullScript 的替代方案,已從 Application Insights SDK for ASP.NET Core 2.14 版開始提供。 如果您需要控制 <script> 標籤以設定內容安全性原則,請使用 ScriptBody

<script> // apply custom changes to this script tag.
 @Html.Raw(JavaScriptSnippet.ScriptBody)
</script>

之前參考的 .cshtml 檔案名,來自於預設 MVC 應用程式範本。 最後,如果您想要正確啟用應用程式的用戶端監視,則 JavaScript (Web) SDK 載入器指令碼必須出現在所要監視應用程式其每個頁面的 <head> 區段中。 將 JavaScript (Web) SDK 載入器指令碼新增至應用程式範本中的 _Layout.cshtml,以啟用用戶端監視。

如果您的專案不包含 _Layout.cshtml,您仍然可以將 JavaScript (Web) SDK 載入器新增至控制應用程式內所有頁面 <head> 的對等檔案,以新增用戶端監視。 或者,您可以將 JavaScript (Web) SDK 載入器指令碼新增至多個頁面,但我們不建議這麼做。

注意

JavaScript 插入提供預設的設定體驗。 如果您需要設定連接字串以外的設定,您必須依照說明移除自動插入,並手動新增 JavaScript SDK

設定 Application Insights SDK

您可以自訂 Application Insights SDK for ASP.NET Core 來變更預設設定。 Application Insights ASP.NET SDK 的使用者可能熟悉使用 ApplicationInsights.config 或修改 TelemetryConfiguration.Active 來變更設定。 針對 ASP.NET Core,除非您另有指示,否則請在 Startup.cs 類別的 ConfigureServices() 方法中進行幾乎所有設定變更。 如需詳細資訊,請參閱下列章節。

注意

在 ASP.NET Core 應用程式中,不支援藉由修改 TelemetryConfiguration.Active 來變更設定。

使用 ApplicationInsightsServiceOptions

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

var builder = WebApplication.CreateBuilder(args);

var aiOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();

// Disables adaptive sampling.
aiOptions.EnableAdaptiveSampling = false;

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

builder.Services.AddApplicationInsightsTelemetry(aiOptions);
var app = builder.Build();

下表具有完整的 ApplicationInsightsServiceOptions 設定清單:

設定 描述 預設
EnablePerformanceCounterCollectionModule 啟用/停用 PerformanceCounterCollectionModule True
EnableRequestTrackingTelemetryModule 啟用/停用 RequestTrackingTelemetryModule True
EnableEventCounterCollectionModule 啟用/停用 EventCounterCollectionModule True
EnableDependencyTrackingTelemetryModule 啟用/停用 DependencyTrackingTelemetryModule True
EnableAppServicesHeartbeatTelemetryModule 啟用/停用 AppServicesHeartbeatTelemetryModule True
EnableAzureInstanceMetadataTelemetryModule 啟用/停用 AzureInstanceMetadataTelemetryModule True
EnableQuickPulseMetricStream 啟用/停用 LiveMetrics 功能。 True
EnableAdaptiveSampling 啟用/停用調適型取樣。 True
EnableHeartbeat 啟用/停用活動訊號功能。 此功能會定期 (15 分鐘預設值) 傳送名為 HeartbeatState 的自訂計量,其中包含 .NET 版本 和 Azure 環境資訊 (若適用) 等執行階段的資訊。 True
AddAutoCollectedMetricExtractor 啟用/停用 AutoCollectedMetrics extractor。 此遙測處理器會在取樣發生之前,先傳送有關要求/相依性的預先彙總計量。 True
RequestCollectionOptions.TrackExceptions 啟用/停用要求收集模組未處理的例外狀況追蹤報告。 netstandard2.0 中為 False (因為例外狀況會使用 ApplicationInsightsLoggerProvider 追蹤)。 否則為 True。
EnableDiagnosticsTelemetryModule 啟用/停用 DiagnosticsTelemetryModule。 停用會導致忽略下列設定:EnableHeartbeatEnableAzureInstanceMetadataTelemetryModuleEnableAppServicesHeartbeatTelemetryModule True

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

Microsoft.ApplicationInsights.AspNetCore SDK 2.15.0 和更新版本的設定建議

在 Microsoft.ApplicationInsights.AspNetCore SDK 2.15.0 版和更新版本中,設定 ApplicationInsightsServiceOptions 中可用的每個設定,包括 ConnectionString。 使用應用程式的 IConfiguration 執行個體。 設定必須位於 ApplicationInsights 區段底下,如下列範例所示。 appsettings.json 的下一區段會設定連接字串,並停用調適型取樣和效能計數器集合。

{
    "ApplicationInsights": {
    "ConnectionString": "Copy connection string from Application Insights Resource Overview",
    "EnableAdaptiveSampling": false,
    "EnablePerformanceCounterCollectionModule": false
    }
}

如果使用 builder.Services.AddApplicationInsightsTelemetry(aiOptions) (ASP.NET Core 6.0) 或 services.AddApplicationInsightsTelemetry(aiOptions) (ASP.NET Core 3.1 和更早版本),則會覆寫 Microsoft.Extensions.Configuration.IConfiguration 的設定。

取樣

Application Insights SDK for ASP.NET Core 支援固定速率和調適型取樣。 預設會啟用調適型取樣。

如需詳細資訊,請參閱為 ASP.NET Core 應用程式設定調適型取樣

新增 TelemetryInitializers

當您想要使用其他資訊擴充遙測時,請使用遙測初始設定式

將任何新的 TelemetryInitializer 新增至 DependencyInjection 容器,如下列程式碼所示。 SDK 會自動挑選新增至 DependencyInjection 容器的任何 TelemetryInitializer 專案。

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<ITelemetryInitializer, MyCustomTelemetryInitializer>();

var app = builder.Build();

注意

builder.Services.AddSingleton<ITelemetryInitializer, MyCustomTelemetryInitializer>(); 適用於簡單的初始設定式。 除此之外,則需要 builder.Services.AddSingleton(new MyCustomTelemetryInitializer() { fieldName = "myfieldName" });

移除 TelemetryInitializers

預設存在遙測初始設定式。 若要移除所有或特定的遙測初始設定式,請在呼叫 AddApplicationInsightsTelemetry()「之後」,使用下列範例程式碼。

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddApplicationInsightsTelemetry();

// Remove a specific built-in telemetry initializer
var tiToRemove = builder.Services.FirstOrDefault<ServiceDescriptor>
                    (t => t.ImplementationType == typeof(AspNetCoreEnvironmentTelemetryInitializer));
if (tiToRemove != null)
{
    builder.Services.Remove(tiToRemove);
}

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

var app = builder.Build();

新增遙測資料中央處理器

您可以在 IServiceCollection 上使用擴充方法 AddApplicationInsightsTelemetryProcessor,將自訂遙測處理器新增至 TelemetryConfiguration。 您在進階篩選案例中使用遙測處理器。 請使用下列範例:

var builder = WebApplication.CreateBuilder(args);

// ...
builder.Services.AddApplicationInsightsTelemetry();
builder.Services.AddApplicationInsightsTelemetryProcessor<MyFirstCustomTelemetryProcessor>();

// If you have more processors:
builder.Services.AddApplicationInsightsTelemetryProcessor<MySecondCustomTelemetryProcessor>();

var app = builder.Build();

設定或移除預設 TelemetryModules

Application Insights 會自動收集特定工作負載的相關遙測,而不需要使用者手動追蹤。

預設會啟用下列自動收集模組。 這些模組負責自動收集遙測。 您可加以停用或設定來改變其預設行為。

  • RequestTrackingTelemetryModule:從傳入 Web 要求收集 RequestTelemetry。
  • DependencyTrackingTelemetryModule:從傳出 HTTP 呼叫和 SQL 呼叫收集 DependencyTelemetry
  • PerformanceCollectorModule:收集 Windows PerformanceCounters。
  • QuickPulseTelemetryModule:收集遙測,以在即時計量入口網站中顯示。
  • AppServicesHeartbeatTelemetryModule:收集裝載應用程式的 App Service 環境相關活動訊號 (作為自訂計量傳送)。
  • AzureInstanceMetadataTelemetryModule:收集裝載應用程式的 Azure VM 環境相關活動訊號 (作為自訂計量傳送)。
  • EventCounterCollectionModule:收集 EventCounters。 此模組是新功能,可在 SDK 2.8.0 版和更新版本中使用。

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

using Microsoft.ApplicationInsights.DependencyCollector;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddApplicationInsightsTelemetry();

// The following configures DependencyTrackingTelemetryModule.
// Similarly, any other default modules can be configured.
builder.Services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>((module, o) =>
        {
            module.EnableW3CHeadersInjection = true;
        });

// The following removes all default counters from EventCounterCollectionModule, and adds a single one.
builder.Services.ConfigureTelemetryModule<EventCounterCollectionModule>((module, o) =>
        {
            module.Counters.Add(new EventCounterCollectionRequest("System.Runtime", "gen-0-size"));
        });

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

var app = builder.Build();

在 2.12.2 版和更新版本中,ApplicationInsightsServiceOptions 包含可停用任何預設模組的簡單選項。

設定遙測通道

預設遙測通道ServerTelemetryChannel。 下列範例會示範如何對其進行覆寫。

using Microsoft.ApplicationInsights.Channel;

var builder = WebApplication.CreateBuilder(args);

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

builder.Services.AddApplicationInsightsTelemetry();

var app = builder.Build();

注意

如果您想要排清緩衝區,請參閱排清資料。 例如,如果您在關閉的應用程式中使用 SDK,您可能需要排清緩衝區。

動態停用遙測

如果您想要有條件且動態地停用遙測,則可在您的程式碼中使用 ASP.NET Core 相依性插入容器來解析 TelemetryConfiguration 執行個體,並在其上設定 DisableTelemetry 旗標。

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddApplicationInsightsTelemetry();

// any custom configuration can be done here:
builder.Services.Configure<TelemetryConfiguration>(x => x.DisableTelemetry = true);

var app = builder.Build();

上述程式碼範例會防止將遙測傳送至 Application Insights。 它不會防止任何自動收集模組收集遙測。 如果您想要移除特定的自動收集模組,請參閱移除遙測模組

常見問題集

本節提供常見問題的答案。

Application Insights 是否支援 ASP.NET Core 3.1?

Microsoft 不再支援 ASP.NET Core 3.1。

適用於 ASP.NET Core 的 Application Insights SDK 2.8.0 版和 Visual Studio 2019 或更新版本可以搭配 ASP.NET Core 3.1 應用程式使用。

如何追蹤未自動收集的遙測?

使用建構函式插入取得 TelemetryClient 的執行個體,並在該執行個體上呼叫必要的 TrackXXX() 方法。 不建議在 ASP.NET Core 應用程式中建立新的 TelemetryClientTelemetryConfiguration 執行個體。 TelemetryClient 的單一執行個體已經在 DependencyInjection 容器中註冊,其會與其餘的遙測共用 TelemetryConfiguration。 只有在需要與其餘遙測分開的設定時,再建立新的 TelemetryClient 執行個體。

下列範例示範如何從控制器追蹤更多遙測資料。

using Microsoft.ApplicationInsights;

public class HomeController : Controller
{
    private TelemetryClient telemetry;

    // Use constructor injection to get a TelemetryClient instance.
    public HomeController(TelemetryClient telemetry)
    {
        this.telemetry = telemetry;
    }

    public IActionResult Index()
    {
        // Call the required TrackXXX method.
        this.telemetry.TrackEvent("HomePageRequested");
        return View();
    }

如需 Application Insights 中自訂資料報告的詳細資訊,請參閱 Application Insights 自訂計量 API 參考。 類似的方法可用於使用 GetMetric API 將自訂指標傳送至 Application Insights。

如何? 擷取遙測中的要求和回應本文?

ASP.NET Core 內 建支援 透過 ILogger記錄 HTTP 要求/回應資訊(包括本文)。 建議您利用這項功能。 這可能會公開遙測中的個人標識資訊(PII),並可能導致成本(效能成本和 Application Insights 計費)大幅增加,因此請在使用此資訊之前仔細評估風險。

如何自訂 ILogger 記錄集合?

Application Insights 的預設設定是只會擷取警告和更嚴重的記錄。

變更 Application Insights 提供者的記錄設定來擷取資訊及較不嚴重的記錄,如下所示。

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

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

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

如需詳細資訊,請參閱 ILogger 設定

特定 Visual Studio 範本使用 IWebHostBuilder 上的 UseApplicationInsights () 擴充方法以啟用 Application Insights。 此使用方式是否仍然有效?

仍支援擴充方法 UseApplicationInsights(),但它在 Application Insights SDK 2.8.0 版和更新版本中標示為已淘汰。 這會在下一個主要版本的 SDK 中移除。 若要啟用 Application Insights 遙測資料,請使用 AddApplicationInsightsTelemetry(),因為它提供多載以控制某些設定。 此外,在 ASP.NET Core 3.X 應用程式中,services.AddApplicationInsightsTelemetry() 是啟用 Application Insights 的唯一方式。

我正在將我的 ASP.NET Core 應用程式部署至 Web Apps。 我是否仍應從 Web Apps 啟用 Application Insights 延伸模組?

如果如本文所示在組建階段安裝 SDK,您無需從 App Service 入口網站啟用 Application Insights 延伸模組。 如果已安裝延伸模組,則會在偵測到已新增 SDK 時停止。 如果您從延伸模組啟用 Application Insights,則無需安裝及更新 SDK。 但如果您依照本文中的指示啟用 Application Insights,您可以有更多的靈活性,原因如下:

  • Application Insights 遙測資料會繼續在以下位置運作:
    • 所有作業系統,包括 Windows、Linux 和 Mac。
    • 所有發佈模式,包括獨立式或架構相依。
    • 所有目標框架,包括完整的 .NET Framework。
    • 所有裝載選項,包括 Web Apps、VM、Linux、容器、AKS 和非 Azure 裝載。
    • 所有 .NET Core 版本,包括預覽版。
  • 當您從 Visual Studio 進行偵錯時,可以在本機看到遙測資料。
  • 您可以使用 TrackXXX() API 來追蹤更多自訂遙測資料。
  • 您可以完全控制您的設定。

我可以使用 Azure 監視器 Application Insights 代理程式 (先前稱為狀態監視器 v2) 之類的工具來啟用 Application Insights 監視嗎?

是。 在 Application Insights 代理程式 2.0.0 搶鮮版 1 及後續版本中,可支援裝載在 IIS 中的 ASP.NET Core 應用程式。

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

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

此 SDK 是否支援背景工作服務?

否。 請針對背景工作服務使用Application Insights for Worker Service 應用程式(非 HTTP 應用程式)。

如何解除安裝 SDK?

若要移除 Application Insights,您必須從應用程式中的 API 移除 NuGet 套件和參考。 您可以使用 Visual Studio 中的 NuGet 套件管理員來解除安裝 NuGet 套件。

注意

這些指示可用來解除安裝 ASP.NET Core SDK。 如果您需要解除安裝 ASP.NET SDK,請參閱如何解除安裝 ASP.NET SDK?

  1. 使用 NuGet 套件管理員解除安裝 Microsoft.ApplicationInsights.AspNetCore 套件。
  2. 若要完全移除 Application Insights,請檢查並手動刪除新增的程式碼或檔案,以及您在專案中新增的任何 API 呼叫。 如需詳細資訊,請參閱新增 Application Insights SDK 時所建立的內容為何?

新增 Application Insights SDK 時所建立的內容為何?

當您將 Application Insights 新增至專案時,系統會建立檔案,並將程式碼新增至部分檔案。 單是解除安裝 NuGet 套件不一定會捨棄檔案和程式碼。 若要完全移除 Application Insights,您應該檢查並手動刪除新增的程式碼或檔案,以及您在專案中新增的任何 API 呼叫。

當您將 Application Insights 遙測新增至 Visual Studio ASP.NET Core 範本專案時,此工具會新增下列程式碼:

  • [您的專案名稱].csproj

      <PropertyGroup>
        <TargetFramework>netcoreapp3.1</TargetFramework>
        <ApplicationInsightsResourceId>/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/Default-ApplicationInsights-EastUS/providers/microsoft.insights/components/WebApplication4core</ApplicationInsightsResourceId>
      </PropertyGroup>
    
      <ItemGroup>
        <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.12.0" />
      </ItemGroup>
    
      <ItemGroup>
        <WCFMetadata Include="Connected Services" />
      </ItemGroup>
    
  • Appsettings.json:

    "ApplicationInsights": {
        "InstrumentationKey": "00000000-0000-0000-0000-000000000000"
    
  • ConnectedService.json

    {
      "ProviderId": "Microsoft.ApplicationInsights.ConnectedService.ConnectedServiceProvider",
      "Version": "16.0.0.0",
      "GettingStartedDocument": {
        "Uri": "https://go.microsoft.com/fwlink/?LinkID=798432"
      }
    }
    
  • Startup.cs

       public void ConfigureServices(IServiceCollection services)
            {
                services.AddRazorPages();
                services.AddApplicationInsightsTelemetry(); // This is added
            }
    

疑難排解

請參閱專用的疑難排解文章

測試應用程式主機與擷取服務之間的連線

應用程式深入剖析 SDK 和代理程式會傳送遙測,以擷取為 REST 呼叫擷取到我們擷取的端點。 您可以使用來自 PowerShell 或 curl 命令的原始 REST 用戶端,測試從 Web 伺服器或應用程式主機電腦到擷取服務端點的連線。 請參閱針對 Azure 監視器 Application Insights 中遺失的應用程式遙測進行疑難排解

開放原始碼 SDK

讀取和貢獻程式碼

如需最新的更新和 Bug 修正,請參閱版本資訊

版本資訊

針對 2.12 版和更新版本:.NET SDK (包括 ASP.NET、ASP.NET Core 及記錄配接器) (英文)

我們的服務更新也會摘要說明主要的 Application Insights 改善功能。

下一步