你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
注意
我们建议新应用程序或客户使用 Azure Monitor OpenTelemetry 发行版来支持 Azure Monitor Application Insights。 Azure Monitor OpenTelemetry 发行版提供与 Application Insights SDK 类似的功能和体验。 可以使用 .NET、Node.js 和 Python 的迁移指南从 Application Insights SDK 进行迁移,但我们仍在努力添加更多功能以实现后向兼容性。
本文介绍如何为 ASP.NET 和 ASP.NET Core 应用程序启用和配置 Application Insights。 此过程将应用程序配置为将遥测数据发送到 Application Insights。
Application Insights 可以从 ASP.NET 和 ASP.NET 核心应用程序收集以下遥测数据:
- 请求
- 依赖关系
- 例外
- 性能计数器
- 跟踪(日志)
- 心跳
- 自定义事件和指标 (需要手动检测)
- 页面视图 (需要网页使用的 JavaScript SDK)
- 可用性测试 (需要手动设置可用性测试)
支持的方案
注意
无论在何处以何种方式运行你的应用程序,适用于 ASP.NET Core 的 Application Insights SDK 都可对其进行监视。 如果应用程序正在运行并与 Azure 建立了网络连接,则可以收集遥测数据。 在 .NET Core 得到支持的所有地方,Application Insights 监控也会得到支持。
已支持 | ASP.NET | ASP.NET Core |
---|---|---|
操作系统 | Windows操作系统 | Windows、Linux 或 Mac |
宿主方法 | 进程内(IIS 或 IIS Express) | 进程内或进程外 |
部署方法 | Web 部署、MSI 或手动文件复制 | 框架依赖或自包含 |
网页服务器 | Internet Information Services (IIS) | Internet Information Server (IIS) 或 Kestrel |
托管平台 | Azure 应用服务(Windows)、Azure 虚拟机或本地服务器 | Azure 应用服务、Azure 虚拟机、Docker 和 Azure Kubernetes 服务的 Web 应用功能 (AKS) |
.NET 版本 | .NET Framework 4.6.1 及更高版本 | 所有正式 支持的 .NET 版本 均未处于预览状态 |
IDE | Visual Studio | Visual Studio、Visual Studio Code 或命令行 |
先决条件
- Azure 订阅。 如果还没有帐户,请创建 一个免费的 Azure 帐户。
- 基于 Application Insights 工作区的资源。
- 正常运行的 Web 应用程序。 如果还没有 Web 应用,请参阅“创建基本 Web 应用”。
- 最新版本的 Visual Studio 具有以下工作负载:
- ASP.NET 和 Web 开发
- Azure 开发
创建基本 Web 应用
我们将使用一个 MVC 应用程序示例。 如果你使用的是Worker Service,请参考适用于 Worker Service 应用程序的 Application Insights中的说明。
- 打开 Visual Studio。
- 选择 “创建新项目”。
- 使用 C# 选择 ASP.NET Web 应用程序(.NET Framework),然后选择“下一步”。
- 输入 项目名称,然后选择“ 创建”。
- 选择 MVC,然后选择“ 创建”。
自动添加 Application Insights (Visual Studio)
本部分将指导你自动将 Application Insights 添加到基于模板的 Web 应用。
注意
如果要为 ASP.NET 应用程序使用独立的 ILogger 提供程序,请使用 Microsoft.Extensions.Logging.ApplicationInsight。
在 Visual Studio 的 ASP.NET Web 应用项目中:
选择“项目”“添加 Application Insights 遥测”>“Application Insights SDK(本地)”“下一步”>“完成”“关闭”。>>>
打开 ApplicationInsights.config 文件。
在闭合的
</ApplicationInsights>
标记前面,添加一行,其中包含用于 Application Insights 资源的连接字符串。 在新创建的 Application Insights 资源的“概述”窗格上,找到你的连接字符串。<ConnectionString>Copy connection string from Application Insights Resource Overview</ConnectionString>
选择“项目”“管理 NuGet 包”>“更新”。> 然后将每个
Microsoft.ApplicationInsights
NuGet 包更新到最新的稳定版本。通过选择“IIS Express”来运行应用程序。 基本 ASP.NET 应用开始运行。 浏览站点上的页面时,遥测数据被发送到 Application Insights。
手动添加 Application Insights(无 Visual Studio)
本部分将指导你手动将 Application Insights 添加到基于模板的 Web 应用。
将以下 NuGet 包及其依赖项添加到项目中:
在某些情况下,系统会自动创建 ApplicationInsights.config 文件。 如果该文件已存在,请跳到步骤 4。
如果没有此模板,请自行创建。 在 ASP.NET 应用程序的根目录中,创建名为 ApplicationInsights.config 的新文件。
将以下 XML 配置复制到新创建的文件中:
<?xml version="1.0" encoding="utf-8"?> <ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings"> <TelemetryInitializers> <Add Type="Microsoft.ApplicationInsights.DependencyCollector.HttpDependenciesParsingTelemetryInitializer, Microsoft.AI.DependencyCollector" /> <Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureRoleEnvironmentTelemetryInitializer, Microsoft.AI.WindowsServer" /> <Add Type="Microsoft.ApplicationInsights.WindowsServer.BuildInfoConfigComponentVersionTelemetryInitializer, Microsoft.AI.WindowsServer" /> <Add Type="Microsoft.ApplicationInsights.Web.WebTestTelemetryInitializer, Microsoft.AI.Web" /> <Add Type="Microsoft.ApplicationInsights.Web.SyntheticUserAgentTelemetryInitializer, Microsoft.AI.Web"> <!-- Extended list of bots: search|spider|crawl|Bot|Monitor|BrowserMob|BingPreview|PagePeeker|WebThumb|URL2PNG|ZooShot|GomezA|Google SketchUp|Read Later|KTXN|KHTE|Keynote|Pingdom|AlwaysOn|zao|borg|oegp|silk|Xenu|zeal|NING|htdig|lycos|slurp|teoma|voila|yahoo|Sogou|CiBra|Nutch|Java|JNLP|Daumoa|Genieo|ichiro|larbin|pompos|Scrapy|snappy|speedy|vortex|favicon|indexer|Riddler|scooter|scraper|scrubby|WhatWeb|WinHTTP|voyager|archiver|Icarus6j|mogimogi|Netvibes|altavista|charlotte|findlinks|Retreiver|TLSProber|WordPress|wsr-agent|http client|Python-urllib|AppEngine-Google|semanticdiscovery|facebookexternalhit|web/snippet|Google-HTTP-Java-Client--> <Filters>search|spider|crawl|Bot|Monitor|AlwaysOn</Filters> </Add> <Add Type="Microsoft.ApplicationInsights.Web.ClientIpHeaderTelemetryInitializer, Microsoft.AI.Web" /> <Add Type="Microsoft.ApplicationInsights.Web.AzureAppServiceRoleNameFromHostNameHeaderInitializer, Microsoft.AI.Web" /> <Add Type="Microsoft.ApplicationInsights.Web.OperationNameTelemetryInitializer, Microsoft.AI.Web" /> <Add Type="Microsoft.ApplicationInsights.Web.OperationCorrelationTelemetryInitializer, Microsoft.AI.Web" /> <Add Type="Microsoft.ApplicationInsights.Web.UserTelemetryInitializer, Microsoft.AI.Web" /> <Add Type="Microsoft.ApplicationInsights.Web.AuthenticatedUserIdTelemetryInitializer, Microsoft.AI.Web" /> <Add Type="Microsoft.ApplicationInsights.Web.AccountIdTelemetryInitializer, Microsoft.AI.Web" /> <Add Type="Microsoft.ApplicationInsights.Web.SessionTelemetryInitializer, Microsoft.AI.Web" /> </TelemetryInitializers> <TelemetryModules> <Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector"> <ExcludeComponentCorrelationHttpHeadersOnDomains> <!-- Requests to the following hostnames will not be modified by adding correlation headers. Add entries here to exclude additional hostnames. NOTE: this configuration will be lost upon NuGet upgrade. --> <Add>core.windows.net</Add> <Add>core.chinacloudapi.cn</Add> <Add>core.cloudapi.de</Add> <Add>core.usgovcloudapi.net</Add> </ExcludeComponentCorrelationHttpHeadersOnDomains> <IncludeDiagnosticSourceActivities> <Add>Microsoft.Azure.EventHubs</Add> <Add>Azure.Messaging.ServiceBus</Add> </IncludeDiagnosticSourceActivities> </Add> <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule, Microsoft.AI.PerfCounterCollector"> <!-- Use the following syntax here to collect additional performance counters: <Counters> <Add PerformanceCounter="\Process(??APP_WIN32_PROC??)\Handle Count" ReportAs="Process handle count" /> ... </Counters> PerformanceCounter must be either \CategoryName(InstanceName)\CounterName or \CategoryName\CounterName NOTE: performance counters configuration will be lost upon NuGet upgrade. The following placeholders are supported as InstanceName: ??APP_WIN32_PROC?? - instance name of the application process for Win32 counters. ??APP_W3SVC_PROC?? - instance name of the application IIS worker process for IIS/ASP.NET counters. ??APP_CLR_PROC?? - instance name of the application CLR process for .NET counters. --> </Add> <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryModule, Microsoft.AI.PerfCounterCollector" /> <Add Type="Microsoft.ApplicationInsights.WindowsServer.AppServicesHeartbeatTelemetryModule, Microsoft.AI.WindowsServer" /> <Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureInstanceMetadataTelemetryModule, Microsoft.AI.WindowsServer"> <!-- Remove individual fields collected here by adding them to the ApplicationInsighs.HeartbeatProvider with the following syntax: <Add Type="Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.DiagnosticsTelemetryModule, Microsoft.ApplicationInsights"> <ExcludedHeartbeatProperties> <Add>osType</Add> <Add>location</Add> <Add>name</Add> <Add>offer</Add> <Add>platformFaultDomain</Add> <Add>platformUpdateDomain</Add> <Add>publisher</Add> <Add>sku</Add> <Add>version</Add> <Add>vmId</Add> <Add>vmSize</Add> <Add>subscriptionId</Add> <Add>resourceGroupName</Add> <Add>placementGroupId</Add> <Add>tags</Add> <Add>vmScaleSetName</Add> </ExcludedHeartbeatProperties> </Add> NOTE: exclusions will be lost upon upgrade. --> </Add> <Add Type="Microsoft.ApplicationInsights.WindowsServer.DeveloperModeWithDebuggerAttachedTelemetryModule, Microsoft.AI.WindowsServer" /> <Add Type="Microsoft.ApplicationInsights.WindowsServer.UnhandledExceptionTelemetryModule, Microsoft.AI.WindowsServer" /> <Add Type="Microsoft.ApplicationInsights.WindowsServer.UnobservedExceptionTelemetryModule, Microsoft.AI.WindowsServer"> <!--</Add> <Add Type="Microsoft.ApplicationInsights.WindowsServer.FirstChanceExceptionStatisticsTelemetryModule, Microsoft.AI.WindowsServer">--> </Add> <Add Type="Microsoft.ApplicationInsights.Web.RequestTrackingTelemetryModule, Microsoft.AI.Web"> <Handlers> <!-- Add entries here to filter out additional handlers: NOTE: handler configuration will be lost upon NuGet upgrade. --> <Add>Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.RequestDataHttpHandler</Add> <Add>System.Web.StaticFileHandler</Add> <Add>System.Web.Handlers.AssemblyResourceLoader</Add> <Add>System.Web.Optimization.BundleHandler</Add> <Add>System.Web.Script.Services.ScriptHandlerFactory</Add> <Add>System.Web.Handlers.TraceHandler</Add> <Add>System.Web.Services.Discovery.DiscoveryRequestHandler</Add> <Add>System.Web.HttpDebugHandler</Add> </Handlers> </Add> <Add Type="Microsoft.ApplicationInsights.Web.ExceptionTrackingTelemetryModule, Microsoft.AI.Web" /> <Add Type="Microsoft.ApplicationInsights.Web.AspNetDiagnosticTelemetryModule, Microsoft.AI.Web" /> </TelemetryModules> <ApplicationIdProvider Type="Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId.ApplicationInsightsApplicationIdProvider, Microsoft.ApplicationInsights" /> <TelemetrySinks> <Add Name="default"> <TelemetryProcessors> <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryProcessor, Microsoft.AI.PerfCounterCollector" /> <Add Type="Microsoft.ApplicationInsights.Extensibility.AutocollectedMetricsExtractor, Microsoft.ApplicationInsights" /> <Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel"> <MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond> <ExcludedTypes>Event</ExcludedTypes> </Add> <Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel"> <MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond> <IncludedTypes>Event</IncludedTypes> </Add> <!-- Adjust the include and exclude examples to specify the desired semicolon-delimited types. (Dependency, Event, Exception, PageView, Request, Trace) --> </TelemetryProcessors> <TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel" /> </Add> </TelemetrySinks> <!-- Learn more about Application Insights configuration with ApplicationInsights.config here: http://go.microsoft.com/fwlink/?LinkID=513840 --> <ConnectionString>Copy the connection string from your Application Insights resource</ConnectionString> </ApplicationInsights>
添加连接字符串,可以通过两种方式完成:
(建议)在配置中设置连接字符串。
在 ApplicationInsights.config 中结束
</ApplicationInsights>
标记之前,为 Application Insights 资源添加连接字符串。 可以在新创建的 Application Insights 资源的“概述”窗格上找到连接字符串。<ConnectionString>Copy the connection string from your Application Insights resource</ConnectionString>
在代码中设置连接字符串。
在 program.cs 类中提供连接字符串。
var configuration = new TelemetryConfiguration { ConnectionString = "Copy the connection string from your Application Insights resource" };
在项目中与 ApplicationInsights.config 文件相同的级别,创建包含名为 AiHandleErrorAttribute.cs 的新 C# 文件的文件夹,将其命名为 ErrorHandler。 该文件的内容如下所示:
using System; using System.Web.Mvc; using Microsoft.ApplicationInsights; namespace WebApplication10.ErrorHandler //namespace will vary based on your project name { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class AiHandleErrorAttribute : HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null) { //If customError is Off, then AI HTTPModule will report the exception if (filterContext.HttpContext.IsCustomErrorEnabled) { var ai = new TelemetryClient(); ai.TrackException(filterContext.Exception); } } base.OnException(filterContext); } } }
在 App_Start 文件夹中,打开 FilterConfig.cs 文件,并更改该文件以匹配示例:
using System.Web; using System.Web.Mvc; namespace WebApplication10 //Namespace will vary based on project name { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new ErrorHandler.AiHandleErrorAttribute()); } } }
如果 Web.config 已更新,请跳过此步骤。 否则,按如下所示更新文件:
<?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application, please visit https://go.microsoft.com/fwlink/?LinkId=301880 --> <configuration> <appSettings> <add key="webpages:Version" value="3.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings> <system.web> <compilation debug="true" targetFramework="4.7.2" /> <httpRuntime targetFramework="4.7.2" /> <!-- Code added for Application Insights start --> <httpModules> <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" /> <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" /> </httpModules> <!-- Code added for Application Insights end --> </system.web> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" /> <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" /> <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-5.2.7.0" newVersion="5.2.7.0" /> </dependentAssembly> <!-- Code added for Application Insights start --> <dependentAssembly> <assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-4.0.1.1" newVersion="4.0.1.1" /> </dependentAssembly> <!-- Code added for Application Insights end --> </assemblyBinding> </runtime> <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" /> <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" /> </compilers> </system.codedom> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <!-- Code added for Application Insights start --> <modules> <remove name="TelemetryCorrelationHttpModule" /> <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="managedHandler" /> <remove name="ApplicationInsightsWebTracking" /> <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" /> </modules> <!-- Code added for Application Insights end --> </system.webServer> </configuration>
现在已成功配置服务器端应用程序监视。 如果运行 Web 应用,你将会看到遥测数据开始出现在 Application Insights 中。
运行应用程序
运行应用程序并向其发出请求。 现在,遥测数据应会流入 Application Insights。 Application Insights SDK 会自动收集应用程序的传入 Web 请求及其相关遥测数据。
实时指标
实时指标可用于快速验证是否正确配置了使用 Application Insights 的应用程序监视。 遥测数据可能需要几分钟才能出现在 Azure 门户中,但实时指标窗格会近乎实时地显示正在运行的进程的 CPU 使用情况。 它还可以显示其他遥测,例如请求、依赖项和跟踪。
注意
按照建议用于 .NET 应用程序的说明加入实时指标时,将会默认启用它。
使用代码为任何 .NET 应用程序启用实时指标
若要手动配置实时指标,请执行以下操作:
安装 NuGet 包 Microsoft.ApplicationInsights.PerfCounterCollector。
以下示例控制台应用代码显示了如何设置实时指标:
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse;
using System;
using System.Threading.Tasks;
namespace LiveMetricsDemo
{
class Program
{
static void Main(string[] args)
{
// Create a TelemetryConfiguration instance.
TelemetryConfiguration config = TelemetryConfiguration.CreateDefault();
config.InstrumentationKey = "INSTRUMENTATION-KEY-HERE";
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();
}
}
}
}
ILogger 日志
默认配置收集 ILogger
Warning
日志和严重性级别更高的日志。 有关详细信息,请参阅如何自定义 ILogger 日志收集?。
依赖关系
自动跟踪的依赖项
适用于 .NET 和 .NET Core 的 Application Insights SDK 随附了 DependencyTrackingTelemetryModule
:一个自动收集依赖项的遥测模块。 该模块 DependencyTrackingTelemetryModule
作为 Microsoft.ApplicationInsights.DependencyCollector NuGet 包提供,并在使用 Microsoft.ApplicationInsights.Web
NuGet 包或 Microsoft.ApplicationInsights.AspNetCore
NuGet 包时自动引入。
DependencyTrackingTelemetryModule
目前自动跟踪以下依赖项:
依赖关系 | 详细信息 |
---|---|
HTTP/HTTPS | 本地或远程 HTTP/HTTPS 调用。 |
WCF 调用 | 仅当使用基于 HTTP 的绑定时,才会自动跟踪。 |
SQL | 使用 SqlClient 发出的调用。 有关如何捕获 SQL 查询,请参阅使用高级 SQL 跟踪获取完整的 SQL 查询。 |
Azure Blob 存储、表存储或队列存储 | 使用 Azure 存储客户端发出的调用。 |
Azure 事件中心客户端 SDK | 使用最新的包:https://nuget.org/packages/Azure.Messaging.EventHubs。 |
Azure 服务总线客户端 SDK | 使用最新的包:https://nuget.org/packages/Azure.Messaging.ServiceBus。 |
Azure Cosmos DB | 使用 HTTP/HTTPS 时会自动跟踪。 使用 TCP 直接模式的操作的跟踪将使用预览包 >= 3.33.0-preview 进行自动捕获。 有关更多详细信息,请访问文档。 |
如果依赖项不是自动收集的,可以通过跟踪依赖项调用手动跟踪它。
有关依赖项跟踪工作原理的详细信息,请参阅 Application Insights 中的依赖项跟踪。
在控制台应用中设置自动依赖项跟踪
若要从 .NET 控制台应用自动跟踪依赖项,请安装 NuGet 包 Microsoft.ApplicationInsights.DependencyCollector
并初始化 DependencyTrackingTelemetryModule
:
DependencyTrackingTelemetryModule depModule = new DependencyTrackingTelemetryModule();
depModule.Initialize(TelemetryConfiguration.Active);
手动跟踪依赖项
下面是不自动收集的依赖项示例,需要手动跟踪它们:
- 仅当使用 HTTP/HTTPS 时,才会自动跟踪 Azure Cosmos DB。 对于早于
2.22.0-Beta1
的 SDK 版本,Application Insights 不会自动捕获 TCP 模式。 - Redis
对于 SDK 不会自动收集的依赖项,可以通过标准自动收集模块使用的 TrackDependency API 手动跟踪它们。
示例
如果使用不是由你自行编写的程序集来生成代码,可对其所有调用进行计时。 这使你能够了解它对响应时间所做的贡献。
若要使此数据显示在 Application Insights 中的依赖项图表中,请使用 TrackDependency
发送此数据:
var startTime = DateTime.UtcNow;
var timer = System.Diagnostics.Stopwatch.StartNew();
try
{
// making dependency call
success = dependency.Call();
}
finally
{
timer.Stop();
telemetryClient.TrackDependency("myDependencyType", "myDependencyCall", "myDependencyData", startTime, timer.Elapsed, success);
}
或者,可以使用 TelemetryClient
提供的扩展方法 StartOperation
和 StopOperation
来手动跟踪依赖项,如传出的依赖项跟踪中所示。
禁用标准依赖项跟踪模块
使用高级 SQL 跟踪获取完整的 SQL 查询
对于 SQL 调用,始终会收集服务器和数据库的名称,并将其存储为收集的 DependencyTelemetry
的名称。 另一个名为 data 的字段可以包含完整的 SQL 查询文本。
注意
Azure Functions 需要使用单独的设置来启用 SQL 文本收集。 有关详细信息,请参阅启用 SQL 查询收集。
对于 ASP.NET 应用程序,完整 SQL 查询文本是在字节代码检测的帮助下收集的,这需要使用检测引擎,或者使用 Microsoft.Data.SqlClient NuGet 包而不是 System.Data.SqlClient 库。 下表描述了用于启用完整 SQL 查询收集的平台特定步骤。
平台 | 获取完整 SQL 查询所要执行的步骤 |
---|---|
Azure 应用服务中的 Web 应用 | 在 Web 应用控制面板中,打开“Application Insights”窗格并启用“.NET”下的“SQL 命令”。 |
IIS 服务器(Azure 虚拟机、本地计算机等) | 使用 Microsoft.Data.SqlClient NuGet 包或使用 Application Insights 代理 PowerShell 模块安装检测引擎并重启 IIS。 |
Azure 云服务 | 添加启动任务以安装 StatusMonitor。 应用应在生成时加入 ApplicationInsights SDK,方法是安装适用于 ASP.NET 或 ASP.NET Core 应用程序的 NuGet 包。 |
IIS Express | 使用 Microsoft.Data.SqlClient NuGet 包。 |
Azure 应用服务中的 WebJobs | 使用 Microsoft.Data.SqlClient NuGet 包。 |
除了上述平台特定的步骤之外,还必须通过以下代码修改 文件来显式选择启用 SQL 命令集合:
<TelemetryModules>
<Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector">
<EnableSqlCommandTextInstrumentation>true</EnableSqlCommandTextInstrumentation>
</Add>
在上述情况下,验证是否已正确安装该检测引擎的适当方法是验证收集的 DependencyTelemetry
的 SDK 版本是否为 rddp
。 使用 rdddsd
或 rddf
表示依赖项是通过 DiagnosticSource
或 EventSource
回调收集的,因此不会捕获完整的 SQL 查询。
性能计数器
ASP.NET 完全支持性能计数器,而 ASP.NET Core 提供有限的支持,具体取决于 SDK 版本和托管环境。 有关详细信息,请参阅 Application Insights 中的 .NET 计数器。
事件计数器
Application Insights 支持收集包含其 EventCounterCollectionModule
的 EventCounters,ASP.NET Core 默认启用此项。 若要了解如何配置要收集的计数器列表,请参阅 Application Insights 中的 .NET 计数器。
通过 HTTP 扩充数据
var requestTelemetry = HttpContext.Current?.Items["Microsoft.ApplicationInsights.RequestTelemetry"] as RequestTelemetry;
if (requestTelemetry != null)
{
requestTelemetry.Properties["myProp"] = "someData";
}
配置 Application Insights SDK
可以自定义 application Insights SDK for ASP.NET 和 ASP.NET Core 以更改默认配置。
若要了解如何为 ASP.NET 应用程序配置 Application Insights SDK,请参阅使用 ApplicationInsights.config 或 .xml配置 Application Insights SDK 。
采样
若要了解如何为 ASP.NET 应用程序配置采样,请参阅 Application Insights 中的采样。
遥测初始化表达式
若要使用其他信息来扩充遥测数据,或替代标准遥测模块设置的遥测属性,请使用遥测初始值设定项。
若要了解如何在 ASP.NET 应用程序中使用遥测初始化器,请参阅 在 Application Insights SDK 中筛选和预处理遥测数据。
遥测处理器
若要了解如何将遥测处理器用于 ASP.NET 应用程序,请参阅 Application Insights SDK 中的筛选器和预处理遥测。
配置或删除默认遥测模块
Application Insights 自动收集有关特定工作负荷的遥测数据,无需用户手动跟踪。
默认情况下,启用以下自动收集模块。 这些模块负责自动收集遥测数据。 可以禁用或配置这些模块,以改变其默认行为。
-
RequestTrackingTelemetryModule
:从传入 Web 请求收集 RequestTelemetry。 -
DependencyTrackingTelemetryModule
:收集来自传出 HTTP 调用和 SQL 调用的 DependencyTelemetry。 -
PerformanceCollectorModule
:收集 Windows PerformanceCounter。 -
QuickPulseTelemetryModule
:收集遥测数据以显示在实时指标窗格中。 -
AppServicesHeartbeatTelemetryModule
:收集有关托管应用程序的应用服务环境的检测信号(以自定义指标的形式发送)。 -
AzureInstanceMetadataTelemetryModule
:收集有关托管应用程序的 Azure VM 环境的检测信号(以自定义指标的形式发送)。 -
EventCounterCollectionModule
:收集 EventCounter。 此模块是一项新功能,可在 SDK 2.8.0 及更高版本中使用。
若要了解如何为 ASP.NET 应用程序配置或删除遥测模块,请参阅 使用 ApplicationInsights.config 或 .xml配置 Application Insights SDK 。
添加客户端监控
前面几个部分提供了有关自动和手动配置服务器端监视的方法的指导。 若要添加客户端监视,请使用客户端 JavaScript SDK。 可以通过在页面 HTML 的结尾 标记之前添加 </head>
来监视任何网页的客户端事务。
尽管可以手动将 JavaScript (Web) SDK 加载程序脚本添加到每个 HTML 页的标头,但建议改为将 JavaScript (Web) SDK 加载程序脚本添加到主页面。 该操作会将 JavaScript (Web) SDK 加载程序脚本注入站点的所有页面。
对于本文中基于模板的 ASP.NET MVC 应用,需要编辑的文件为 _Layout.cshtml。 可以在视图>共享下找到。 若要添加客户端监视,请打开 _Layout.cshtml,然后按照关于客户端 JavaScript SDK 配置的文章中的基于 JavaScript (Web) SDK 加载程序脚本的设置说明进行操作。
故障排除
请参阅专用疑难解答文章。
Visual Studio 2019 中存在一个已知问题:将检测密钥或连接字符串存储在用户机密中这项操作对基于 .NET Framework 的应用无效。 密钥最终必须硬编码到 applicationinsights.config 文件中,以修复此 bug。 本文旨在通过不使用用户密码来完全避免此问题。
测试应用程序主机与引入服务之间的连接性
Application Insights SDK 和代理会发送遥测,以将其作为 REST 调用引入到终结点。 可以使用原始 REST 客户端通过 PowerShell 或使用 curl 命令,测试从 Web 服务器或应用程序主机计算机到引入服务终结点的连接。 请参阅排查 Azure Monitor Application Insights 中缺少应用程序遥测数据的问题。
开源 SDK
有关最新的更新和 bug 修复,请参阅发行说明。
发行说明
对于 2.12 及更高版本:包含 ASP.NET、ASP.NET Core 和日志适配器的 .NET 软件开发工具包 (SDK)
我们的服务更新还总结了 Application Insights 的主要改进。
后续步骤
- 验证是否正在运行受支持的 Application Insights SDK 版本 。
- 添加模拟事务,以通过可用性监视测试你的网站是否能从世界各地进行访问。
- 配置采样以帮助降低遥测数据流量和数据存储费用。
- 浏览用户流,了解用户如何在应用中移动。
- 配置快照收集,以便在引发异常时查看源代码和变量的状态。
- 使用 API 发送自己的事件和指标,以获取应用性能和使用情况的详细视图。
- 若要查看常见问题解答(常见问题解答),请参阅 Application Insights for ASP.NET FAQ。