在 Azure Application Insights 中跟踪依赖项Dependency Tracking in Azure Application Insights

依赖项是由应用程序调用的组件。A dependency is a component that is called by your application. 它通常是使用 HTTP、数据库或文件系统调用的服务。It's typically a service called using HTTP, or a database, or a file system. Application Insights 可以度量依赖项调用的持续时间、调用结果是否失败,以及依赖项名称等附加信息。Application Insights measures the duration of dependency calls, whether its failing or not, along with additional information like name of dependency and so on. 可以调查特定的依赖项调用,并将其与请求和异常相关联。You can investigate specific dependency calls, and correlate them to requests and exceptions.

自动跟踪的依赖项Automatically tracked dependencies

适用于 .NET 和 .NET Core 的 Application Insights SDK 随附了 DependencyTrackingTelemetryModule:一个自动收集依赖项的遥测模块。Application Insights SDKs for .NET and .NET Core ships with DependencyTrackingTelemetryModule, which is a Telemetry Module that automatically collects dependencies. 根据链接的官方文档进行配置后,将自动为 ASP.NETASP.NET Core 应用程序启用此依赖项收集功能。DependencyTrackingTelemetryModule 作为 NuGet 包附送,使用 NuGet 包 Microsoft.ApplicationInsights.WebMicrosoft.ApplicationInsights.AspNetCore 时会自动打开它。This dependency collection is enabled automatically for ASP.NET and ASP.NET Core applications, when configured as per the linked official docs. DependencyTrackingTelemetryModule is shipped as this NuGet package, and is brought automatically when using either of the NuGet packages Microsoft.ApplicationInsights.Web or Microsoft.ApplicationInsights.AspNetCore.

DependencyTrackingTelemetryModule 目前会自动跟踪以下依赖项:DependencyTrackingTelemetryModule currently tracks the following dependencies automatically:

依赖项Dependencies 详细信息Details
Http/HttpsHttp/Https 本地或远程 http/https 调用Local or Remote http/https calls
WCF 调用WCF calls 仅当使用基于 Http 的绑定时,才会自动跟踪。Only tracked automatically if Http-based bindings are used.
SQLSQL 使用 SqlClient 发出的调用。Calls made with SqlClient. 请参阅此文来捕获 SQL 查询。See this for capturing SQL query.
Azure 存储(Blob、表、队列)Azure storage (Blob, Table, Queue ) 使用 Azure 存储客户端发出的调用。Calls made with Azure Storage Client.
事件中心客户端 SDKEventHub Client SDK 1.1.0 和更高版本。Version 1.1.0 and above.
ServiceBus 客户端 SDKServiceBus Client SDK 3.0.0 和更高版本。Version 3.0.0 and above.
Azure Cosmos DBAzure Cosmos DB 仅当使用 HTTP/HTTPS 时,才会自动跟踪。Only tracked automatically if HTTP/HTTPS is used. Application Insights 不会捕获 TCP 模式。TCP mode won't be captured by Application Insights.

如果缺少某个依赖项,或使用其他 SDK,请确保它在自动收集的依赖项列表中。If you're missing a dependency, or using a different SDK make sure it's in the list of auto-collected dependencies. 如果依赖项不是自动收集的,仍可通过跟踪依赖项调用手动跟踪它。If the dependency isn't auto-collected, you can still track it manually with a track dependency call.

在控制台应用中设置自动依赖项跟踪Setup automatic dependency tracking in Console Apps

要从 .NET 控制台应用自动跟踪依赖项,请安装 NuGet 包 Microsoft.ApplicationInsights.DependencyCollector,并按如下所示初始化 DependencyTrackingTelemetryModuleTo automatically track dependencies from .NET console apps, install the NuGet package Microsoft.ApplicationInsights.DependencyCollector, and initialize DependencyTrackingTelemetryModule as follows:

    DependencyTrackingTelemetryModule depModule = new DependencyTrackingTelemetryModule();

对于 .NET Core 控制台应用,TelemetryConfiguration.Active 已过时。For .NET Core console apps TelemetryConfiguration.Active is obsolete. 请参阅辅助角色服务文档ASP.NET Core 监视文档中的指南Refer to the guidance in the worker service documentation and the ASP.NET Core monitoring documentation

自动依赖项监视的工作原理How automatic dependency monitoring works?

使用以下方法之一自动收集依赖项:Dependencies are automatically collected by using one of the following techniques:

  • 围绕 select 方法使用字节代码检测。Using byte code instrumentation around select methods. (StatusMonitor 或 Azure Web 应用扩展中的 InstrumentationEngine)(InstrumentationEngine either from StatusMonitor or Azure Web App Extension)
  • EventSource 回调EventSource callbacks
  • 最新 .NET/.NET Core SDK 中的 DiagnosticSource 回调DiagnosticSource callbacks (in the latest .NET/.NET Core SDKs)

手动跟踪依赖项Manually tracking dependencies

下面是不会自动收集的一些依赖项示例,需要手动跟踪它们。The following are some examples of dependencies, which aren't automatically collected, and hence require manual tracking.

  • 仅当使用 HTTP/HTTPS 时,才会自动跟踪 Azure Cosmos DB。Azure Cosmos DB is tracked automatically only if HTTP/HTTPS is used. Application Insights 不会捕获 TCP 模式。TCP mode won't be captured by Application Insights.
  • RedisRedis

对于 SDK 不会自动收集的依赖项,可以通过标准自动收集模块使用的 TrackDependency API 手动跟踪它们。For those dependencies not automatically collected by SDK, you can track them manually using the TrackDependency API that is used by the standard auto collection modules.

例如,如果使用未自行编写的程序集生成代码,可以对其所有调用进行计时,以了解它对响应时间所做的贡献。For example, if you build your code with an assembly that you didn't write yourself, you could time all the calls to it, to find out what contribution it makes to your response times. 若要使此数据显示在 Application Insights 中的依赖项图表中,请使用 TrackDependency 发送它。To have this data displayed in the dependency charts in Application Insights, send it using TrackDependency.

    var startTime = DateTime.UtcNow;
    var timer = System.Diagnostics.Stopwatch.StartNew();
        // making dependency call
        success = dependency.Call();
        telemetryClient.TrackDependency("myDependencyType", "myDependencyCall", "myDependencyData",  startTime, timer.Elapsed, success);

或者,可以使用 TelemetryClient 提供的扩展方法 StartOperationStopOperation 来手动跟踪依赖项,如此处所示Alternatively, TelemetryClient provides extension methods StartOperation and StopOperation which can be used to manually track dependencies, as shown here

若要关闭标准依赖项跟踪模块,请在 ASP.NET 应用程序的 ApplicationInsights.config 中删除对 DependencyTrackingTelemetryModule 的引用。If you want to switch off the standard dependency tracking module, remove the reference to DependencyTrackingTelemetryModule in ApplicationInsights.config for ASP.NET applications. 对于 ASP.NET Core 应用程序,请遵照此处的说明操作。For ASP.NET Core applications, follow instructions here.

跟踪来自网页的 AJAX 调用Tracking AJAX calls from Web Pages

对于网页,Application Insights JavaScript SDK 以依赖项的形式自动收集 AJAX 调用。For web pages, Application Insights JavaScript SDK automatically collects AJAX calls as dependencies.

使用高级 SQL 跟踪获取完整的 SQL 查询Advanced SQL tracking to get full SQL Query


Azure Functions 需要单独的设置才能启用 SQL 文本收集。有关详细信息,请参阅为 Azure Functions 配置监视Azure Functions requires separate settings to enable SQL text collection, see configure monitoring for Azure Functions to learn more.

对于 SQL 调用,始终会收集服务器和数据库的名称,并将其存储为收集的 DependencyTelemetry 的名称。For SQL calls, the name of the server and database is always collected and stored as name of the collected DependencyTelemetry. 有一个名为“data”的附加字段,其中可以包含完整的 SQL 查询文本。There's an additional field called 'data', which can contain the full SQL query text.

对于 ASP.NET Core 应用程序,现在需要通过使用以下命令来选择加入 SQL 文本收集For ASP.NET Core applications, It is now required to opt-in to SQL Text collection by using

services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>((module, o) => { module. EnableSqlCommandTextInstrumentation = true; });

对于 ASP.NET 应用程序,完整 SQL 查询文本是在字节代码检测的帮助下收集的,这需要使用检测引擎,或者使用 Microsoft.Data.SqlClient NuGet 包而不是 System.Data.SqlClient 库。For ASP.NET applications, full SQL query text is collected with the help of byte code instrumentation, which requires using the instrumentation engine or by using the Microsoft.Data.SqlClient NuGet package instead of the System.Data.SqlClient library. 下面介绍了启用完整 SQL 查询集合的平台特定步骤:Platform specific steps to enable full SQL Query collection are described below:

平台Platform 获取完整 SQL 查询所要执行的步骤Step(s) Needed to get full SQL Query
Azure Web 应用Azure Web App 在 Web 应用控制面板中,打开“Application Insights”边栏选项卡并启用“.NET”下的“SQL 命令”In your web app control panel, open the Application Insights blade and enable SQL Commands under .NET
IIS 服务器(Azure VM、本地服务器,等等。)IIS Server (Azure VM, on-prem, and so on.) 使用 Microsoft.Data.SqlClient NuGet 包或使用状态监视器 PowerShell 模块安装检测引擎并重启 IIS。Either use the Microsoft.Data.SqlClient NuGet package or use the Status Monitor PowerShell Module to install the Instrumentation Engine and restart IIS.
Azure 云服务Azure Cloud Service 添加启动任务以安装 StatusMonitorAdd startup task to install StatusMonitor
应通过为 ASP.NETASP.NET Core 应用程序安装 NuGet 包,在生成应用时将其加入 ApplicationInsights SDKYour app should be onboarded to ApplicationInsights SDK at build time by installing NuGet packages for ASP.NET or ASP.NET Core applications
IIS ExpressIIS Express 使用 Microsoft.Data.SqlClient NuGet 包。Use the Microsoft.Data.SqlClient NuGet package.
Azure Web 作业Azure Web Jobs 使用 Microsoft.Data.SqlClient NuGet 包。Use the Microsoft.Data.SqlClient NuGet package.

除了上述平台特定的步骤之外,还必须通过使用以下命令修改 applicationInsights.config 文件来显式选择启用 SQL 命令集合:In addition to the platform specific steps above, you must also explicitly opt-in to enable SQL command collection by modifying the applicationInsights.config file with the following:

  <Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector">

在上述情况下,验证是否已正确安装该检测引擎的适当方法是验证收集的 DependencyTelemetry 的 SDK 版本是否为“rddp”。In the above cases, the correct way of validating that instrumentation engine is correctly installed is by validating that the SDK version of collected DependencyTelemetry is 'rddp'. “rdddsd”或“rddf”表示依赖项是通过 DiagnosticSource 或 EventSource 回调收集的,因此不会捕获完整的 SQL 查询。'rdddsd' or 'rddf' indicates dependencies are collected via DiagnosticSource or EventSource callbacks, and hence full SQL query won't be captured.

在何处查找依赖项数据Where to find dependency data

  • 应用程序地图直观显示应用与相邻组件之间的依赖关系。Application Map visualizes dependencies between your app and neighboring components.
  • 事务诊断显示统一的关联服务器数据。Transaction Diagnostics shows unified, correlated server data.
  • “浏览器”选项卡显示从用户浏览器发出的 AJAX 调用。Browsers tab shows AJAX calls from your users' browsers.
  • 单击缓慢或失败的请求可以检查其依赖性调用。Click through from slow or failed requests to check their dependency calls.
  • Analytics 可用于查询依赖性数据。Analytics can be used to query dependency data.

诊断慢速请求Diagnose slow requests

每个请求事件都与应用处理请求时跟踪的依赖项调用、异常和其他事件相关联。Each request event is associated with the dependency calls, exceptions, and other events that are tracked while your app is processing the request. 因此,如果某些请求的执行状态不佳,可以判断其原因是否为某个依赖项的响应速度缓慢。So if some requests are doing badly, you can find out whether it's because of slow responses from a dependency.

从发往依赖项的请求开始跟踪Tracing from requests to dependencies

打开“性能”选项卡,导航到顶部的操作旁边的“依赖项”选项卡。Open the Performance tab and navigate to the Dependencies tab at the top next to operations.

单击整个选项卡下面的某个 依赖项名称Click on a Dependency Name under overall. 选择一个依赖项后,右侧会显示该依赖项的持续时间分布图。After you select a dependency a graph of that dependency's distribution of durations will show up on the right.


单击右下方的蓝色“示例”按钮,然后单击某个示例以查看端到端的事务详细信息。Click on the blue Samples button on the bottom right and then on a sample to see the end-to-end transaction details.


分析实时站点Profile your live site

不知道时间花到哪去了?No idea where the time goes? Application Insights 探查器将跟踪对实时站点的 HTTP 调用,并显示代码中有哪些函数花费了最长的时间。The Application Insights profiler traces HTTP calls to your live site and shows you the functions in your code that took the longest time.

失败的请求Failed requests

失败的请求还可能与依赖项的失败调用相关联。Failed requests might also be associated with failed calls to dependencies.

我们可以转到左侧的“失败”选项卡,然后单击顶部的“依赖项”选项卡。We can go to the Failures tab on the left and then click on the dependencies tab at the top.


在此处可以查看失败的依赖项计数。Here you will be able to see the failed dependency count. 若要获取有关某个失败依赖项的更多详细信息,请尝试单击底部表中的依赖项名称。To get more details about a failed occurrence trying clicking on a dependency name in the bottom table. 可以单击右下方的蓝色“依赖项”按钮获取端到端的事务详细信息。You can click on the blue Dependencies button at the bottom right to get the end-to-end transaction details.

日志(分析)Logs (Analytics)

可以跟踪 Kusto 查询语言中的依赖项。You can track dependencies in the Kusto query language. 下面是一些示例。Here are some examples.

  • 查找所有失败的依赖项调用:Find any failed dependency calls:

    dependencies | where success != "True" | take 10
  • 查找 AJAX 调用:Find AJAX calls:

    dependencies | where client_Type == "Browser" | take 10
  • 查找与请求关联的依赖项调用:Find dependency calls associated with requests:

    | where timestamp > ago(1d) and  client_Type != "Browser"
    | join (requests | where timestamp > ago(1d))
      on operation_Id  
  • 查找与页面视图关联的 AJAX 调用:Find AJAX calls associated with page views:

    | where timestamp > ago(1d) and  client_Type == "Browser"
    | join (browserTimings | where timestamp > ago(1d))
      on operation_Id

常见问题Frequently asked questions

自动依赖项收集器如何报告依赖项的失败调用?How does automatic dependency collector report failed calls to dependencies?

  • 失败依赖项调用的“success”字段设置为 False。Failed dependency calls will have 'success' field set to False. DependencyTrackingTelemetryModule 不会报告 ExceptionTelemetryDependencyTrackingTelemetryModule does not report ExceptionTelemetry. 此处介绍了依赖项的完整数据模型。The full data model for dependency is described here.

如何计算依赖项遥测的引入延迟?How do I calculate ingestion latency for my dependency telemetry?

| extend E2EIngestionLatency = ingestion_time() - timestamp 
| extend TimeIngested = ingestion_time()

如何确定启动依赖项调用的时间?How do I determine the time the dependency call was initiated?

在 Log Analytics“查询”视图中,timestamp 表示启动 TrackDependency() 调用的时刻,该时刻是在收到依赖项调用响应后立即发生的。In the Log Analytics query view timestamp represents the moment the TrackDependency() call was initiated which occurs immediately after the dependency call response is received. 若要计算依赖项调用的开始时间,需要获取 timestamp,然后减去记录的依赖项调用的 durationTo calculate the time when the dependency call began, you would take timestamp and subtract the recorded duration of the dependency call.

开源 SDKOpen-source SDK

与每个 Application Insights SDK 一样,依赖项收集模块也是开源的。Like every Application Insights SDK, dependency collection module is also open-source. 请在官方 GitHub 存储库中阅读和贡献代码,或者报告问题。Read and contribute to the code, or report issues at the official GitHub repo.

后续步骤Next steps