注意
我们建议新应用程序或客户使用 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 可以从应用收集以下遥测数据:
- 请求
- 依赖关系
- 例外
- 性能计数器
- 跟踪(日志)
- 心跳
- 自定义事件和指标 (需要手动检测)
- 页面视图 (需要用于网页的 JavaScript SDK)
- 可用性测试 (需要手动设置可用性测试)
支持的方案
注意
无论在何处以何种方式运行你的应用程序,适用于 ASP.NET Core 的 Application Insights SDK 都可对其进行监视。 如果应用程序正在运行并与 Azure 建立了网络连接,则可以收集遥测数据。 在 .NET Core 得到支持的所有地方,Application Insights 监控也会得到支持。
已支持 | ASP.NET | ASP.NET Core |
---|---|---|
操作系统 | Windows操作系统 | Windows、Linux 或 macOS |
宿主方法 | 进程内 (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 或命令行 |
添加 Application Insights
先决条件
- 一份 Azure 订阅。 如果还没有帐户,请创建 一个 Azure 帐户。
- 基于 Application Insights 工作区的资源。
- 正常运行的 Web 应用程序。 如果还没有 Web 应用,请参阅“创建基本 Web 应用”。
- 最新版的 Visual Studio 具有以下工作负载:
- ASP.NET 和 Web 开发
- Azure 开发
创建基本 Web 应用
如果还没有正常运行的 Web 应用程序,可以使用以下指南创建一个。
注意
我们将使用一个 MVC 应用程序示例。 如果你使用的是Worker Service,请参考适用于 Worker Service 应用程序的 Application Insights中的说明。
- 打开 Visual Studio。
- 选择 “创建新项目”。
- 使用 C# 选择 ASP.NET Web 应用程序(.NET Framework),然后选择“下一步”。
- 输入 项目名称,然后选择“ 创建”。
- 选择 MVC,然后选择“ 创建”。
自动添加 Application Insights (Visual Studio)
本部分将指导你自动将 Application Insights 添加到基于模板的 Web 应用。
在 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.chinacloudapi.cn</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>
中结束的 标记前面,为 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。 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();
}
}
}
}
跟踪(日志)
Application Insights 通过 ILogger 从 ASP.NET Core 和其他 .NET 应用捕获日志,并通过经典 SDK 和适配器从经典 ASP.NET (.NET Framework) 捕获日志。
小窍门
默认情况下,Application Insights 提供程序仅发送严重性为
Warning
或更高级别的日志。 若要包括Information
或更低级别的日志,请在appsettings.json
中更新日志级别设置。Microsoft.ApplicationInsights.WorkerService
NuGet 包(用于为后台服务启用 Application Insights)超出范围。 有关详细信息,请参阅 适用于辅助角色服务应用的 Application Insights。
注意
若要查看常见问题解答 (FAQ),请参阅 .NET 日志记录常见问题解答。
ILogger 指南不适用于 ASP.NET。 若要将跟踪日志从经典 ASP.NET 应用发送到 Application Insights,请使用受支持的适配器,例如:
- 带有 Application Insights TraceListener 的 System.Diagnostics.Trace
- 具有官方 Application Insights 目标的 log4net 或 NLog
有关详细步骤和配置示例,请参阅将跟踪日志发送到 Application Insights。
控制台应用程序
要将 Application Insights 日志记录添加到控制台应用程序,请先安装以下 NuGet 包:
以下示例使用了 Microsoft.Extensions.Logging.ApplicationInsights
包并演示了控制台应用程序的默认行为。
Microsoft.Extensions.Logging.ApplicationInsights
包应该在控制台应用程序中使用,或者在你只需要 Application Insights 的最小实现而不需要完整功能集(例如指标、分布式跟踪、采样和遥测初始化表达式)时使用。
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using var channel = new InMemoryChannel();
try
{
IServiceCollection services = new ServiceCollection();
services.Configure<TelemetryConfiguration>(config => config.TelemetryChannel = channel);
services.AddLogging(builder =>
{
// Only Application Insights is registered as a logger provider
builder.AddApplicationInsights(
configureTelemetryConfiguration: (config) => config.ConnectionString = "<YourConnectionString>",
configureApplicationInsightsLoggerOptions: (options) => { }
);
});
IServiceProvider serviceProvider = services.BuildServiceProvider();
ILogger<Program> logger = serviceProvider.GetRequiredService<ILogger<Program>>();
logger.LogInformation("Logger is working...");
}
finally
{
// Explicitly call Flush() followed by Delay, as required in console apps.
// This ensures that even if the application terminates, telemetry is sent to the back end.
channel.Flush();
await Task.Delay(TimeSpan.FromMilliseconds(1000));
}
有关详细信息,请参阅将从 ILogger 日志生成哪种类型的 Application Insights 遥测数据?可以在何处查看 Application Insights 中的 ILogger 日志?。
日志记录范围
注意
以下指南适用于 ILogger 方案(仅适用于 ASP.NET Core 和控制台)。 它不适用于经典 ASP.NET。
ApplicationInsightsLoggingProvider
支持日志范围(默认启用)。
如果范围的类型为 IReadOnlyCollection<KeyValuePair<string,object>>
,则集合中的每个键值对都将作为自定义属性添加到 Application Insights 遥测中。 在下面的示例中,日志被捕获为 TraceTelemetry
并且在属性中具有 ("MyKey", "MyValue")
。
using (_logger.BeginScope(new Dictionary<string, object> { ["MyKey"] = "MyValue" }))
{
_logger.LogError("An example of an Error level message");
}
如果使用任何其他类型作为范围,它将存储在 Application Insights 遥测中的 Scope
属性下。 在下面的示例中,TraceTelemetry
具有包含该范围且名为 Scope
的属性。
using (_logger.BeginScope("hello scope"))
{
_logger.LogError("An example of an Error level message");
}
查找日志
ILogger 日志显示为跟踪遥测(Application Insights 中的 traces
表和 Log Analytics 中的 AppTraces
)。
示例
在 Azure 门户中,转到 Application Insights 并运行:
traces
| where severityLevel >= 2 // 2=Warning, 1=Information, 0=Verbose
| take 50
依赖关系
自动跟踪的依赖项
适用于 .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。 Application Insights 不会自动捕获低于
2.22.0-Beta1
的 SDK 版本的 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 命令集合applicationInsights.config
:
<TelemetryModules>
<Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector">
<EnableSqlCommandTextInstrumentation>true</EnableSqlCommandTextInstrumentation>
</Add>
在上述情况下,验证是否已正确安装该检测引擎的适当方法是验证收集的 DependencyTelemetry
的 SDK 版本是否为 rddp
。 使用 rdddsd
或 rddf
将指示通过 DiagnosticSource
或 EventSource
回调收集依赖项,因此不会捕获完整的 SQL 查询。
例外
可以使用 Application Insights 来报告 Web 应用程序中的异常。 可将失败的请求与客户端和服务器上的异常和其他事件相关联,以便快速诊断原因。 本部分介绍了如何设置异常报告,显式报告异常,诊断故障,等等。
设置异常报告
可以设置 Application Insights 以报告服务器或客户端中发生的异常。 根据应用程序所依赖的平台,你需要相应的扩展或 SDK。
要从服务器端应用程序报告异常,请考虑以下方案:
- 为 Azure Web 应用添加 Application Insights 扩展。
- 为 Azure 虚拟机规模集和 Azure 虚拟机规模集 IIS 托管的应用添加应用程序监视扩展。
- 在应用代码中添加 Application Insights SDK,为 IIS Web 服务器运行 Application Insights 代理,或为 Java Web 应用启用 Java 代理。
重要
本部分侧重于 .NET Framework 应用,并从代码示例的角度进行讲解。 用于 .NET Framework 的某些方法在 .NET Core SDK 中已过时。
诊断失败和异常
- Azure 门户
- Visual Studio
Application Insights 随附了特选的应用程序性能管理体验,可帮助你诊断受监视应用程序中发生的故障。
有关详细说明,请参阅使用 Application Insights 调查故障、性能和事务。
自定义跟踪和日志数据
要获取特定于应用的诊断数据,可插入代码以发送自己的遥测数据。 自定义遥测或日志数据与请求、页面视图和其他自动收集的数据一起显示在诊断搜索中。
使用 <xref:Microsoft.VisualStudio.ApplicationInsights.TelemetryClient?displayProperty=fullName> 时,可以使用多个 API:
- <xref:Microsoft.VisualStudio.ApplicationInsights.TelemetryClient.TrackEvent%2A?displayProperty=nameWithType> 通常用于监视使用模式,但它发送的数据还显示在诊断搜索的“自定义事件”下。 事件可以进行命名,并可以带有在筛选诊断搜索时可依据的字符串属性和数值指标。
- <xref:Microsoft.VisualStudio.ApplicationInsights.TelemetryClient.TrackTrace%2A?displayProperty=nameWithType> 支持发送较长的数据,例如 POST 信息。
- <xref:Microsoft.VisualStudio.ApplicationInsights.TelemetryClient.TrackException%2A?displayProperty=nameWithType> 向 Application Insights 发送异常详细信息,例如堆栈跟踪。
要查看这些事件,请在左侧菜单中打开“搜索”。 选择下拉菜单“事件类型”,然后选择“自定义事件”、“跟踪”或“异常”。
注意
如果你的应用生成大量遥测数据,则自适应采样模块仅发送一小部分事件,从而自动减少发送到门户的数据量。 属于同一操作的事件会作为一个组被选中或取消选中,以便你在相关事件之间进行导航。 有关详细信息,请参阅 Application Insights 中的采样。
查看请求 POST 数据
请求详细信息不包含在 POST 调用中发送到应用的数据。 若要报告此数据:
- 向你的应用代码添加 Application Insights SDK。
- 在应用程序中插入代码以调用 Microsoft.ApplicationInsights.TrackTrace()。 在消息参数中发送 POST 数据。 允许的大小有限制,因此,应该尝试仅发送必要数据。
- 调查失败的请求时,请查找关联的跟踪。
捕获异常和相关的诊断数据
默认情况下,并不是所有导致应用失败的异常都会显示在门户中。 如果在网页中使用 JavaScript SDK,则会看到浏览器异常。 但是,大多数服务器端异常由 IIS 截获,因此你需要添加一些代码来捕获和报告它们。
您可以:
- 通过在异常处理程序中插入代码来显式记录异常,从而报告这些异常。
- 通过配置 ASP.NET 框架自动捕获异常。 框架类型不同,必要的附加内容也不同。
显式报告异常
最简单的报告方法是在异常处理程序中插入对 trackException()
的调用。
var telemetry = new TelemetryClient();
try
{
// ...
}
catch (Exception ex)
{
var properties = new Dictionary<string, string>
{
["Game"] = currentGame.Name
};
var measurements = new Dictionary<string, double>
{
["Users"] = currentGame.Users.Count
};
// Send the exception telemetry:
telemetry.TrackException(ex, properties, measurements);
}
属性和测量参数是可选的,但对筛选和添加额外信息很有用。 例如,如果有一个可运行多个游戏的应用,可查找与特定游戏相关的所有异常报表。 可向每个字典添加任意数量的项。
浏览器异常
报告大多数浏览器异常。
如果网页包括来自内容分发网络或其他域的脚本文件,请确保脚本标记具有属性 crossorigin="anonymous"
,并且服务器可发送 CORS 头。 通过此行为,你可以从这些资源获取未经处理的 JavaScript 异常的堆栈跟踪和详细信息。
重用遥测客户端
注意
建议实例化 TelemetryClient
一次,并在应用程序的整个生命周期内重用它。
使用 .NET 中的依赖项注入 (DI)、相应的 .NET SDK 并为 DI 正确配置了 Application Insights 时,可以要求将 <xref:Microsoft.VisualStudio.ApplicationInsights.TelemetryClient> 用作构造函数参数。
public class ExampleController : ApiController
{
private readonly TelemetryClient _telemetryClient;
public ExampleController(TelemetryClient telemetryClient)
{
_telemetryClient = telemetryClient;
}
}
在上面的示例中,TelemetryClient
将注入到 ExampleController
类中。
Web 窗体
对于 Web 窗体,没有为重定向配置 CustomErrors
时,HTTP 模块能够收集这些异常。 但是,如果有活动重定向,请在 Global.asax.cs 中将以下行添加到 Application_Error
函数。
void Application_Error(object sender, EventArgs e)
{
if (HttpContext.Current.IsCustomErrorEnabled &&
Server.GetLastError () != null)
{
_telemetryClient.TrackException(Server.GetLastError());
}
}
在上面的示例中,_telemetryClient
是 <xref:Microsoft.VisualStudio.ApplicationInsights.TelemetryClient> 类型的类范围的变量。
MVC
从 Application Insights Web SDK 2.6 版(beta3 及更高版本)开始,Application Insights 会自动收集 MVC 5+ 控制器方法中引发的未经处理异常。 如果你以前添加了自定义处理程序来跟踪此类异常,则可以将其移除,以防止对异常进行双重跟踪。
在某些情况下,当引发异常时,异常筛选器无法正确处理错误:
- 从控制器构造函数引发异常时
- 从消息处理程序引发异常时
- 在路由期间引发异常时
- 在响应内容序列化期间引发异常时
- 在应用程序启动期间引发异常时
- 在后台任务中引发异常时
仍需要手动跟踪应用程序处理的所有异常。 源自控制器的未经处理异常通常会导致 500“内部服务器错误”响应。 如果此类响应是由于已处理的异常或根本没有任何异常而手动构造的,则它是通过 ResultCode
500 在相应请求遥测数据中进行跟踪的。 但是,Application Insights SDK 无法跟踪相应异常。
以前版本支持
如果使用 Application Insights Web SDK 2.5(及更低版本)的 MVC 4(及更低版本),请参照以下示例跟踪异常。
展开可查看早期版本的说明
如果 CustomErrors 配置是 Off
,则异常可供 HTTP 模块收集。 但是,如果它设置为 RemoteOnly
(默认值)或 On
,则异常会被清除,不可供 Application Insights 自动收集。 可通过替代 System.Web.Mvc.HandleErrorAttribute 类和应用该被替代类来修复该行为,如以下针对不同 MVC 版本的方式所示(请参阅 GitHub 源):
using System;
using System.Web.Mvc;
using Microsoft.ApplicationInsights;
namespace MVC2App.Controllers
{
[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)
{
//The attribute should track exceptions only when CustomErrors setting is On
//if CustomErrors is Off, exceptions will be caught by AI HTTP Module
if (filterContext.HttpContext.IsCustomErrorEnabled)
{ //Or reuse instance (recommended!). See note above.
var ai = new TelemetryClient();
ai.TrackException(filterContext.Exception);
}
}
base.OnException(filterContext);
}
}
}
MVC 2
在控制器中将 HandleError 属性替换为新属性:
namespace MVC2App.Controllers
{
[AiHandleError]
public class HomeController : Controller
{
// Omitted for brevity
}
}
MVC 3
将 AiHandleErrorAttribute
注册为 Global.asax.cs 中的全局筛选器:
public class MyMvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new AiHandleErrorAttribute());
}
}
MVC 4、MVC 5
将 AiHandleErrorAttribute
注册为 FilterConfig.cs 中的全局筛选器:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
// Default replaced with the override to track unhandled exceptions
filters.Add(new AiHandleErrorAttribute());
}
}
网络应用程序接口
从 Application Insights Web SDK 2.6 版(beta3 及更高版本)开始,Application Insights 会自动收集 Web API 2+ 控制器方法中引发的未经处理异常。 如果你之前添加了自定义处理程序来跟踪此类异常,如以下示例中所述,则可以将其移除,以防止对异常进行双重跟踪。
存在一些无法处理异常筛选器的情况。 例如:
- 从控制器构造函数引发的异常。
- 从消息处理程序引发的异常。
- 在路由过程中引发的异常。
- 在响应内容序列化期间引发的异常。
- 在应用程序启动过程中引发的异常。
- 在后台任务中引发的异常。
仍需要手动跟踪应用程序处理的所有异常。 源自控制器的未经处理异常通常会导致 500“内部服务器错误”响应。 如果此类响应是由于已处理的异常或根本没有任何异常而手动构造的,则它是通过 ResultCode
500 在相应请求遥测数据中进行跟踪的。 但是,Application Insights SDK 无法跟踪相应异常。
以前版本支持
如果使用 Application Insights Web SDK 2.5(及更低版本)的 Web API 1(及更低版本),请参阅以下示例以跟踪异常。
展开可查看早期版本的说明
Web API 1.x
替代 System.Web.Http.Filters.ExceptionFilterAttribute
:
using System.Web.Http.Filters;
using Microsoft.ApplicationInsights;
namespace WebAPI.App_Start
{
public class AiExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext != null && actionExecutedContext.Exception != null)
{ //Or reuse instance (recommended!). See note above.
var ai = new TelemetryClient();
ai.TrackException(actionExecutedContext.Exception);
}
base.OnException(actionExecutedContext);
}
}
}
可将此被替代属性添加到特定控制器,或者将其添加到 WebApiConfig
类中的全局筛选器配置:
using System.Web.Http;
using WebApi1.x.App_Start;
namespace WebApi1.x
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
// ...
config.EnableSystemDiagnosticsTracing();
// Capture exceptions for Application Insights:
config.Filters.Add(new AiExceptionFilterAttribute());
}
}
}
Web API 2.x
添加 IExceptionLogger
的实现:
using System.Web.Http.ExceptionHandling;
using Microsoft.ApplicationInsights;
namespace ProductsAppPureWebAPI.App_Start
{
public class AiExceptionLogger : ExceptionLogger
{
public override void Log(ExceptionLoggerContext context)
{
if (context != null && context.Exception != null)
{
//or reuse instance (recommended!). see note above
var ai = new TelemetryClient();
ai.TrackException(context.Exception);
}
base.Log(context);
}
}
}
将此代码片段添加到 WebApiConfig
中的服务:
using System.Web.Http;
using System.Web.Http.ExceptionHandling;
using ProductsAppPureWebAPI.App_Start;
namespace WebApi2WithMVC
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
config.Services.Add(typeof(IExceptionLogger), new AiExceptionLogger());
}
}
}
作为替代方法,可以:
- 仅将
ExceptionHandler
实例替换为IExceptionHandler
的自定义实现。 此异常处理程序仅在框架仍能够选择要发送哪个响应消息时(而不是在终止了连接等情况下)调用。 - 使用异常筛选器(如上述有关 Web API 1.x 控制器的部分中所述),这些筛选器并非在所有情况下都调用。
WCF
添加一个用来扩展 Attribute
并实现 IErrorHandler
和 IServiceBehavior
的类。
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Web;
using Microsoft.ApplicationInsights;
namespace WcfService4.ErrorHandling
{
public class AiLogExceptionAttribute : Attribute, IErrorHandler, IServiceBehavior
{
public void AddBindingParameters(ServiceDescription serviceDescription,
System.ServiceModel.ServiceHostBase serviceHostBase,
System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints,
System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription,
System.ServiceModel.ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcher disp in serviceHostBase.ChannelDispatchers)
{
disp.ErrorHandlers.Add(this);
}
}
public void Validate(ServiceDescription serviceDescription,
System.ServiceModel.ServiceHostBase serviceHostBase)
{
}
bool IErrorHandler.HandleError(Exception error)
{//or reuse instance (recommended!). see note above
var ai = new TelemetryClient();
ai.TrackException(error);
return false;
}
void IErrorHandler.ProvideFault(Exception error,
System.ServiceModel.Channels.MessageVersion version,
ref System.ServiceModel.Channels.Message fault)
{
}
}
}
将属性添加到服务实现:
namespace WcfService4
{
[AiLogException]
public class Service1 : IService1
{
// Omitted for brevity
}
}
异常性能计数器
如果你在服务器上安装了 Azure Monitor Application Insights 代理,则可以获取 .NET 测量的异常率的图表。 已经处理和未经处理的 .NET 异常均会包括在内。
打开一个指标资源管理器选项卡并添加一个新图表。 在“性能计数器”下,选择“异常率”。
.NET Framework 通过对间隔中的异常数进行计数并除以间隔长度计算异常率。
此计数与 Application Insights 门户通过对 TrackException
报告计数计算得出的“异常”计数不同。 采样间隔不同,并且 SDK 不会为所有已经处理和未经处理的异常发送 TrackException
报告。
自定义指标集合
Azure Monitor Application Insights .NET 和 .NET Core SDK 有两种不同的收集自定义指标的方法:
-
TrackMetric()
方法,没有预聚合。 -
GetMetric()
方法,具有预聚合。
建议使用聚合,因此 不再是收集自定义指标的首选方法。TrackMetric()
本文介绍如何使用 GetMetric()
方法及其工作原理背后的一些基本原理。
展开可了解有关预聚合与非预聚合 API 的详细信息
TrackMetric()
方法发送表示指标的原始遥测。 为每个值发送单个遥测项效率低。
TrackMetric()
方法在性能方面的效率也较低,因为每个 TrackMetric(item)
都要经过遥测初始化表达式和处理器的完整 SDK 管道。
与 TrackMetric()
不同,GetMetric()
为你处理本地预聚合,然后仅以一分钟的固定间隔提交经过汇总的指标摘要。 如果你需要在秒级甚至毫秒级密切监视某些自定义指标,则可以这样做,同时只需要承担每分钟监视一次的存储和网络流量成本。 此行为还大大减少了发生限制的风险,因为需要为聚合指标发送的遥测项总数会大大减少。
在 Application Insights 中,通过 TrackMetric()
和 GetMetric()
收集的自定义指标不受采样限制。 对重要指标采样可能会导致围绕这些指标生成的警报变得不可靠。 通过从不采样自定义指标,通常可以确信,一旦超过警报阈值,便会触发警报。 由于没有对自定义指标进行采样,因此存在一些潜在的问题。
如果需要每秒钟跟踪一个指标的趋势,或以更细粒度的间隔进行跟踪,这可能会导致:
- 增加了数据存储成本。 向 Azure Monitor 发送的数据量会产生一定的成本。 发送的数据越多,监视的总体成本就越高。
- 网络流量或性能开销增加。 在某些情况下,此类开销可能会产生货币成本和应用程序性能成本。
- 产生引入限制风险。 当应用以短时间间隔发送速率很高的遥测时,Azure Monitor 会丢弃(“限制”)数据点。
限制是一个问题,因为它可能导致错过警报。 触发警报的情况可能在本地发生,然后由于发送的数据太多而在引入终结点被丢弃。 除非你实现了自己的本地聚合逻辑,否则不建议将 TrackMetric()
用于 .NET 和 .NET Core。 如果尝试跟踪事件在给定时间段内发生的每个实例,则可能会发现 TrackEvent()
更适合。 请记住,与自定义指标不同,自定义事件受采样限制。 即使不编写自己的本地预聚合,也可以使用 TrackMetric()
。 但如果这样做,请注意陷阱。
总之,建议使用 GetMetric()
,因为它执行预聚合、从所有 Track()
调用中累积值,并每分钟发送一次摘要/汇总。 通过发送更少的数据点,同时仍然收集所有相关信息,GetMetric()
方法可以显著降低成本和性能开销。
GetMetric 入门
在示例中,我们将使用基本的 .NET Core 3.1 辅助角色服务应用程序。 如果要复制与这些示例一起使用的测试环境,请按照 监视辅助角色服务文章中的步骤 1-6 进行作。 这些步骤会将 Application Insights 添加到基本辅助角色服务项目模板。 此概念适用于任何可以使用 SDK 的通用应用程序,包括 Web 应用和控制台应用。
发送指标
将 worker.cs
文件的内容替换为以下内容:
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.ApplicationInsights;
namespace WorkerService3
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private TelemetryClient _telemetryClient;
public Worker(ILogger<Worker> logger, TelemetryClient tc)
{
_logger = logger;
_telemetryClient = tc;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{ // The following line demonstrates usages of GetMetric API.
// Here "computersSold", a custom metric name, is being tracked with a value of 42 every second.
while (!stoppingToken.IsCancellationRequested)
{
_telemetryClient.GetMetric("ComputersSold").TrackValue(42);
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
}
运行示例代码时,你将看到 while
循环重复执行,且不会在 Visual Studio 输出窗口中发送遥测数据。 在大约 60 秒时发送了一条遥测数据,在我们的测试中看起来是这样的:
Application Insights Telemetry: {"name":"Microsoft.ApplicationInsights.Dev.00000000-0000-0000-0000-000000000000.Metric", "time":"2019-12-28T00:54:19.0000000Z",
"ikey":"00000000-0000-0000-0000-000000000000",
"tags":{"ai.application.ver":"1.0.0.0",
"ai.cloud.roleInstance":"Test-Computer-Name",
"ai.internal.sdkVersion":"m-agg2c:2.12.0-21496",
"ai.internal.nodeName":"Test-Computer-Name"},
"data":{"baseType":"MetricData",
"baseData":{"ver":2,"metrics":[{"name":"ComputersSold",
"kind":"Aggregation",
"value":1722,
"count":41,
"min":42,
"max":42,
"stdDev":0}],
"properties":{"_MS.AggregationIntervalMs":"42000",
"DeveloperMode":"true"}}}}
此单一遥测数据条目代表了 41 个不同指标测量值的聚合。 由于我们反复发送相同的值,因此标准偏差 (stDev
) 为 0
,具有相同的最大值 (max
) 和最小值 (min
)。
value
属性表示聚合的所有单个值的总和。
注意
GetMetric
方法不支持跟踪最后一个值(例如 gauge
)或跟踪直方图/分布。
如果我们在“日志(分析)”体验中检查 Application Insights 资源,此单独的遥测项将如以下屏幕截图所示。
注意
虽然原始遥测项在引入后不包含显式的总和属性/字段,但我们会为你创建一个。 在本例中,value
和 valueSum
属性都表示相同的内容。
还可以在门户的指标部分访问自定义指标遥测,作为基于日志的指标和自定义指标。 以下屏幕截图是基于日志的指标的一个示例。
用于高吞吐量使用情况的缓存指标引用
在某些情况下,可能会经常观察到指标值。 例如,每秒处理 500 个请求的高吞吐量服务可能希望为每个请求发出 20 个遥测指标。 该结果意味着每秒跟踪 10,000 个值。 在这种高吞吐量方案中,用户可能需要通过避免一些查找来帮助 SDK。
例如,上述示例对指标 ComputersSold
的句柄执行了查找操作,然后跟踪了观察到的值 42
。 相反,用户应该缓存该句柄,以进行多次跟踪调用:
//...
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// This is where the cache is stored to handle faster lookup
Metric computersSold = _telemetryClient.GetMetric("ComputersSold");
while (!stoppingToken.IsCancellationRequested)
{
computersSold.TrackValue(42);
computersSold.TrackValue(142);
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(50, stoppingToken);
}
}
除了缓存指标句柄之外,上述示例还将 Task.Delay
缩短到了 50 毫秒,这样循环将更频繁地执行, 从而导致了 772 次 TrackValue()
调用。
多维指标
上一部分中的示例显示了零维指标。 指标也可以是多维指标。 我们目前最多支持 10 个维度。
下面是如何创建一维指标的示例:
//...
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// This is an example of a metric with a single dimension.
// FormFactor is the name of the dimension.
Metric computersSold= _telemetryClient.GetMetric("ComputersSold", "FormFactor");
while (!stoppingToken.IsCancellationRequested)
{
// The number of arguments (dimension values)
// must match the number of dimensions specified while GetMetric.
// Laptop, Tablet, etc are values for the dimension "FormFactor"
computersSold.TrackValue(42, "Laptop");
computersSold.TrackValue(20, "Tablet");
computersSold.TrackValue(126, "Desktop");
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(50, stoppingToken);
}
}
运行示例代码至少 60 秒会向 Azure 发送三条不同的遥测数据。 每个项都表示这三种外形规格之一的聚合。 与之前一样,你可以在“日志(分析)”视图中执行进一步检查。
在指标资源管理器中:
请注意,你无法按新的自定义维度拆分指标,也无法使用指标视图查看自定义维度。
默认情况下,Application Insights 资源中未启用指标资源管理器中的多维指标。
启用多维指标
要为 Application Insights 资源启用多维指标,请选择“使用情况和估计成本”“自定义指标”>“启用自定义指标维度的警报”“确定”>>。 有关详细信息,请参阅自定义指标维度和预聚合。
完成该更改并发送新的多维遥测数据后,可以选择“应用拆分”。
注意
只有在门户中启用该功能之后新发送的指标才会存储维度信息。
查看每个 FormFactor
维度的指标聚合。
当维度超过三个时使用 MetricIdentifier
目前支持 10 个维度。 超过三个维度需要使用 MetricIdentifier
:
// Add "using Microsoft.ApplicationInsights.Metrics;" to use MetricIdentifier
// MetricIdentifier id = new MetricIdentifier("[metricNamespace]","[metricId],"[dim1]","[dim2]","[dim3]","[dim4]","[dim5]");
MetricIdentifier id = new MetricIdentifier("CustomMetricNamespace","ComputerSold", "FormFactor", "GraphicsCard", "MemorySpeed", "BatteryCapacity", "StorageCapacity");
Metric computersSold = _telemetryClient.GetMetric(id);
computersSold.TrackValue(110,"Laptop", "Nvidia", "DDR4", "39Wh", "1TB");
自定义指标配置
如果想要更改指标配置,则必须在初始化指标的位置进行更改。
特殊维度名称
指标不使用用于访问它们的 TelemetryClient
的遥测上下文。 在 MetricDimensionNames
类中使用可用作常量的特殊维度名称是解决此限制的最佳方法。
以下 Special Operation Request Size
指标发送的指标聚合未将 设置为 Context.Operation.Name
。Special Operation
TrackMetric()
方法或任何其他 TrackXXX()
方法已将 OperationName
正确设置为 Special Operation
。
//...
TelemetryClient specialClient;
private static int GetCurrentRequestSize()
{
// Do stuff
return 1100;
}
int requestSize = GetCurrentRequestSize()
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
//...
specialClient.Context.Operation.Name = "Special Operation";
specialClient.GetMetric("Special Operation Request Size").TrackValue(requestSize);
//...
}
}
在这种情况下,使用 MetricDimensionNames
类中列出的特殊维度名称来指定 TelemetryContext
值。
例如,当下一语句生成的指标聚合发送到 Application Insights 云终结点时,其 Context.Operation.Name
数据字段设置为 Special Operation
:
_telemetryClient.GetMetric("Request Size", MetricDimensionNames.TelemetryContext.Operation.Name).TrackValue(requestSize, "Special Operation");
此特殊维度的值被复制到 TelemetryContext
中,不用作普通维度。 如果你还需要保留一个操作维度以用于普通指标浏览,则需要为该目的创建单独的维度:
_telemetryClient.GetMetric("Request Size", "Operation Name", MetricDimensionNames.TelemetryContext.Operation.Name).TrackValue(requestSize, "Special Operation", "Special Operation");
维度和时序上限
为了防止遥测子系统意外耗尽资源,你可以控制每个指标的数据系列最大数量。 默认限制是每个指标的总数据系列不超过 1,000 个,每个维度的不同值不超过 100 个。
重要
对维度使用低基数值以避免限制。
在维度和时序上限的上下文中,我们使用 Metric.TrackValue(..)
来确保遵守限制。 如果已达到限制,则 Metric.TrackValue(..)
返回 False
并且不跟踪该值。 否则,将返回 True
。 如果指标的数据源于用户输入,该行为将很有用。
MetricConfiguration
构造函数采用一些选项来管理相应指标中的不同系列;同时还采用一个实现了 IMetricSeriesConfiguration
接口的类对象,用来指定该指标中每个系列的聚合行为:
var metConfig = new MetricConfiguration(seriesCountLimit: 100, valuesPerDimensionLimit:2,
new MetricSeriesConfigurationForMeasurement(restrictToUInt32Values: false));
Metric computersSold = _telemetryClient.GetMetric("ComputersSold", "Dimension1", "Dimension2", metConfig);
// Start tracking.
computersSold.TrackValue(100, "Dim1Value1", "Dim2Value1");
computersSold.TrackValue(100, "Dim1Value1", "Dim2Value2");
// The following call gives 3rd unique value for dimension2, which is above the limit of 2.
computersSold.TrackValue(100, "Dim1Value1", "Dim2Value3");
// The above call does not track the metric, and returns false.
-
seriesCountLimit
是指标可以包含的最大数据时序数目。 达到此限制时,对TrackValue()
的调用将返回false
,该调用通常会生成新序列。 -
valuesPerDimensionLimit
以类似的方式限制每个维度的非重复值数。 -
restrictToUInt32Values
决定是否应跟踪非负整数值。
以下示例演示如何发送消息以了解是否超过上限:
if (! computersSold.TrackValue(100, "Dim1Value1", "Dim2Value3"))
{
// Add "using Microsoft.ApplicationInsights.DataContract;" to use SeverityLevel.Error
_telemetryClient.TrackTrace("Metric value not tracked as value of one of the dimension exceeded the cap. Revisit the dimensions to ensure they are within the limits",
SeverityLevel.Error);
}
自定义操作跟踪
Application Insights SDK 自动跟踪传入的 HTTP 请求和对依赖服务的调用,例如 HTTP 请求和 SQL 查询。 通过跟踪和关联请求及依赖项,可了解由微服务组成的应用程序对这些微服务的整体响应能力和可靠性。
在一般情况下,有一类应用程序模式不受支持。 正确监视此类模式需要手动代码检测。 本文介绍可能需要手动检测的一些模式,例如自定义队列处理和运行长时间运行的后台任务。
本部分提供了有关如何使用 Application Insights SDK 跟踪自定义操作的指导。
概述
操作是由应用程序运行的一项逻辑工作。 它具有名称、开始时间、持续时间、结果和执行上下文(如用户名、属性和结果)。 如果操作 A 由操作 B 启动,则操作 B 设置为 A 的父级。一个操作只能有一个父操作,但可以有许多子操作。 有关操作和遥测关联的详细信息,请参阅 Application Insights 遥测关联。
在 Application Insights.NET SDK 中,操作由抽象类 OperationTelemetry 及其后代 RequestTelemetry 和 DependencyTelemetry 描述。
传入操作跟踪
Application Insights Web SDK 自动收集 ASP.NET 应用程序(在 IIS 管道中运行)和所有 ASP.NET Core 应用程序的 HTTP 请求。 有其他平台和框架的社区支持解决方案。 如果应用程序不受任何标准或社区支持解决方案的支持,可以手动进行检测。
需要自定义跟踪的另一个示例是,从队列接收项目的辅助角色。 对于某些队列,向队列添加消息的调用将作为依赖项进行跟踪。 不会自动收集描述消息处理的高级操作。
我们来了解可以跟踪此类操作的方式。
大致而言,此任务旨在创建 RequestTelemetry
并设置已知的属性。 在操作完成后,可跟踪遥测数据。 以下示例演示了此任务。
Owin 自托管应用中的 HTTP 请求
在此示例中,跟踪上下文根据 HTTP 关联协议进行传播。 用户应该会收到此处所述的标头。
展开可查看代码
public class ApplicationInsightsMiddleware : OwinMiddleware
{
// You may create a new TelemetryConfiguration instance, reuse one you already have,
// or fetch the instance created by Application Insights SDK.
private readonly TelemetryConfiguration telemetryConfiguration = TelemetryConfiguration.CreateDefault();
private readonly TelemetryClient telemetryClient = new TelemetryClient(telemetryConfiguration);
public ApplicationInsightsMiddleware(OwinMiddleware next) : base(next) {}
public override async Task Invoke(IOwinContext context)
{
// Let's create and start RequestTelemetry.
var requestTelemetry = new RequestTelemetry
{
Name = $"{context.Request.Method} {context.Request.Uri.GetLeftPart(UriPartial.Path)}"
};
// If there is a Request-Id received from the upstream service, set the telemetry context accordingly.
if (context.Request.Headers.ContainsKey("Request-Id"))
{
var requestId = context.Request.Headers.Get("Request-Id");
// Get the operation ID from the Request-Id (if you follow the HTTP Protocol for Correlation).
requestTelemetry.Context.Operation.Id = GetOperationId(requestId);
requestTelemetry.Context.Operation.ParentId = requestId;
}
// StartOperation is a helper method that allows correlation of
// current operations with nested operations/telemetry
// and initializes start time and duration on telemetry items.
var operation = telemetryClient.StartOperation(requestTelemetry);
// Process the request.
try
{
await Next.Invoke(context);
}
catch (Exception e)
{
requestTelemetry.Success = false;
requestTelemetry.ResponseCode;
telemetryClient.TrackException(e);
throw;
}
finally
{
// Update status code and success as appropriate.
if (context.Response != null)
{
requestTelemetry.ResponseCode = context.Response.StatusCode.ToString();
requestTelemetry.Success = context.Response.StatusCode >= 200 && context.Response.StatusCode <= 299;
}
else
{
requestTelemetry.Success = false;
}
// Now it's time to stop the operation (and track telemetry).
telemetryClient.StopOperation(operation);
}
}
public static string GetOperationId(string id)
{
// Returns the root ID from the '|' to the first '.' if any.
int rootEnd = id.IndexOf('.');
if (rootEnd < 0)
rootEnd = id.Length;
int rootStart = id[0] == '|' ? 1 : 0;
return id.Substring(rootStart, rootEnd - rootStart);
}
}
HTTP 关联协议还声明 Correlation-Context
标头。 为了简单起见,此处省略了该操作。
队列检测
W3C 跟踪上下文和 HTTP 关联协议使用 HTTP 请求传递关联详细信息,但每个队列协议必须定义如何随队列消息传递相同的详细信息。 有些队列协议(例如 AMQP)允许传递更多元数据。 其他协议(例如 Azure 存储队列)要求将上下文编码到消息有效负载中。
注意
队列尚不支持跨组件跟踪。
使用 HTTP 时,如果生成者和使用者将遥测数据发送到不同的 Application Insights 资源,则事务诊断体验和应用程序映射将显示事务和端到端映射。 对于队列,尚不支持此功能。
服务总线队列
有关跟踪信息,请参阅通过 Azure 服务总线消息传递进行分布式跟踪和关联。
Azure 存储队列
以下示例显示如何跟踪 Azure 存储队列操作,并将生成者、使用者和 Azure 存储之间的遥测相关联。
存储队列具有一个 HTTP API。 用于 HTTP 请求的 Application Insights Dependency Collector 会跟踪对该队列的所有调用。 在 ASP.NET 和 ASP.NET Core 应用程序上默认会配置此功能。 对于其他类型的应用程序,请参阅控制台应用程序文档。
用户可能还想将 Application Insights 操作 ID 与存储请求 ID 相关联。 有关如何设置与获取存储请求客户端和服务器请求 ID 的信息,请参阅对 Azure 存储进行监视、诊断和故障排除。
由于存储队列支持 HTTP API,因此 Application Insights 会自动跟踪队列的所有操作。 在多数情况下,此检测已足够。 为了将使用者跟踪与生成者跟踪相关联,必须传递某些关联上下文,方法类似于 HTTP 关联协议中所执行的操作。
此示例演示如何跟踪 Enqueue
操作。 您可以:
-
关联重试(如果有):它们都有一个共同的父级,即
Enqueue
操作。 否则,它们都作为传入请求的子级进行跟踪。 如果有多个对队列的逻辑请求,可能很难发现导致重试的调用。 - 关联存储日志(如果需要):它们与 Application Insights 遥测相关联。
Enqueue
操作是父操作的子级。 例如传入的 HTTP 请求。 HTTP 依赖项调用是 Enqueue
操作的子级以及传入请求的孙级。
public async Task Enqueue(CloudQueue queue, string message)
{
var operation = telemetryClient.StartOperation<DependencyTelemetry>("enqueue " + queue.Name);
operation.Telemetry.Type = "Azure queue";
operation.Telemetry.Data = "Enqueue " + queue.Name;
// MessagePayload represents your custom message and also serializes correlation identifiers into payload.
// For example, if you choose to pass payload serialized to JSON, it might look like
// {'RootId' : 'some-id', 'ParentId' : '|some-id.1.2.3.', 'message' : 'your message to process'}
var jsonPayload = JsonConvert.SerializeObject(new MessagePayload
{
RootId = operation.Telemetry.Context.Operation.Id,
ParentId = operation.Telemetry.Id,
Payload = message
});
CloudQueueMessage queueMessage = new CloudQueueMessage(jsonPayload);
// Add operation.Telemetry.Id to the OperationContext to correlate Storage logs and Application Insights telemetry.
OperationContext context = new OperationContext { ClientRequestID = operation.Telemetry.Id};
try
{
await queue.AddMessageAsync(queueMessage, null, null, new QueueRequestOptions(), context);
}
catch (StorageException e)
{
operation.Telemetry.Properties.Add("AzureServiceRequestID", e.RequestInformation.ServiceRequestID);
operation.Telemetry.Success = false;
operation.Telemetry.ResultCode = e.RequestInformation.HttpStatusCode.ToString();
telemetryClient.TrackException(e);
}
finally
{
// Update status code and success as appropriate.
telemetryClient.StopOperation(operation);
}
}
若要减少应用程序报告的遥测数或者由于其他原因不想跟踪 Enqueue
操作,可直接使用 Activity
API:
- 创建(并启动)新的
Activity
,而不是启动 Application Insights 操作。 除了作名称之外,无需为其分配任何属性。 - 将
yourActivity.Id
串行化到消息有效负载,而不是operation.Telemetry.Id
。 还可以使用Activity.Current.Id
。
同样,可以检测其他队列操作。 应该以类似于取消排队操作的方式检测速览操作。 不必检测队列管理操作。 Application Insights 会跟踪 HTTP 之类的操作,在大多数情况下,这就足够了。
检测消息删除时,请务必设置操作(关联)标识符。 或者,可以使用 Activity
API。 这样就无需在遥测项目上设置操作标识符,因为 Application Insights SDK 会为用户完成:
- 从队列中获取项目后,创建新的
Activity
。 - 使用
Activity.SetParentId(message.ParentId)
关联使用者日志和生产者日志。 - 启动
Activity
。 - 使用
Start/StopOperation
帮助程序跟踪取消排队、处理和删除操作。 从同一个异步控制流(执行上下文)执行。 这样,它们就能正确关联。 - 停止
Activity
。 - 使用
Start/StopOperation
或手动调用Track
遥测。
依赖项类型
Application Insights 使用依赖项类型来自定义 UI 体验。 对于队列,它识别以下可改善DependencyTelemetry
的 类型:
-
Azure queue
(Azure 存储队列) -
Azure Event Hubs
表示 Azure 事件中心 -
Azure Service Bus
表示 Azure 服务总线
批处理
有些队列允许对一个请求的多条消息取消排队。 这类消息的处理可能彼此独立,而且属于不同的逻辑操作。 无法将 Dequeue
操作关联到正在处理的特定消息。
每条消息都应在自己的异步控制流中处理。 有关详细信息,请参阅传出依赖项跟踪部分。
长时间运行后台任务
某些应用程序可能因用户请求而启动长时间运行的操作。 从跟踪/检测的角度来看,它与请求或依赖项检测没有区别:
async Task BackgroundTask()
{
var operation = telemetryClient.StartOperation<DependencyTelemetry>(taskName);
operation.Telemetry.Type = "Background";
try
{
int progress = 0;
while (progress < 100)
{
// Process the task.
telemetryClient.TrackTrace($"done {progress++}%");
}
// Update status code and success as appropriate.
}
catch (Exception e)
{
telemetryClient.TrackException(e);
// Update status code and success as appropriate.
throw;
}
finally
{
telemetryClient.StopOperation(operation);
}
}
在此示例中,telemetryClient.StartOperation
创建 DependencyTelemetry
并填充相关上下文。 假设有一个父操作,它是由计划操作的传入请求创建的。 只要在与传入请求相同的异步控制流中启动 BackgroundTask
,它就会与该父操作相关联。
BackgroundTask
和所有嵌套的遥测项自动与引发此项的请求相关联,即使请求结束也一样。
从不含与之关联的任何操作 (Activity
) 的后台线程启动任务时,BackgroundTask
没有任何父级。 但是,它可以具有嵌套操作。 从任务报告的所有遥测项与 DependencyTelemetry
中创建的 BackgroundTask
相关联。
传出依赖项跟踪
用户可以跟踪自己的依赖项类型或不受 Application Insights 支持的操作。
服务总线队列或 Azure 存储队列中的 Enqueue
方法可作为此类自定义跟踪的示例。
自定义依赖项跟踪的常规方法是:
- 调用
TelemetryClient.StartOperation
(扩展)方法,该方法填充关联所需的DependencyTelemetry
属性和某些其他属性,例如开始时间、时间戳和持续时间。 - 在
DependencyTelemetry
上设置其他自定义属性,比如名称和所需的任何其他上下文。 - 进行依赖项调用,并等它完成。
- 完成后,使用
StopOperation
停止操作。 - 处理异常。
public async Task RunMyTaskAsync()
{
using (var operation = telemetryClient.StartOperation<DependencyTelemetry>("task 1"))
{
try
{
var myTask = await StartMyTaskAsync();
// Update status code and success as appropriate.
}
catch(...)
{
// Update status code and success as appropriate.
}
}
}
释放某个操作会导致该操作停止,因此可以这样做而不是调用 StopOperation
。
警告
在某些情况下,未经处理的异常可能会阻止调用 finally
,因此可能无法跟踪操作。
并行处理和跟踪操作
调用 StopOperation
只会停止已启动的操作。 如果当前运行的操作与要停止的操作不匹配,StopOperation
不执行任何操作。 如果在同一执行上下文中并行启动多个操作,则可能发生这种情况。
var firstOperation = telemetryClient.StartOperation<DependencyTelemetry>("task 1");
var firstTask = RunMyTaskAsync();
var secondOperation = telemetryClient.StartOperation<DependencyTelemetry>("task 2");
var secondTask = RunMyTaskAsync();
await firstTask;
// FAILURE!!! This will do nothing and will not report telemetry for the first operation
// as currently secondOperation is active.
telemetryClient.StopOperation(firstOperation);
await secondTask;
请确保始终在同一异步方法中调用 StartOperation
和处理操作,以隔离并行运行的操作。 如果操作是同步的(或非异步的),请包装进程并使用 Task.Run
跟踪。
public void RunMyTask(string name)
{
using (var operation = telemetryClient.StartOperation<DependencyTelemetry>(name))
{
Process();
// Update status code and success as appropriate.
}
}
public async Task RunAllTasks()
{
var task1 = Task.Run(() => RunMyTask("task 1"));
var task2 = Task.Run(() => RunMyTask("task 2"));
await Task.WhenAll(task1, task2);
}
ApplicationInsights 操作与 System.Diagnostics.Activity
System.Diagnostics.Activity
表示分布式跟踪上下文,由框架和库用来在进程内外创建和传播上下文,并关联遥测项。
Activity
与 System.Diagnostics.DiagnosticSource
配合运行,后者是框架/库之间的通知机制,用于通知需要关注的事件,例如传入或传出请求和异常。
活动是 Application Insights 中的一流公民。 自动依赖项和请求集合严重依赖于活动以及 DiagnosticSource
事件。 如果你在应用程序中创建了 Activity
,将不会导致创建 Application Insights 遥测。 Application Insights 需要接收 DiagnosticSource
事件并了解事件名称和有效负载,才能转换为 Activity
遥测数据。
每个 Application Insights 操作(请求或依赖项)都涉及 Activity
。 调用 StartOperation
时,它会在下面创建 Activity
。
StartOperation
是手动跟踪请求或依赖项遥测的推荐方法,并确保一切事项都是相关的。
Application Insights 中的计数器
Application Insights 支持性能计数器和事件计数器。 本指南对这两个计数器都做了概述,包括它们在 .NET 应用程序中的用途、配置和使用方法。
概述
性能计数器内置于 Windows 操作系统中,并提供预定义的指标,例如 CPU 使用率、内存消耗和磁盘活动。 这些计数器非常适合以最少的设置来监视标准性能指标。 它们可帮助在基于 Windows 的应用程序中跟踪资源利用率或排查系统级瓶颈问题,但不支持自定义特定于应用程序的指标。
事件计数器跨多个平台工作,包括 Windows、Linux 和 macOS。 它们允许开发人员定义和监视轻型、可自定义的特定于应用程序的指标,从而提供比性能计数器更大的灵活性。 当系统指标不足以满足要求或跨平台应用程序中需要详细遥测时,事件计数器非常有用。 它们需要显式实现和配置,这使得设置更加费力。
性能计数器
Windows 提供了各种性能计数器,例如用于收集处理器、内存和磁盘使用统计信息的计数器。 你还可以定义自己的性能计数器。
如果应用程序在本地主机或具有管理访问权限的虚拟机上的 Internet 信息服务器 (IIS) 下运行,则应用程序支持性能计数器收集。 作为 Azure Web 应用运行的应用程序无法直接访问性能计数器,但 Application Insights 会收集一部分可用的计数器。
小窍门
与其他指标一样,可以设置警报以便在计数器超出指定的限制时收到警报。 若要设置警报,请打开“警报”窗格并选择“添加警报”。
先决条件
通过将应用程序池服务帐户添加到性能监视器用户组来为其授予监视性能计数器的权限。
net localgroup "Performance Monitor Users" /add "IIS APPPOOL\NameOfYourPool"
查看计数器
“指标”窗格显示了一组默认的性能计数器。
ASP.NET Web 应用程序的默认计数器:
- % 进程\处理器时间
- % 进程\处理器时间标准化
- 内存\可用字节数
- ASP.NET 请求数/秒
- 每秒抛出异常的 .NET 公共语言运行时 (CLR)
- ASP.NET ApplicationsRequest 执行时间
- 进程\私有字节
- Process\IO 数据字节数/秒
- ASP.NET 应用程序队列中的应用程序\请求
- 处理器(_Total)\% 处理器占用时间
添加计数器
如果你需要的性能计数器未包括在指标列表中,则你可以添加它。
选项 1:ApplicationInsights.config 中的配置
通过在本地服务器上使用此 PowerShell 命令,了解服务器中有哪些计数器可用:
Get-Counter -ListSet *
有关详细信息,请参阅
Get-Counter
。打开
ApplicationInsights.config
。如果在开发期间将 Application Insights 添加到应用:
- 在项目中编辑
ApplicationInsights.config
。 - 将其重新部署到服务器。
- 在项目中编辑
编辑性能收集器指令:
<Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule, Microsoft.AI.PerfCounterCollector"> <Counters> <Add PerformanceCounter="\Objects\Processes"/> <Add PerformanceCounter="\Sales(photo)\# Items Sold" ReportAs="Photo sales"/> </Counters> </Add>
可以捕获标准计数器和自己实现的计数器。
\Objects\Processes
是标准计数器的一个示例,可在所有 Windows 系统上使用。
\Sales(photo)\# Items Sold
是自定义计数器的一个示例,可在 Web 服务中实现。
格式为 \Category(instance)\Counter
,而对于不具有实例的类别,仅为 \Category\Counter
。
与 ReportAs
不匹配的计数器名称需要 [a-zA-Z()/-_ \.]+
参数。
如果指定实例,它会成为所报告指标的 CounterInstanceName
维度。
选项 2:代码中的配置
请参阅以下部分。
为 ASP.NET Web 应用程序或 .NET/.NET Core 控制台应用程序收集代码中的性能计数器
若要收集系统性能计数器并将其发送到 Application Insights,可以改编以下代码片段:
var perfCollectorModule = new PerformanceCollectorModule();
perfCollectorModule.Counters.Add(new PerformanceCounterCollectionRequest(
@"\Process([replace-with-application-process-name])\Page Faults/sec", "PageFaultsPerfSec"));
perfCollectorModule.Initialize(TelemetryConfiguration.Active);
或者,可以执行与所创建自定义指标相同的操作:
var perfCollectorModule = new PerformanceCollectorModule();
perfCollectorModule.Counters.Add(new PerformanceCounterCollectionRequest(
@"\Sales(photo)\# Items Sold", "Photo sales"));
perfCollectorModule.Initialize(TelemetryConfiguration.Active);
在 Azure 应用服务上的 Azure Web 应用和 Windows 容器中运行的应用程序的性能计数器
部署到 Azure Web 应用的 ASP.NET 和 ASP.NET Core 应用程序在特殊的沙盒环境中运行。 部署到 Azure 应用服务的应用程序可以利用 Windows 容器,也可以在沙盒环境中托管。 如果在 Windows 容器中部署应用程序,则可在容器映像中使用所有标准性能计数器。
沙盒环境不允许直接访问系统性能计数器。 但是,有限的一部分计数器将作为环境变量公开,如作为环境变量公开的性能计数器中所述。 在此环境中只能使用一部分计数器。 有关完整列表,请参阅作为环境变量公开的性能计数器。
适用于 ASP.NET 和 ASP.NET Core 的 Application Insights SDK 会检测代码是部署到 Web 应用还是非 Windows 容器。 这种检测决定了它是在沙盒环境中还是利用标准收集机制(在 Windows 容器或虚拟机上托管时)来收集性能计数器。
针对性能计数器的 Log Analytics 查询
可以在 Log Analytics 中搜索并显示性能计数器报告。
PerformanceCounters 架构公开每个性能计数器的 category
、counter
名称和 instance
名称。 在每个应用程序的遥测中,将仅看到该应用程序的计数器。 例如,若要查看哪些计数器可用:
performanceCounters | summarize count(), avg(value) by category, instance, counter
此处的 Instance
是指性能计数器实例,而不是角色或服务器计算机实例。 通常,性能计数器实例名称会按进程或应用程序的名称对计数器(如处理器时间)进行分段。
若要获取最近一段时间内可用内存的图表:
performanceCounters | where counter == "Available Bytes" | summarize avg(value), min(value) by bin(timestamp, 1h) | render timechart
与其他遥测一样,performanceCounters 同样也具有列 cloud_RoleInstance
,指示正在其上运行应用的主机服务器实例的标识。 例如,若要应用在不同计算机上的性能:
performanceCounters | where counter == "% Processor Time" and instance == "SendMetrics" | summarize avg(value) by cloud_RoleInstance, bin(timestamp, 1d)
性能计数器常见问题解答
若要查看常见问题解答 (FAQ),请参阅性能计数器常见问题解答。
事件计数器
EventCounter
是用于发布和使用计数器或统计信息的 .NET/.NET Core 机制。 所有 OS 平台(Windows、Linux 和 macOS)都支持 EventCounters。 可以将其视为仅在 Windows 系统中受支持的 PerformanceCounters 的等效跨平台。
虽然用户可以根据需要发布任何自定义事件计数器,但默认情况下,.NET 会发布一组此类计数器。 该文档指导你完成在 Azure Application Insights 中收集和查看事件计数器(系统定义的或用户定义的)所需的步骤。
小窍门
与其他指标一样,可以设置警报以便在计数器超出指定的限制时收到警报。 若要设置警报,请打开“警报”窗格并选择“添加警报”。
使用 Application Insights 收集 EventCounters
Application Insights 支持使用 EventCounters
来收集 EventCounterCollectionModule
,新发布的 NuGet 包 Microsoft.ApplicationInsights.EventCounterCollector 中包含该模块。
使用 EventCounterCollectionModule
或 WorkerService 时,将自动启用 。
EventCounterCollectionModule
以 60 秒的收集频率(不可配置)收集计数器。 收集 EventCounters 时,不需要具备特殊的权限。 对于 ASP.NET Core 应用程序,还需要添加 Microsoft.ApplicationInsights.AspNetCore 包。
dotnet add package Microsoft.ApplicationInsights.EventCounterCollector
dotnet add package Microsoft.ApplicationInsights.AspNetCore
已收集默认计数器
从 AspNetCore SDK 或 WorkerService SDK 的 2.15.0 版本开始,默认情况下不会收集任何计数器。 模块本身已启用,因此用户可以添加所需的计数器来收集它们。
若要获取 .NET 运行时发布的已知计数器的列表,请参阅可用计数器文档。
自定义要收集的计数器
以下示例介绍如何添加/删除计数器。 使用 AddApplicationInsightsTelemetry()
或 AddApplicationInsightsWorkerService()
启用 Application Insights 遥测收集后,此自定义将作为应用程序服务配置的一部分完成。 下面是 ASP.NET Core 应用程序的示例代码。 有关其他类型的应用程序,请参阅 本文档 。
using Microsoft.ApplicationInsights.Extensibility.EventCounterCollector;
using Microsoft.Extensions.DependencyInjection;
builder.Services.ConfigureTelemetryModule<EventCounterCollectionModule>(
(module, o) =>
{
// Removes all default counters, if any.
module.Counters.Clear();
// Adds a user defined counter "MyCounter" from EventSource named "MyEventSource"
module.Counters.Add(
new EventCounterCollectionRequest("MyEventSource", "MyCounter"));
// Adds the system counter "gen-0-size" from "System.Runtime"
module.Counters.Add(
new EventCounterCollectionRequest("System.Runtime", "gen-0-size"));
}
);
禁用 EventCounter 收集模块
可以使用 EventCounterCollectionModule
禁用 ApplicationInsightsServiceOptions
。
以下示例使用 ASP.NET Core SDK。
using Microsoft.ApplicationInsights.AspNetCore.Extensions;
using Microsoft.Extensions.DependencyInjection;
var applicationInsightsServiceOptions = new ApplicationInsightsServiceOptions();
applicationInsightsServiceOptions.EnableEventCounterCollectionModule = false;
builder.Services.AddApplicationInsightsTelemetry(applicationInsightsServiceOptions);
类似的方法也可用于 WorkerService SDK,但必须更改命名空间,如以下示例中所示。
using Microsoft.ApplicationInsights.AspNetCore.Extensions;
using Microsoft.Extensions.DependencyInjection;
var applicationInsightsServiceOptions = new ApplicationInsightsServiceOptions();
applicationInsightsServiceOptions.EnableEventCounterCollectionModule = false;
builder.Services.AddApplicationInsightsTelemetry(applicationInsightsServiceOptions);
针对事件计数器的 Log Analytics 查询
你可以在 Log Analytics 的“customMetrics”表中搜索和显示事件计数器报表。
例如,运行以下查询,以查看收集了哪些计数器并可用于查询:
customMetrics | summarize avg(value) by name
若要在最近一段时间内获取特定计数器(例如:ThreadPool Completed Work Item Count
)的图表,请运行以下查询。
customMetrics
| where name contains "System.Runtime|ThreadPool Completed Work Item Count"
| where timestamp >= ago(1h)
| summarize avg(value) by cloud_RoleInstance, bin(timestamp, 1m)
| render timechart
与其他遥测一样,customMetrics 同样也具有列 ,指示正在其上运行应用的主机服务器实例的标识cloud_RoleInstance
。 上述查询显示每个实例的计数器值,并可用于比较不同服务器实例的性能。
事件计数器常见问题解答
若要查看常见问题解答 (FAQ),请参阅事件计数器常见问题解答。
配置 Application Insights SDK
本部分内容
可以自定义 application Insights SDK for ASP.NET 和 ASP.NET Core 以更改默认配置。
Application Insights .NET SDK 由很多 NuGet 包组成。 核心包提供 API,用于将遥测数据发送到 Application Insights。 其他包提供遥测模块和初始值设定项,用于自动从应用程序及其上下文跟踪遥测。 可以通过调整配置文件来启用或禁用遥测模块和初始值设定项。 对于其中的一些,你还可以设置参数。
配置文件名称是 ApplicationInsights.config
或 ApplicationInsights.xml
。 该名称取决于应用程序的类型。
安装大多数版本的 SDK 时,系统会自动将配置文件添加到项目。
默认情况下,使用支持“添加”“Application Insights 遥测”>的 Visual Studio 模板项目提供的自动化体验时,ApplicationInsights.config
文件将在项目根文件夹中创建。 编译后,它会复制到 bin 文件夹。 它也会由 IIS 服务器上的 Application Insights 代理添加到 Web 应用。
重要
如果使用了 Azure 网站的扩展或 Azure VM 和虚拟机规模集的扩展,则会忽略此配置文件。
没有一个等效的文件用来控制网页中的 SDK。
遥测通道
遥测通道是 Application Insights SDK 不可或缺的组成部分。 它们负责管理发往 Application Insights 服务的遥测数据的缓冲和传输。 SDK 的 .NET 和 .NET Core 版本具有两个内置遥测通道:InMemoryChannel
和 ServerTelemetryChannel
。 本文介绍每个频道,并演示如何自定义通道行为。
注意
若要查看常见问题解答 (FAQ),请参阅遥测通道常见问题解答
什么是遥测通道?
遥测通道负责缓冲遥测项,并将其发送到 Application Insights 服务,系统会在其中存储这些数据,以供查询和分析。 遥测通道是实现 Microsoft.ApplicationInsights.ITelemetryChannel
接口的任何类。
在调用所有遥测初始化程序和遥测处理器之后,将调用遥测通道的 Send(ITelemetry item)
方法。 因此,遥测处理器删除的项都不会进入通道。 一般情况下,Send()
方法不会立即将项发送到后端。 它通常将这些项缓冲在内存中并分批发送,以提高传输效率。
除非必须立即发送缓冲的遥测数据,否则请勿调用 Flush()
。 仅在以下场景中使用它:应用程序关闭、异常处理,或者在使用短生命周期的进程(例如后台任务或命令行工具)时。 在 Web 应用程序或长时间运行的服务中,SDK 会自动处理遥测数据发送。 在非必要的情况下调用 Flush()
可能会导致性能问题。
实时指标流还有一个自定义通道,可支持遥测实时流式传输。 此通道与常规遥测通道是相互独立的,本文件不适用于此通道。
内置遥测通道
Application Insights .NET 和 .NET Core SDK 附带两个内置通道:
InMemoryChannel:一个轻型通道,它在内存中将项目缓冲到发送为止。 项目会缓存在内存中,每 30 秒刷新一次,或在缓存满 500 个项目时刷新。 此通道只提供最低限度的可靠性保证,因为它在发送遥测数据失败后不会进行重试。 此通道也不会将项保留在磁盘上。 因此,无论应用程序关闭是否正常,任何未发送的项都将永久丢失。 此通道实现了
Flush()
方法,可用于同步强制刷新任何内存中的遥测项目。 此通道非常适合短时运行的应用程序,在这种情况下同步刷新是理想的选择。此通道是更大的 Microsoft.ApplicationInsights NuGet 包的一部分,并且是在未作其他配置时 SDK 默认使用的通道。
ServerTelemetryChannel:这是一个更高级的通道,它具有重试策略,并能够将数据存储到本地磁盘。 如果出现暂时性错误,该通道会重新尝试发送遥测数据。 在网络中断或者遥测量较高时,此通道还会使用本地磁盘存储将项保留在磁盘上。 由于这些重试机制和本地磁盘存储,我们认为此通道更可靠。 建议将其用于所有生产方案。 此通道是根据官方文档配置的 ASP.NET 和 ASP.NET 核心应用程序的默认通道。 此通道专为具有长时间运行进程的服务器环境进行了优化。 此通道实现的
Flush()
方法不是同步的。此通道作为 Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel NuGet 包交付,使用 Microsoft.ApplicationInsights.Web 或 Microsoft.ApplicationInsights.AspNetCore NuGet 包时可自动获取它。
配置遥测通道
你可以对遥测通道进行配置,将其设置为活动的遥测配置。 对于 ASP.NET 应用程序,配置过程涉及到将遥测通道实例设置为 TelemetryConfiguration.Active
,或修改 ApplicationInsights.config
。 对于 ASP.NET Core 应用程序,配置过程涉及到将通道添加到依赖项注入容器。
以下部分展示了针对不同应用程序类型配置 StorageFolder
设置的示例。
StorageFolder
只是可配置设置之一。 有关配置设置的完整列表,请参阅本文后面的通道中的可配置设置部分。
选项 1:代码中的配置
以下代码设置一个 ServerTelemetryChannel
实例,其中 StorageFolder
设置为自定义位置。 请将此代码添加到应用程序的开头,通常是添加到 Global.aspx.cs 中的 Application_Start()
方法内。
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel;
protected void Application_Start()
{
var serverTelemetryChannel = new ServerTelemetryChannel();
serverTelemetryChannel.StorageFolder = @"d:\temp\applicationinsights";
serverTelemetryChannel.Initialize(TelemetryConfiguration.Active);
TelemetryConfiguration.Active.TelemetryChannel = serverTelemetryChannel;
}
选项 2:ApplicationInsights.config 中的配置
ApplicationInsights.config 中的以下部分展示了 ServerTelemetryChannel
通道的配置情况,其中 StorageFolder
被设置为一个自定义位置:
<TelemetrySinks>
<Add Name="default">
<TelemetryProcessors>
<!-- Telemetry processors omitted for brevity -->
</TelemetryProcessors>
<TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel">
<StorageFolder>d:\temp\applicationinsights</StorageFolder>
</TelemetryChannel>
</Add>
</TelemetrySinks>
代码中针对控制台应用程序的配置
对于控制台应用,适用于 .NET 和 .NET Core 的代码相同:
var serverTelemetryChannel = new ServerTelemetryChannel();
serverTelemetryChannel.StorageFolder = @"d:\temp\applicationinsights";
serverTelemetryChannel.Initialize(TelemetryConfiguration.Active);
TelemetryConfiguration.Active.TelemetryChannel = serverTelemetryChannel;
ServerTelemetryChannel 的操作详细信息
ServerTelemetryChannel
会将传入的项保存到内存缓冲区中。 这些项目会被序列化、压缩,并存储到一个 Transmission
实例中,每 30 秒执行一次,或者当缓冲数量达到 500 个项目时立即执行。 单个 Transmission
实例最多包含 500 个项目,表示通过对 Application Insights 服务的单个 HTTPS 调用发送的一批遥测数据。
默认情况下,最多可以并行发送 10 Transmission
个实例。 如果遥测数据以更快的速度到达,或者网络或 Application Insights 后端响应较慢,则 Transmission
实例会被存储在内存中。 此内存 Transmission
缓冲区的默认容量为 5 MB。 超过内存中容量后,Transmission
实例将存储在本地磁盘上,最大限制为 50 MB。
当存在网络问题时,Transmission
实例也会存储在本地磁盘上。 只有存储在本地磁盘上的项目才能在应用程序崩溃后保留下来。 每当应用程序再次启动时,系统就会发送这些项目。 如果网络问题仍然存在,则 ServerTelemetryChannel
在重试发送遥测数据之前,将使用指数退避逻辑,范围从 10 秒到 1 小时。
通道中的可配置设置
有关每个通道的可配置设置的完整列表,请参阅:
以下是 ServerTelemetryChannel
最常用的设置:
MaxTransmissionBufferCapacity
:通道用于缓冲内存中的传输的最大内存量(以字节为单位)。 达到此容量后,新项目将直接存储到本地磁盘。 默认值为 5 MB。 设置较高的值会导致磁盘使用率降低,但请记住,如果应用程序崩溃,内存中的项目会丢失。MaxTransmissionSenderCapacity
:同时发送到 Application Insights 的Transmission
实例的最大数量。 默认值为 10。 可将此设置配置为更大的数字,生成巨量的遥测数据时建议这样做。 执行负载测试或关闭采样时,往往会出现大量的遥测数据。StorageFolder
:磁盘上的文件夹,通道根据需要将项存储到其中。 在 Windows 中,如果没有明确指定其他路径,则使用 %LOCALAPPDATA% 或 %TEMP%。 在 Windows 以外的环境中,必须指定有效位置,否则遥测数据不会存储到本地磁盘。
应使用哪个通道?
对于涉及到长时间运行的应用程序的大多数生产方案,建议使用 ServerTelemetryChannel
。 有关刷新遥测的详细信息,请了解如何使用 Flush()
。
何时使用 Flush()
Flush()
方法会立即发送任何缓冲的遥测数据。 但是,它只应在特定方案中使用。
在以下情况下使用 Flush()
:
- 应用程序即将关闭,并且你想要确保在退出之前发送遥测数据。
- 你位于异常处理程序中,需要保证遥测数据已送达。
- 你要编写一个短暂的进程,例如快速退出的后台作业或 CLI 工具。
避免在长时间运行的应用程序(如 Web 服务)中使用 Flush()
。 SDK 会自动管理缓冲和传输。 在非必要的情况下调用 Flush()
可能会导致性能问题,并且不能保证发送所有数据,尤其是在使用 ServerTelemetryChannel
时,因为它不会同步刷新。
遥测模块
Application Insights 自动收集有关特定工作负荷的遥测数据,无需用户手动跟踪。
默认情况下,启用以下自动收集模块。 可以禁用或配置这些模块,以改变其默认行为。
每个遥测模块收集特定类型的数据,并使用核心 API 来发送数据。 不同的 NuGet 包会安装这些模块,同时在 .config 文件中添加所需的行。
Area | DESCRIPTION |
---|---|
请求跟踪 | 收集传入 Web 请求的请求遥测数据(响应时间、结果代码)。 模块: Microsoft.ApplicationInsights.Web.RequestTrackingTelemetryModule NuGet:Microsoft.ApplicationInsights.Web |
依赖关系跟踪 | 收集有关传出依赖项(HTTP 调用、SQL 调用)的遥测数据。 若要在 IIS 中运行,请安装 Application Insights 代理。 还可以使用 TrackDependency API 编写自定义依赖项跟踪。 支持通过应用服务和 VM/VMSS 监控进行自动检测。 模块: Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule NuGet:Microsoft.ApplicationInsights.DependencyCollector |
性能计数器 | 收集 Windows 性能计数器(来自 IIS 安装的 CPU、内存、网络负载)。 指定哪些计数器(包括自定义的计数器)。 有关详细信息,请参阅收集系统性能计数器。 模块: Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule NuGet:Microsoft.ApplicationInsights.PerfCounterCollector |
事件计数器 | 收集 .NET EventCounters。 推荐在 ASP.NET Core 以及跨平台场景中使用,以替代 Windows 性能计数器。 模块: (SDK ≥ 2.8.0) EventCounterCollectionModule |
实时指标 (QuickPulse) | 收集实时指标窗格的遥测数据。 模块: QuickPulseTelemetryModule |
检测信号(应用服务) | 发送应用服务环境的检测信号和自定义指标。 模块: AppServicesHeartbeatTelemetryModule |
检测信号 (VM/VMSS) | 发送 Azure VM 环境的检测信号和自定义指标。 模块: AzureInstanceMetadataTelemetryModule |
诊断遥测数据 | 报告 Application Insights 检测代码中的错误(例如缺少计数器、ITelemetryInitializer 异常)。 跟踪遥测数据会显示在诊断搜索中。模块: Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.DiagnosticsTelemetryModule NuGet:Microsoft.ApplicationInsights 请注意:如果只安装此包,则不会自动创建 ApplicationInsights.config 文件。 |
开发人员模式(附加了调试程序) | 当连接了调试程序时,强制 TelemetryChannel 立即发送项目。 降低延迟,但会增加 CPU/网络开销。模块: Microsoft.ApplicationInsights.WindowsServer.DeveloperModeWithDebuggerAttachedTelemetryModule NuGet:Application Insights Windows Server |
异常跟踪 (Web) | 跟踪 Web 应用中未经处理的异常。 请参阅故障和异常。 模块: Microsoft.ApplicationInsights.Web.ExceptionTrackingTelemetryModule NuGet:Microsoft.ApplicationInsights.Web |
异常跟踪(未观察/未处理) | 跟踪辅助角色、Windows 服务和控制台应用的未记录任务异常和未经处理的异常。 模块: • Microsoft.ApplicationInsights.WindowsServer.UnobservedExceptionTelemetryModule • Microsoft.ApplicationInsights.WindowsServer.UnhandledExceptionTelemetryModule NuGet:Microsoft.ApplicationInsights.WindowsServer |
EventSource 跟踪 | 将配置的 EventSource 事件作为跟踪发送到 Application Insights。 模块: Microsoft.ApplicationInsights.EventSourceListener.EventSourceTelemetryModule NuGet:Microsoft.ApplicationInsights.EventSourceListener |
ETW 收集器 | 将配置的 ETW 提供程序事件作为跟踪发送到 Application Insights。 模块: Microsoft.ApplicationInsights.EtwCollector.EtwCollectorTelemetryModule NuGet:Microsoft.ApplicationInsights.EtwCollector |
核心 API(不是模块) |
其他遥测组件和自定义遥测使用的核心 API。 模块: Microsoft.ApplicationInsights package NuGet:Microsoft.ApplicationInsights 请注意:如果只安装此包,则不会自动创建 ApplicationInsights.config 文件。 |
配置遥测模块
使用 ApplicationInsights.configTelemetryModules
中的 部分来配置、添加或删除模块。 示例如下:
- 配置
DependencyTrackingTelemetryModule
(启用 W3C 标头注入)。 - 配置
EventCounterCollectionModule
(清除默认值并添加单个计数器)。 - 通过删除
PerformanceCollectorModule
禁用 perf-counter 集合。
<ApplicationInsights>
<TelemetryModules>
<!-- Dependency tracking -->
<Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector">
<!-- Match Core example: enable W3C header injection -->
<EnableW3CHeadersInjection>true</EnableW3CHeadersInjection>
</Add>
<!-- EventCounterCollectionModule: add a single counter (if you use event counters) -->
<Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.EventCounterCollectionModule, Microsoft.AI.PerfCounterCollector">
<Counters>
<!-- Mirrors Core example: only collect 'gen-0-size' from System.Runtime -->
<Add ProviderName="System.Runtime" CounterName="gen-0-size" />
</Counters>
</Add>
<!-- PerformanceCollectorModule (classic Windows performance counters).
To DISABLE perf-counter collection, do NOT include this module.
If it already exists in your file, remove or comment it out.
Example of the line you would remove:
<Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule, Microsoft.AI.PerfCounterCollector" />
-->
</TelemetryModules>
</ApplicationInsights>
注意
ApplicationInsights.config
中存在的确切模块集取决于安装的 SDK 包。
禁用遥测
在配置文件中,每个模块都有一个对应的节点。 要禁用某个模块,请删除该节点或将其注释掉。
遥测初始化表达式
若要使用其他信息来扩充遥测数据,或替代标准遥测模块设置的遥测属性,请使用遥测初始值设定项。
遥测初始值设定项设置连同每个遥测项一起发送的上下文属性。
可以编写自己的初始值设定项来设置上下文属性。
标准的初始值设定项均由 Web 或 WindowsServer NuGet 包设置:
初始化表达式 | DESCRIPTION |
---|---|
AccountIdTelemetryInitializer |
设置 AccountId 属性。 |
AuthenticatedUserIdTelemetryInitializer |
根据 JavaScript SDK 的设定来设置 AuthenticatedUserId 属性。 |
AzureRoleEnvironmentTelemetryInitializer |
对于包含从 Azure 运行时环境提取的信息的所有遥测项,更新 RoleName 上下文的 RoleInstance 和 Device 属性。 |
BuildInfoConfigComponentVersionTelemetryInitializer |
对于包含从 MS 版本生成的 Version 文件提取的值的所有遥测项,更新 Component 上下文的 BuildInfo.config 属性。 |
ClientIpHeaderTelemetryInitializer |
根据请求的 Ip HTTP 标头更新所有遥测项的 Location 上下文的 X-Forwarded-For 属性。 |
DeviceTelemetryInitializer |
更新所有遥测项的 Device 上下文的以下属性:• Type 设置为 PC 。• Id 设置为 Web 应用程序运行所在的计算机的域名。• OemName 设置为使用 WMI 从 Win32_ComputerSystem.Manufacturer 字段提取的值。• Model 设置为使用 WMI 从 Win32_ComputerSystem.Model 字段提取的值。• NetworkType 设置为从 NetworkInterface 属性中提取的值。• Language 设置为 CurrentCulture 属性的名称。 |
DomainNameRoleInstanceTelemetryInitializer |
对于包含 Web 应用程序运行所在计算机的域名的所有遥测项,更新 RoleInstance 上下文的 Device 属性。 |
OperationNameTelemetryInitializer |
根据 HTTP 方法、ASP.NET MVC 控制器的名称以及为了处理请求而调用的操作,更新所有遥测项的 Name 的 RequestTelemetry 属性,以及 Name 上下文的 Operation 属性。 |
OperationIdTelemetryInitializer 或 OperationCorrelationTelemetryInitializer |
在处理包含自动生成的 Operation.Id 的请求时,更新跟踪的所有遥测项的 RequestTelemetry.Id 上下文属性。 |
SessionTelemetryInitializer |
对于包含从用户浏览器中运行的 Id JavaScript 检测代码生成的 Session Cookie 提取的值的所有遥测项,更新 ai_session 上下文的 ApplicationInsights 属性。 |
SyntheticTelemetryInitializer 或 SyntheticUserAgentTelemetryInitializer |
在处理来自综合源(例如可用性测试或搜索引擎 Bot)的请求时,更新跟踪的所有遥测项的 User 、Session 和 Operation 上下文属性。 默认情况下,指标资源管理器不显示综合遥测数据。<Filters> 设置请求的标识属性。 |
UserTelemetryInitializer |
对于包含从用户浏览器中运行的 Application Insights JavaScript 检测代码生成的 Id Cookie 提取的值的所有遥测项,更新 AcquisitionDate 上下文的 User 和 ai_user 属性。 |
WebTestTelemetryInitializer |
设置用户 ID、会话 ID,以及来自可用性测试的 HTTP 请求的综合源属性。<Filters> 设置请求的标识属性。 |
注意
对于在 Azure Service Fabric 中运行的 .NET 应用程序,可包含 Microsoft.ApplicationInsights.ServiceFabric
NuGet 包。 该包所含的 FabricTelemetryInitializer
属性会将 Service Fabric 属性添加到遥测项。 有关详细信息,请参阅GitHub 页,了解由此 NuGet 包所添加的属性。
若要了解如何将遥测初始值设定项用于 ASP.NET,请参阅 Application Insights SDK 中的筛选器和预处理遥测。
遥测处理器
将遥测数据从 SDK 发送到门户之前,遥测处理器可以筛选和修改每个遥测项。
若要了解如何将遥测处理器用于 ASP.NET 应用程序,请参阅 Application Insights SDK 中的筛选器和预处理遥测。
可以编写自己的遥测处理器。
自适性采样遥测处理器(从 2.0.0-beta3 开始)
此功能默认处于启用状态。 如果应用程序要发送大量遥测数据,此处理器将删除某些遥测数据。
<TelemetryProcessors>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
<MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
</Add>
</TelemetryProcessors>
参数将提供算法尝试实现的目标。 SDK 的每个实例都独立工作。 因此,如果服务器是由多个计算机组成的群集,实际遥测量会相应地倍增。
了解有关采样的详细信息。
固定速率采样遥测处理器(从 2.0.0-beta1 开始)
还有一种标准的采样遥测处理器(从 2.0.1 开始):
<TelemetryProcessors>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.SamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
<!-- Set a percentage close to 100/N where N is an integer. -->
<!-- E.g. 50 (=100/2), 33.33 (=100/3), 25 (=100/4), 20, 1 (=100/100), 0.1 (=100/1000) -->
<SamplingPercentage>10</SamplingPercentage>
</Add>
</TelemetryProcessors>
连接字符串
此设置确定显示数据的 Application Insights 资源。 通常,我们会使用单独的连接字符串为每个应用程序单独创建一个资源。
有关代码示例,请参阅 Application Insights 中的连接字符串。
如果想要以动态方式设置连接字符串以实现特定的目的(例如,将应用程序的结果发送到不同的资源),则可在配置文件中省略连接字符串,改为在代码中设置它。
若为 TelemetryClient
的所有实例(包括标准遥测模块)设置连接字符串,请在初始化方法(例如 ASP.NET 服务中的 global.aspx.cs)中执行此步骤:
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights;
protected void Application_Start()
{
TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();
configuration.ConnectionString = "InstrumentationKey=00000000-0000-0000-0000-000000000000";
var telemetryClient = new TelemetryClient(configuration);
如果要将特定的一组事件发送到不同的资源,可以针对特定的遥测客户端设置密钥:
var tc = new TelemetryClient();
tc.Context.ConnectionString = "InstrumentationKey=00000000-0000-0000-0000-000000000000";
tc.TrackEvent("myEvent");
// ...
若要获取新连接字符串,请在 Application Insights 门户中创建新资源。
ApplicationId 提供程序
注意
对于 ASP.NET,该提供程序自 SDK v2.6.0 起可用。
此提供程序的用途是根据连接字符串查找应用程序 ID。 应用程序 ID 包含在 RequestTelemetry
和 DependencyTelemetry
中,用于在门户中确定关联。
此功能可通过设置 TelemetryConfiguration.ApplicationIdProvider
实现。
接口:IApplicationIdProvider
public interface IApplicationIdProvider
{
bool TryGetApplicationId(string instrumentationKey, out string applicationId);
}
我们在 Microsoft.ApplicationInsights SDK 中提供了两个实现:ApplicationInsightsApplicationIdProvider
和 DictionaryApplicationIdProvider
。
ApplicationInsightsApplicationIdProvider
这是用于我们的配置文件 API 的包装器。 它会限制请求和缓存结果。 安装 Microsoft.ApplicationInsights.DependencyCollector 或 Microsoft.ApplicationInsights.Web 时,会自动包含此提供程序。
该类公开了名为 ProfileQueryEndpoint
的可选属性。 默认情况下它设置为 https://dc.services.visualstudio.com/api/profiles/{0}/appId
。
如果需要配置代理,建议对基址进行代理,并确保路径包括 /api/profiles/{0}/appId
。 在运行时,{0}
会被替换为每个请求的检测密钥。
通过 ApplicationInsights.config 实现的示例配置
<ApplicationInsights>
...
<ApplicationIdProvider Type="Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId.ApplicationInsightsApplicationIdProvider, Microsoft.ApplicationInsights">
<ProfileQueryEndpoint>https://dc.services.visualstudio.com/api/profiles/{0}/appId</ProfileQueryEndpoint>
</ApplicationIdProvider>
...
</ApplicationInsights>
通过代码实现的示例配置
TelemetryConfiguration.Active.ApplicationIdProvider = new ApplicationInsightsApplicationIdProvider();
DictionaryApplicationIdProvider
此静态提供程序依赖于所配置的检测密钥/应用程序 ID 对。
此类具有 Defined
属性,该属性是检测密钥/应用程序 ID 对的 Dictionary<string,string>
。
此类有可选的 Next
属性,该属性可以用来配置当请求配置中不存在的连接字符串时要使用的其他提供程序。
通过 ApplicationInsights.config 实现的示例配置
<ApplicationInsights>
...
<ApplicationIdProvider Type="Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId.DictionaryApplicationIdProvider, Microsoft.ApplicationInsights">
<Defined>
<Type key="InstrumentationKey_1" value="ApplicationId_1"/>
<Type key="InstrumentationKey_2" value="ApplicationId_2"/>
</Defined>
<Next Type="Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId.ApplicationInsightsApplicationIdProvider, Microsoft.ApplicationInsights" />
</ApplicationIdProvider>
...
</ApplicationInsights>
通过代码实现的示例配置
TelemetryConfiguration.Active.ApplicationIdProvider = new DictionaryApplicationIdProvider{
Defined = new Dictionary<string, string>
{
{"InstrumentationKey_1", "ApplicationId_1"},
{"InstrumentationKey_2", "ApplicationId_2"}
}
};
配置快照收集
若要了解如何为 ASP.NET 和 ASP.NET Core 应用程序配置快照收集,请参阅在 Azure Service Fabric、云服务和虚拟机中为 .NET 应用启用 Snapshot Debugger。
采样
若要了解如何为 ASP.NET 和 ASP.NET 核心应用程序配置采样,请参阅 Application Insights 中的采样。
通过 HTTP 扩充数据
var requestTelemetry = HttpContext.Current?.Items["Microsoft.ApplicationInsights.RequestTelemetry"] as RequestTelemetry;
if (requestTelemetry != null)
{
requestTelemetry.Properties["myProp"] = "someData";
}
添加客户端监视
前面几个部分提供了有关自动和手动配置服务器端监视的方法的指导。 若要添加客户端监视,请使用客户端 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 for ASP.NET FAQ 和 Application Insights for ASP.NET Core FAQ。
- 验证是否正在运行受支持的 Application Insights SDK 版本 。
- 有关 Application Insights 的类型和数据模型,请参阅数据模型。
- 添加模拟事务,以通过可用性监视测试你的网站是否能从世界各地进行访问。
- 了解 Application Insights 中的遥测关联基础知识。
- 查看 System.Diagnostics.Activity 用户指南,了解如何关联遥测。
- 配置快照收集,以便在引发异常时查看源代码和变量的状态。
- 使用 API 发送自己的事件和指标,以获取应用性能和使用情况的详细视图。