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 for Worker Service 應用程式中指示。

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 服務、Azure 虛擬機器、Docker 和 Azure Kubernetes Service 的 Web Apps 功能(AKS)
  • .NET 版本:所有正式 支援的 .NET 版本 均未處於預覽狀態
  • IDE:Visual Studio、Visual Studio Code 或命令行

必要條件

您需要:

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

針對 Visual Studio for Mac,請使用 手動指引。 只有 Windows 版本的 Visual Studio 支援此程式。

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

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

  3. 選取 [Azure 應用程式 [深入解析>] [下一步]。

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

  5. 新增或確認 Application Insights 連接字串。 它應該根據您在上一個步驟中的選取專案預先填入。 選取 [完成]。

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

    Screenshot that shows where to select the Application Insights package for update.

啟用 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 版本。

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

    // 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:ConnectionString JSON 組態檔中指定 連接字串APPLICATIONINSIGHTS_CONNECTION_STRING

    例如:

    • 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.AspNetCore 2.15.0 版和更新版本中,呼叫 services.AddApplicationInsightsTelemetry() 會自動從Microsoft.Extensions.Configuration.IConfiguration應用程式讀取 連接字串。 不需要明確提供 IConfiguration

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

執行您的應用程式

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

即時計量

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

ILogger 記錄

默認組態會 ILoggerWarning 收集記錄和更嚴重的記錄。 如需詳細資訊,請參閱 如何? 自定義 ILogger 記錄收集?

相依性

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

效能計數器

ASP.NET Core 中性能計數器的支援有限:

  • 如果應用程式是在 Web Apps 中執行,SDK 2.4.1 版和更新版本會收集性能計數器。
  • SDK 2.7.1 版和更新版本會在應用程式在 Windows 中執行且目標 netstandard2.0 或更新版本時收集性能計數器。
  • 針對以 .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.cshtmlHtmlHelper 結尾 <head> 插入 ,但在任何其他文稿之前插入 。 如果您想要從頁面報告任何自訂 JavaScript 遙測,請在此代碼段之後插入:

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

除了使用 FullScriptScriptBody 可從 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 JavaScript (Web) SDK 載入器腳本必須出現在 <head> 您要監視之應用程式每個頁面的 區段中。 將 JavaScript JavaScript (Web) SDK 載入器腳本新增至 _Layout.cshtml 應用程式範本中,以啟用用戶端監視。

如果您的專案不包含 _Layout.cshtml,您仍然可以將 JavaScript 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

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

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 啟用/停用活動訊號功能。 如果適用的話,它會定期傳送名為 HeartbeatState 的自定義計量,其中包含運行時間的相關信息,例如 .NET 版本和 Azure 環境資訊。 True
AddAutoCollectedMetricExtractor 開啟/停用 AutoCollectedMetrics extractor。 此遙測處理器會在取樣發生之前,先傳送有關要求/相依性的預先匯總計量。 True
RequestCollectionOptions.TrackExceptions 啟用/停用要求收集模組未處理的例外狀況追蹤報告。 False in netstandard2.0 (因為例外狀況會使用 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的設定。

取樣

適用於 ASP.NET Core 的 Application Insights SDK 同時支援固定速率和自適性取樣。 根據預設,會啟用調適型取樣。

如需詳細資訊,請參閱 設定 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 2.8.0 版和 Visual Studio 2019 或更新版本的 Application Insights SDK 可以搭配 ASP.NET Core 3.1 應用程式使用。

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

使用建構函式插入取得 的 TelemetryClient 實例,並在其上呼叫必要的 TrackXXX() 方法。 不建議在 ASP.NET Core 應用程式中建立新的 TelemetryClientTelemetryConfiguration 實例。 的單一實例已在容器中DependencyInjection註冊,此實例TelemetryClient會與其餘的遙測共用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 會新增默認記錄篩選器,指示 ApplicationInsightsWarning 擷取記錄和更嚴重的記錄。 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 進行偵錯時,您可以在本機看到遙測。
  • 您可以使用 API 來追蹤更多自訂遙測 TrackXXX()
  • 您可以完全控制組態。

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

是。 在 Application Insights Agent 2.0.0-beta1 和更新版本中,支援裝載在 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"
    
  • 連線 edService.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
            }
    

疑難排解

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

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

開放原始碼 SDK

讀取並參與程序代碼

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

版本資訊

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

我們的服務 更新 也摘要說明主要的 Application Insights 改進。

下一步