本文說明如何為 ASP.NET Core 應用程式啟用及設定 Application Insights。
警告
我們建議新的應用程式或客戶使用 Azure Monitor OpenTelemetry Distro 以支持 Azure Monitor Application Insights。 Azure 監視器 OpenTelemetry 發行版本提供與 Application Insights SDK 類似的功能和體驗。 您可以使用適用於 .NET、Node.js 和 Python 的移轉指南,從 Application Insights SDK 移轉,但我們仍在努力新增更多功能以提供回溯相容性。
Application Insights 可以從 ASP.NET Core 應用程式收集下列遙測:
- 請求事項
- 相依性
- 例外狀況
- 效能計數器
- 心跳
- 記錄
我們將使用 MVC 應用程式範例。 如果您使用背景工作服務,請使用適用於背景工作服務應用程式的 Application Insights 中的指示。
OpenTelemetry 型 .NET 供應項目可供使用。 如需詳細資訊,請參閱 OpenTelemetry 概觀。
附註
如果您想要使用獨立 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 支援此程序。
在 Visual Studio 中,開啟您的專案。
移至 [專案]>[新增 Application Insights 遙測]。
選取 [Azure Application Insights]>[下一步]。
選擇您的訂閱和 Application Insights 實例。 或者,您可以使用 [建立新的] 來建立新的執行個體。 選取 [下一步]。
新增或確認 Application Insights 連接字串。 這應該會根據上一個步驟中的選取項目預先填入。 選取 [完成]。
將 Application Insights 新增至專案之後,請檢查以確認您正在使用最新穩定版本的 SDK。 移至 [專案] > [管理 NuGet 套件] > [Microsoft.ApplicationInsights.AspNetCore]。 如果您有需要,請選取 [更新]。
啟用 Application Insights 伺服器端遙測 (非 Visual Studio)
安裝適用於 ASP.NET Core 的 Application Insights SDK NuGet 套件。
建議您一律使用最新穩定版本。 在開放原始碼 GitHub 存放庫上尋找 SDK 的完整版本資訊。
下列程式碼範例顯示要新增至專案 .csproj 檔案的變更:
<ItemGroup> <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.21.0" /> </ItemGroup>
將 新增
AddApplicationInsightsTelemetry()
至您的 program.cs 類別。在
builder.Services.AddApplicationInsightsTelemetry();
方法後面新增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();
新增 連接字串,其可透過三種方式來完成:
(建議)在組態中設定 連接字串。
在 appsettings.json 中設定 連接字串,並確定組態檔會在發佈期間複製到應用程式根資料夾。
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "ApplicationInsights": { "ConnectionString": "InstrumentationKey=00000000-0000-0000-0000-000000000000" } }
將連接字串設定在環境變數
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
,而該變數優先於其他選項。在程式代碼中設定 連接字串。
在
ApplicationInsightsServiceOptions
類別中,將連接字串做為AddApplicationInsightsTelemetry
引數的一部分提供給 。
使用者密碼和其他設定來源
如果您想將連接字串儲存在 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特殊優待。
執行您的應用程式
執行應用程式並對其提出要求。 遙測現在應該會流向 Application Insights。 Application Insights SDK 會自動收集應用程式的傳入網頁請求,以及以下的遙測資料。
即時計量
即時計量可以用來快速驗證使用 Application Insights 是否正確地配置了應用程式監控。 遙測可能需要幾分鐘的時間才會出現在 Azure 入口網站中,但 [即時計量] 窗格會近乎即時地顯示執行中處理序的 CPU 使用率。 它還可以顯示其他遙測數據,例如請求、相依性和追蹤。
使用程式碼為任何 .NET 應用程式啟用即時計量
附註
使用 .NET 應用程式的建議指示上線時,預設會啟用即時計量。
若要手動設定即時計量:
安裝 NuGet 套件 Microsoft.ApplicationInsights.PerfCounterCollector。
下列範例主控台應用程式程式碼顯示設定即時計量:
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse;
// Create a TelemetryConfiguration instance.
TelemetryConfiguration config = TelemetryConfiguration.CreateDefault();
config.ConnectionString = "InstrumentationKey=00000000-0000-0000-0000-000000000000";
QuickPulseTelemetryProcessor quickPulseProcessor = null;
config.DefaultTelemetrySink.TelemetryProcessorChainBuilder
.Use((next) =>
{
quickPulseProcessor = new QuickPulseTelemetryProcessor(next);
return quickPulseProcessor;
})
.Build();
var quickPulseModule = new QuickPulseTelemetryModule();
// Secure the control channel.
// This is optional, but recommended.
quickPulseModule.AuthenticationApiKey = "YOUR-API-KEY-HERE";
quickPulseModule.Initialize(config);
quickPulseModule.RegisterTelemetryProcessor(quickPulseProcessor);
// Create a TelemetryClient instance. It is important
// to use the same TelemetryConfiguration here as the one
// used to set up live metrics.
TelemetryClient client = new TelemetryClient(config);
// This sample runs indefinitely. Replace with actual application logic.
while (true)
{
// Send dependency and request telemetry.
// These will be shown in live metrics.
// CPU/Memory Performance counter is also shown
// automatically without any additional steps.
client.TrackDependency("My dependency", "target", "http://sample",
DateTimeOffset.Now, TimeSpan.FromMilliseconds(300), true);
client.TrackRequest("My Request", DateTimeOffset.Now,
TimeSpan.FromMilliseconds(230), "200", true);
Task.Delay(1000).Wait();
}
上述範例適用於主控台應用程式,但相同的程式碼可用於任何 .NET 應用程式。 如果啟用任何其他遙測模組以自動收集遙測,請務必確定即時計量模組所使用的設定與這些模組初始化時使用的設定相同。
ILogger 日志
預設設定會收集 ILogger
Warning
記錄和更嚴重的記錄。 如需詳細資訊,請檢閱如何自訂 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 載入器指令碼」插入來收集使用量遙測。
在 _ViewImports.cshtml 中,新增插入:
@inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
在 _Layout.cshtml 中,在
HtmlHelper
區段的結尾插入<head>
,但在插入任何其他腳本之前。 如果您想要從頁面報告任何自訂的 JavaScript 遙測,請將它插入至此程式碼片段之後:@Html.Raw(JavaScriptSnippet.FullScript) </head>
FullScript
作為使用 ScriptBody
的替代方案,已從 Application Insights SDK for ASP.NET Core 2.14 版開始提供。 如果您需要控制 ScriptBody
標籤以設定內容安全性原則,請使用 <script>
:
<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,除非另有指示,否則幾乎所有的組態變更都應在 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 live metrics (also known as QuickPulse).
aiOptions.EnableQuickPulseMetricStream = false;
builder.Services.AddApplicationInsightsTelemetry(aiOptions);
var app = builder.Build();
下表具有完整的 ApplicationInsightsServiceOptions
設定清單:
設定 | 描述 | 預設 |
---|---|---|
EnablePerformanceCounterCollectionModule | 啟用/停用 PerformanceCounterCollectionModule 。 |
對 |
啟用請求追蹤遙測模組 | 啟用/停用 RequestTrackingTelemetryModule 。 |
對 |
EnableEventCounterCollectionModule | 啟用/停用 EventCounterCollectionModule 。 |
對 |
啟用依賴性追蹤遙測模組 | 啟用/停用 DependencyTrackingTelemetryModule 。 |
對 |
啟用應用服務心跳遙測模組 | 啟用/停用 AppServicesHeartbeatTelemetryModule 。 |
對 |
啟用 Azure 實例元資料遙測模組 (EnableAzureInstanceMetadataTelemetryModule) | 啟用/停用 AzureInstanceMetadataTelemetryModule 。 |
對 |
EnableQuickPulseMetricStream | 啟用/停用 LiveMetrics 功能。 | 對 |
啟用自適應取樣 (EnableAdaptiveSampling) | 啟用/停用調適型取樣。 | 對 |
EnableHeartbeat | 開啟/關閉心跳功能。 此功能會定期 (15 分鐘預設值) 傳送名為 HeartbeatState 的自訂計量,其中包含 .NET 版本 和 Azure 環境資訊 (若適用) 等執行階段的資訊。 |
對 |
AddAutoCollectedMetricExtractor | 啟用/停用 AutoCollectedMetrics extractor 。 此遙測處理器會在取樣發生之前,先傳送有關要求/相依性的預先彙總計量。 |
對 |
RequestCollectionOptions.TrackExceptions | 啟用/停用要求收集模組未處理的例外狀況追蹤報告。 | 在 netstandard2.0 中為 False (因為例外狀況會使用 ApplicationInsightsLoggerProvider 追蹤)。 否則為 True。 |
啟用診斷遙測模組 (EnableDiagnosticsTelemetryModule) | 啟用/停用 DiagnosticsTelemetryModule 。 停用會導致忽略下列設定:EnableHeartbeat 、EnableAzureInstanceMetadataTelemetryModule 和 EnableAppServicesHeartbeatTelemetryModule 。 |
對 |
如需最新的清單,請參閱 ApplicationInsightsServiceOptions
中可設定的設定。
Microsoft.ApplicationInsights.AspNetCore SDK 2.15.0 和更新版本的設定建議
在 Microsoft.ApplicationInsights.AspNetCore SDK 2.15.0 版和更新版本中,設定 ApplicationInsightsServiceOptions
中可用的每個設定,包括 ConnectionString
。 使用應用程式的 IConfiguration
執行個體。 設定必須位於 ApplicationInsights
區段底下,如下列範例所示。 appsettings.json 的下一區段會設定連接字串,並停用調適型取樣和效能計數器集合。
{
"ApplicationInsights": {
"ConnectionString": "InstrumentationKey=00000000-0000-0000-0000-000000000000",
"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 會自動挑選新增至 TelemetryInitializer
容器的任何 DependencyInjection
專案。
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();
新增遙測資料中央處理器
您可以在 TelemetryConfiguration
上使用擴充方法 AddApplicationInsightsTelemetryProcessor
,將自訂遙測處理器新增至 IServiceCollection
。 您在進階篩選案例中使用遙測處理器。 請使用下列範例:
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
,請在 ConfigureTelemetryModule<T>
上使用擴充方法 IServiceCollection
,如下列範例所示:
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。 它不會防止任何自動收集模組收集遙測。 如果您想要移除特定的自動收集模組,請參閱移除遙測模組。
疑難排解
請參閱專用的疑難排解文章。
測試應用程式主機與擷取服務之間的連線
應用程式深入剖析 SDK 和代理程式會傳送遙測,以擷取為 REST 呼叫擷取到我們擷取的端點。 您可以使用來自 PowerShell 或 curl 命令的原始 REST 用戶端,測試從 Web 伺服器或應用程式主機電腦到擷取服務端點的連線。 請參閱如何在 Azure Monitor Application Insights 中疑難排解應用程式遙測遺失問題。
開放原始碼 SDK
如需最新的更新和 Bug 修正,請參閱版本資訊。
版本資訊
針對 2.12 版和更新版本:.NET SDK (包括 ASP.NET、ASP.NET Core 及記錄配接器) (英文)
我們的服務更新也會摘要說明主要的 Application Insights 改善功能。
下一步
- 若要檢閱常見問題 (FAQ),請參閱 Application Insights for ASP.NET Core 常見問題
- 驗證您正在執行支援的 Application Insights SDK 版本 。
- 探索使用者流程來了解使用者如何瀏覽您的應用程式。
- 設定快照集集合,以查看擲回例外狀況時原始程式碼和變數的狀態。
- 使用 API 可傳送您自己的事件和計量,以取得您的應用程式效能和使用方式的詳細檢視。
- 使用可用性測試持續從世界各地檢查您的應用程式。
- 深入了解 ASP.NET Core 中的相依性插入。