用于处理自定义事件和指标的 Application Insights APIApplication Insights API for custom events and metrics

在应用程序中插入几行代码,即可了解用户在该应用程序中执行的操作或帮助诊断问题。Insert a few lines of code in your application to find out what users are doing with it, or to help diagnose issues. 可以从设备和桌面应用、Web 客户端和 Web 服务器发送遥测数据。You can send telemetry from device and desktop apps, web clients, and web servers. 使用 Visual Studio Application Insights 核心遥测 API 发送自定义事件和指标,以及自己的标准遥测版本。Use the Azure Application Insights core telemetry API to send custom events and metrics, and your own versions of standard telemetry. 此 API 与标准 Application Insights 数据收集器使用的 API 相同。This API is the same API that the standard Application Insights data collectors use.

API 摘要API summary

核心 API 在所有平台中是统一的,只有少许差异,例如 GetMetric(仅限 .NET)。The core API is uniform across all platforms, apart from a few variations like GetMetric(.NET only).

方法Method 用途Used for
TrackPageView 页面、屏幕、边栏选项卡或窗体。Pages, screens, blades, or forms.
TrackEvent 用户操作和其他事件。User actions and other events. 用于跟踪用户行为或监视性能。Used to track user behavior or to monitor performance.
GetMetric 零维度和多维度指标,集中配置的聚合,仅限 C#。Zero and multi-dimensional metrics, centrally configured aggregation, C# only.
TrackMetric 性能度量,例如与特定事件不相关的队列长度。Performance measurements such as queue lengths not related to specific events.
TrackException 记录诊断的异常。Logging exceptions for diagnosis. 跟踪与其他事件的相关性,以及检查堆栈跟踪。Trace where they occur in relation to other events and examine stack traces.
TrackRequest 记录服务器请求的频率和持续时间以进行性能分析。Logging the frequency and duration of server requests for performance analysis.
TrackTrace 资源诊断日志消息。Resource Diagnostic log messages. 还可以捕获第三方日志。You can also capture third-party logs.
TrackDependency 记录对应用依赖的外部组件的调用持续时间和频率。Logging the duration and frequency of calls to external components that your app depends on.

可以将属性和指标附加到其中的大多数遥测调用。You can attach properties and metrics to most of these telemetry calls.

开始之前Before you start

如果还没有 Application Insights SDK 引用:If you don't have a reference on Application Insights SDK yet:

获取 TelemetryClient 实例Get a TelemetryClient instance

获取 TelemetryClient 的实例(网页中的 JavaScript 除外):Get an instance of TelemetryClient (except in JavaScript in webpages):

对于 ASP.NET Core 应用和用于 .NET/.NET Core 的非 HTTP/辅助角色,建议从依赖关系注入容器获取 TelemetryClient 的实例,如各自的相关文档中所述。For ASP.NET Core apps and Non HTTP/Worker for .NET/.NET Core apps, it is recommended to get an instance of TelemetryClient from the dependency injection container as explained in their respective documentation.

如果使用的是 AzureFunctions v2 及更高版本或 Azure WebJobs v3 及更高版本,请遵循以下文档:/azure-functions/functions-monitoring#version-2x-and-higherIf you use AzureFunctions v2+ or Azure WebJobs v3+ - follow this document: /azure-functions/functions-monitoring#version-2x-and-higher


private TelemetryClient telemetry = new TelemetryClient();

对于看到“此方法已过时”消息的任何人,请访问 microsoft/ApplicationInsights-dotnet#1152 了解更多详细信息。For anyone seeing this method is obsolete messages please visit microsoft/ApplicationInsights-dotnet#1152 for further details.

Visual BasicVisual Basic

Private Dim telemetry As New TelemetryClient


private TelemetryClient telemetry = new TelemetryClient();


var telemetry = applicationInsights.defaultClient;

TelemetryClient 是线程安全的。TelemetryClient is thread-safe.

对于 ASP.NET 和 Java 项目,可自动捕获传入的 HTTP 请求。For ASP.NET and Java projects, incoming HTTP Requests are automatically captured. 可能需要为应用的其他模块创建 TelemetryClient 的其他实例。You might want to create additional instances of TelemetryClient for other module of your app. 例如,可以在中间件类中使用一个 TelemetryClient 实例报告业务逻辑事件。For instance, you may have one TelemetryClient instance in your middleware class to report business logic events. 可以设置属性(如 UserId 和 DeviceId)来标识计算机。You can set properties such as UserId and DeviceId to identify the machine. 此信息将附加到实例发送的所有事件中。This information is attached to all events that the instance sends.


TelemetryClient.Context.User.Id = "...";
TelemetryClient.Context.Device.Id = "...";



在 Node.js 项目中,可以使用 new applicationInsights.TelemetryClient(instrumentationKey?) 创建新实例,但这建议仅用于需要与单一实例 defaultClient 隔离的配置的方案。In Node.js projects, you can use new applicationInsights.TelemetryClient(instrumentationKey?) to create a new instance, but this is recommended only for scenarios that require isolated configuration from the singleton defaultClient.


在 Application Insights 中,自定义事件是一个数据点,它可在指标资源管理器中显示为聚合计数,在诊断搜索中显示为单个事件。In Application Insights, a custom event is a data point that you can display in Metrics Explorer as an aggregated count, and in Diagnostic Search as individual occurrences. (它与 MVC 或其他框架“事件”不相关。)(It isn't related to MVC or other framework "events.")

在代码中插入 TrackEvent 调用来统计各种事件。Insert TrackEvent calls in your code to count various events. 用户选择特定功能的频率、实现特定目标的频率,或可能制造特定类型的错误的频率。How often users choose a particular feature, how often they achieve particular goals, or maybe how often they make particular types of mistakes.

例如,在游戏应用中,每当用户获胜时会发送事件:For example, in a game app, send an event whenever a user wins the game:





Visual BasicVisual Basic





telemetry.trackEvent({name: "WinGame"});

Analytics 中的自定义事件Custom events in Analytics

Application Insights AnalyticscustomEvents 表格提供了遥测。The telemetry is available in the customEvents table in Application Insights Analytics. 每行表示对应用中 trackEvent(..) 的调用。Each row represents a call to trackEvent(..) in your app.

如果正在进行采样,那么 itemCount 属性将显示大于 1 的值。If sampling is in operation, the itemCount property shows a value greater than 1. 例如,itemCount==10 表明对 trackEvent() 调用了 10 次,采样进程只传输其中一次。For example itemCount==10 means that of 10 calls to trackEvent(), the sampling process only transmitted one of them. 若要获取自定义事件的正确计数,应使用 customEvents | summarize sum(itemCount) 之类的代码。To get a correct count of custom events, you should therefore use code such as customEvents | summarize sum(itemCount).


若要了解如何有效地使用 GetMetric() 调用捕获 .NET 和 .NET Core 应用程序的本地预聚合指标,请访问 GetMetric 文档。To learn how to effectively use the GetMetric() call to capture locally pre-aggregated metrics for .NET and .NET Core applications visit the GetMetric documentation.



Microsoft.ApplicationInsights.TelemetryClient.TrackMetric 不是发送指标的首选方法。Microsoft.ApplicationInsights.TelemetryClient.TrackMetric is not the preferred method for sending metrics. 在发送之前,应当始终对一段时间内的指标进行预聚合。Metrics should always be pre-aggregated across a time period before being sent. 使用 GetMetric(..) 重载之一获取用于访问 SDK 预聚合功能的指标对象。Use one of the GetMetric(..) overloads to get a metric object for accessing SDK pre-aggregation capabilities. 如果要实现自己的预聚合逻辑,则可以使用 TrackMetric() 方法发送生成的聚合。If you are implementing your own pre-aggregation logic, you can use the TrackMetric() method to send the resulting aggregates. 如果应用程序需要在每种场合下发送单独的遥测项而不需要在整个时间段上进行聚合,那么你可能就有了一个事件遥测用例;请参阅 TelemetryClient.TrackEvent (Microsoft.ApplicationInsights.DataContracts.EventTelemetry)。If your application requires sending a separate telemetry item at every occasion without aggregation across time, you likely have a use case for event telemetry; see TelemetryClient.TrackEvent (Microsoft.ApplicationInsights.DataContracts.EventTelemetry).

Application Insights 可绘制未附加到特定事件的指标。Application Insights can chart metrics that are not attached to particular events. 例如,可以定期监视队列长度。For example, you could monitor a queue length at regular intervals. 对指标而言,变化和趋势比单个度量值更具价值,因此统计图表非常实用。With metrics, the individual measurements are of less interest than the variations and trends, and so statistical charts are useful.

若要将指标发送到 Application Insights,可以使用 TrackMetric(..) API。In order to send metrics to Application Insights, you can use the TrackMetric(..) API. 可通过两种方式发送指标:There are two ways to send a metric:

  • 单个值。Single value. 每次在应用中执行测量时,会发送相应的值到 Application Insights。Every time you perform a measurement in your application, you send the corresponding value to Application Insights. 例如,假设有个指标用于描述容器中项的数量。For example, assume that you have a metric describing the number of items in a container. 在特定时间段,先将 3 个项放入容器中,再从容器中移除 2 个项。During a particular time period, you first put three items into the container and then you remove two items. 相应地,将会调用 TrackMetric 两次:首先传递值 3,然后传递值 -2Accordingly, you would call TrackMetric twice: first passing the value 3 and then the value -2. Application Insights 会替你存储这两个值。Application Insights stores both values on your behalf.

  • 聚合。Aggregation. 使用指标时,每个单次测量几乎无关紧要。When working with metrics, every single measurement is rarely of interest. 反而特定时间段内发生活动的摘要很重要。Instead a summary of what happened during a particular time period is important. 此类摘要名为聚合。Such a summary is called aggregation. 在上一示例中,该时间段的聚合指标总数为 1,同时指标值的计数为 2In the above example, the aggregate metric sum for that time period is 1 and the count of the metric values is 2. 使用聚合方法时,每个时间段只调用一次 TrackMetric 并发送聚合值。When using the aggregation approach, you only invoke TrackMetric once per time period and send the aggregate values. 建议采用此方法是因为它可以通过发送更少的数据点到 Application Insights 同时仍然收集所有相关信息来显著降低成本和性能开销。This is the recommended approach since it can significantly reduce the cost and performance overhead by sending fewer data points to Application Insights, while still collecting all relevant information.


单个值Single values

发送单一指标值:To send a single metric value:


appInsights.trackMetric("queueLength", 42.0);


var sample = new MetricTelemetry();
sample.Name = "metric name";
sample.Value = 42.3;


telemetry.trackMetric("queueLength", 42.0);


telemetry.trackMetric({name: "queueLength", value: 42.0});

分析中的自定义指标Custom metrics in Analytics

Application Insights AnalyticscustomMetrics 表格提供了遥测。The telemetry is available in the customMetrics table in Application Insights Analytics. 每行表示对应用中 trackMetric(..) 的调用。Each row represents a call to trackMetric(..) in your app.

  • valueSum - 这是度量值的总和。valueSum - This is the sum of the measurements. 若要获取平均值,请除以 valueCountTo get the mean value, divide by valueCount.
  • valueCount - 聚合到此 trackMetric(..) 调用中的度量值个数。valueCount - The number of measurements that were aggregated into this trackMetric(..) call.

页面视图Page views

在设备或网页应用中,加载每个屏幕或页面时默认将发送页面视图遥测数据。In a device or webpage app, page view telemetry is sent by default when each screen or page is loaded. 但是,可以更改为在其他时间或不同时间跟踪页面视图。But you can change that to track page views at additional or different times. 例如,在显示选项卡或边栏选项卡的应用中,可以在用户每次打开新边栏选项卡时跟踪一个页面。For example, in an app that displays tabs or blades, you might want to track a page whenever the user opens a new blade.

用户和会话数据与页面视图作为属性一起发送,以便在有页面视图遥测数据时显示用户与会话图表。User and session data is sent as properties along with page views, so the user and session charts come alive when there is page view telemetry.

自定义页面视图Custom page views





Visual BasicVisual Basic




如果不同的 HTML 网页中有多个选项卡,还可以指定 URL:If you have several tabs within different HTML pages, you can specify the URL too:

appInsights.trackPageView("tab1", "http://fabrikam.com/page1.htm");

计时页面视图Timing page views

默认情况下,报告为“页面视图加载时间”的时间测量是从浏览器发送请求开始、调用浏览器的页面加载事件为止的时间。By default, the times reported as Page view load time are measured from when the browser sends the request, until the browser's page load event is called.

可以:Instead, you can either:

  • trackPageView 调用中设置显式持续时间:appInsights.trackPageView("tab1", null, null, null, durationInMilliseconds);Set an explicit duration in the trackPageView call: appInsights.trackPageView("tab1", null, null, null, durationInMilliseconds);.
  • 使用页面视图计时调用 startTrackPagestopTrackPageUse the page view timing calls startTrackPage and stopTrackPage.


// To start timing a page:


// To stop timing and log the page:
appInsights.stopTrackPage("Page1", url, properties, measurements);

用作第一个参数的名称会将开始调用与停止调用相关联。The name that you use as the first parameter associates the start and stop calls. 该名称默认为当前页面名称。It defaults to the current page name.

显示在指标资源管理器中的最终页面加载持续时间派生自开始调用与停止调用的间隔时间。The resulting page load durations displayed in Metrics Explorer are derived from the interval between the start and stop calls. 实际时间间隔由你决定。It's up to you what interval you actually time.

Analytics 中的页面遥测Page telemetry in Analytics

Analytics中有两个表展示了浏览器操作的数据:In Analytics two tables show data from browser operations:

  • pageViews 表包含关于 URL 和页标题的数据The pageViews table contains data about the URL and page title
  • browserTimings 表包含关于客户端性能的数据,例如处理传入数据所用的时间The browserTimings table contains data about client performance, such as the time taken to process the incoming data

查找浏览器处理不同页面需要的时间:To find how long the browser takes to process different pages:

| summarize avg(networkDuration), avg(processingDuration), avg(totalDuration) by name

发现不同浏览器的热门程度:To discover the popularities of different browsers:

| summarize count() by client_Browser

若要将页面视图关联到 AJAX 调用,请联接依赖项:To associate page views to AJAX calls, join with dependencies:

| join (dependencies) on operation_Id 


服务器 SDK 使用 TrackRequest 记录 HTTP 请求。The server SDK uses TrackRequest to log HTTP requests.

如果想要在没有 Web 服务模块运行的上下文中模拟请求,也可以自行调用。You can also call it yourself if you want to simulate requests in a context where you don't have the web service module running.

但是,发送请求遥测的建议方式是将请求用作操作上下文However, the recommended way to send request telemetry is where the request acts as an operation context.

操作上下文Operation context

可以通过将遥测项与操作上下文关联来将遥测项关联在一起。You can correlate telemetry items together by associating them with operation context. 标准的请求跟踪模块针对在处理 HTTP 请求时发送的异常和其他事件执行此操作。The standard request-tracking module does this for exceptions and other events that are sent while an HTTP request is being processed. 搜索分析中,可以使用操作 ID 轻松找到与请求关联的任何事件。In Search and Analytics, you can easily find any events associated with the request using its operation ID.

有关关联的更多详细信息,请参阅 Application Insights 中的遥测关联See Telemetry correlation in Application Insights for more details on correlation.

手动跟踪遥测时,使用此模式确保遥测关联的最简单方法:When tracking telemetry manually, the easiest way to ensure telemetry correlation by using this pattern:


// Establish an operation context and associated telemetry item:
using (var operation = telemetryClient.StartOperation<RequestTelemetry>("operationName"))
    // Telemetry sent in here will use the same operation ID.
    telemetryClient.TrackTrace(...); // or other Track* calls

    // Set properties of containing telemetry item--for example:
    operation.Telemetry.ResponseCode = "200";

    // Optional: explicitly send telemetry item:

} // When operation is disposed, telemetry item is sent.

除了设置操作上下文之外,StartOperation 还会创建一个所指定类型的遥测项。Along with setting an operation context, StartOperation creates a telemetry item of the type that you specify. 在处理操作时,或如果显式调用 StopOperation,它将发送遥测项。It sends the telemetry item when you dispose the operation, or if you explicitly call StopOperation. 如果使用 RequestTelemetry 作为遥测类型,其持续时间将设置为开始与停止的间隔时间。If you use RequestTelemetry as the telemetry type, its duration is set to the timed interval between start and stop.

在操作范围内报告的遥测项将成为此类操作的“子级”。Telemetry items reported within a scope of operation become 'children' of such operation. 操作上下文可以嵌套。Operation contexts could be nested.

在搜索中,操作上下文可用于创建“相关项”列表:In Search, the operation context is used to create the Related Items list:


有关自定义操作跟踪的详细信息,请参阅使用 Application Insights .NET SDK 跟踪自定义操作See Track custom operations with Application Insights .NET SDK for more information on custom operations tracking.

Analytics 中的请求Requests in Analytics

Application Insights Analytics 中,请求出现在 requests 表中。In Application Insights Analytics, requests show up in the requests table.

如果正在进行采样,那么 itemCount 属性将会显示大于 1 的值。If sampling is in operation, the itemCount property will show a value greater than 1. 例如,itemCount==10 表明对 trackRequest() 调用了 10 次,采样进程只传输其中一次。For example itemCount==10 means that of 10 calls to trackRequest(), the sampling process only transmitted one of them. 若要按请求名称获取正确的请求数和平均持续时间,请使用如下所示的代码:To get a correct count of requests and average duration segmented by request names, use code such as:

| summarize count = sum(itemCount), avgduration = avg(duration) by name


将异常发送到 Application Insights:Send exceptions to Application Insights:

报告包含堆栈跟踪。The reports include the stack traces.


catch (Exception ex)


try {
} catch (Exception ex) {


catch (ex)


catch (ex)
    telemetry.trackException({exception: ex});

SDK 会自动捕获许多异常,因此不一定需要显式调用 TrackException。The SDKs catch many exceptions automatically, so you don't always have to call TrackException explicitly.

    instrumentationKey: "your key",
    disableExceptionTracking: true

Analytics 中的异常Exceptions in Analytics

Application Insights Analytics 中,异常出现在 exceptions 表中。In Application Insights Analytics, exceptions show up in the exceptions table.

如果正在进行采样,那么 itemCount 属性将显示大于 1 的值。If sampling is in operation, the itemCount property shows a value greater than 1. 例如,itemCount==10 表明对 trackException() 调用了 10 次,采样进程只传输其中一次。For example itemCount==10 means that of 10 calls to trackException(), the sampling process only transmitted one of them. 若要按异常类型获取正确的异常数,请使用如下所示的代码:To get a correct count of exceptions segmented by type of exception, use code such as:

| summarize sum(itemCount) by type

虽然大部分重要的堆叠信息已提取到了单独的变量中,但可以扩展 details 结构,获取更多信息。Most of the important stack information is already extracted into separate variables, but you can pull apart the details structure to get more. 由于这个结构是动态的,应将结果转换为预期的类型。Since this structure is dynamic, you should cast the result to the type you expect. 例如:For example:

| extend method2 = tostring(details[0].parsedStack[1].method)

若要将异常与相关请求关联,请使用联接:To associate exceptions with their related requests, use a join:

| join (requests) on operation_Id


使用 TrackTrace 可以通过将“痕迹导航跟踪”发送到 Application Insights 来帮助诊断问题。Use TrackTrace to help diagnose problems by sending a "breadcrumb trail" to Application Insights. 可以发送诊断数据区块,并在诊断搜索中检查。You can send chunks of diagnostic data and inspect them in Diagnostic Search.

使用 .NET 时,日志适配器使用此 API 将第三方日志发送到门户。In .NET Log adapters use this API to send third-party logs to the portal.

使用 Java 时,标准记录器(如 Log4J、Logback)使用 Application Insights Log4j 或 Logback Appenders 将第三方日志发送到门户。In Java for Standard loggers like Log4J, Logback use Application Insights Log4j or Logback Appenders to send third-party logs to the portal.


telemetry.TrackTrace(message, SeverityLevel.Warning, properties);


telemetry.trackTrace(message, SeverityLevel.Warning, properties);


    message: message,
    severity: applicationInsights.Contracts.SeverityLevel.Warning,
    properties: properties

客户端/浏览器端 JavaScriptClient/Browser-side JavaScript

trackTrace(message: string, properties?: {[string]:string}, severityLevel?: SeverityLevel)

记录诊断事件,例如进入或离开某个方法。Log a diagnostic event such as entering or leaving a method.

参数Parameter 说明Description
message 诊断数据。Diagnostic data. 可以比名称长很多。Can be much longer than a name.
properties 字符串到字符串的映射:用于在门户中筛选异常的其他数据。Map of string to string: Additional data used to filter exceptions in the portal. 默认为空。Defaults to empty.
severityLevel 支持的值:SeverityLevel.tsSupported values: SeverityLevel.ts

可以搜索消息内容,但是(不同于属性值)无法在其中进行筛选。You can search on message content, but (unlike property values) you can't filter on it.

message 上的大小限制比属性上的限制高得多。The size limit on message is much higher than the limit on properties. TrackTrace 的一个优势是可将相对较长的数据放置在消息中。An advantage of TrackTrace is that you can put relatively long data in the message. 例如,可在此处对 POST 数据进行编码。For example, you can encode POST data there.

此外,可向消息添加严重性级别。In addition, you can add a severity level to your message. 并像其他遥测一样,可以添加属性值以帮助筛选或搜索不同跟踪集。And, like other telemetry, you can add property values to help you filter or search for different sets of traces. 例如:For example:


var telemetry = new Microsoft.ApplicationInsights.TelemetryClient();
telemetry.TrackTrace("Slow database response",
                new Dictionary<string,string> { {"database", db.ID} });


Map<String, Integer> properties = new HashMap<>();
properties.put("Database", db.ID);
telemetry.trackTrace("Slow Database response", SeverityLevel.Warning, properties);

搜索中,可轻松筛选出与特定数据库相关的所有特定严重性级别的消息。In Search, you can then easily filter out all the messages of a particular severity level that relate to a particular database.

Analytics 中的跟踪Traces in Analytics

Application Insights Analytics 中,对 TrackTrace 的调用出现在 traces 表中。In Application Insights Analytics, calls to TrackTrace show up in the traces table.

如果正在进行采样,那么 itemCount 属性将显示大于 1 的值。If sampling is in operation, the itemCount property shows a value greater than 1. 例如,itemCount==10 表明对 trackTrace() 调用了 10 次,采样进程只传输其中一次。For example itemCount==10 means that of 10 calls to trackTrace(), the sampling process only transmitted one of them. 若要获取正确的跟踪调用数,应使用 traces | summarize sum(itemCount) 之类的代码。To get a correct count of trace calls, you should use therefore code such as traces | summarize sum(itemCount).


可使用 TrackDependency 调用跟踪响应时间以及调用外部代码片段的成功率。Use the TrackDependency call to track the response times and success rates of calls to an external piece of code. 结果会显示在门户上的依赖项图表中。The results appear in the dependency charts in the portal. 需要在进行依赖项调用的任何位置添加以下代码片段。The code snippet below needs to be added wherever a dependency call is made.


var success = false;
var startTime = DateTime.UtcNow;
var timer = System.Diagnostics.Stopwatch.StartNew();
    success = dependency.Call();
catch(Exception ex) 
    success = false;
    throw new Exception("Operation went wrong", ex);
    telemetry.TrackDependency("DependencyType", "myDependency", "myCall", startTime, timer.Elapsed, success);


boolean success = false;
Instant startTime = Instant.now();
try {
    success = dependency.call();
finally {
    Instant endTime = Instant.now();
    Duration delta = Duration.between(startTime, endTime);
    RemoteDependencyTelemetry dependencyTelemetry = new RemoteDependencyTelemetry("My Dependency", "myCall", delta, success);


var success = false;
var startTime = new Date().getTime();
    success = dependency.Call();
    var elapsed = new Date() - startTime;
        dependencyTypeName: "myDependency",
        name: "myCall",
        duration: elapsed,
        success: success

请记住,服务器 SDK 包含依赖项模块,用于自动发现和跟踪特定的依赖项调用(例如,数据库和 REST API)。Remember that the server SDKs include a dependency module that discovers and tracks certain dependency calls automatically--for example, to databases and REST APIs. 必须在服务器上安装一个代理才能让模块正常运行。You have to install an agent on your server to make the module work.

使用 Java 时,可以使用 Java 代理自动跟踪某些依赖项调用。In Java, certain dependency calls can be automatically tracked using Java Agent.

如果想要跟踪自动跟踪未捕获的调用,或不想安装代理,可以使用此调用。You use this call if you want to track calls that the automated tracking doesn't catch, or if you don't want to install the agent.

要关闭 C# 中的标准依赖项跟踪模块,请编辑 ApplicationInsights.config 并删除对 DependencyCollector.DependencyTrackingTelemetryModule 的引用。To turn off the standard dependency-tracking module in C#, edit ApplicationInsights.config and delete the reference to DependencyCollector.DependencyTrackingTelemetryModule. 使用 Java 时,如果不希望自动收集标准依赖项,请勿安装 java 代理。In Java, please do not install java agent if you do not want to collect standard dependencies automatically.

Analytics 中的依赖项Dependencies in Analytics

Application Insights Analytics 中,trackDependency 调用出现在 dependencies 表中。In Application Insights Analytics, trackDependency calls show up in the dependencies table.

如果正在进行采样,那么 itemCount 属性将显示大于 1 的值。If sampling is in operation, the itemCount property shows a value greater than 1. 例如,itemCount==10 表明对 trackDependency() 调用了 10 次,采样进程只传输其中一次。For example itemCount==10 means that of 10 calls to trackDependency(), the sampling process only transmitted one of them. 若要按目标组件获取正确的依赖项数,请使用如下所示的代码:To get a correct count of dependencies segmented by target component, use code such as:

| summarize sum(itemCount) by target

若要将依赖项与相关请求关联,请使用联接:To associate dependencies with their related requests, use a join:

| join (requests) on operation_Id

刷新数据Flushing data

通常,SDK 以固定的间隔(通常为 30 秒)或每当缓冲区已满(通常为 500 项)时发送数据。Normally, the SDK sends data at fixed intervals (typically 30 secs) or whenever buffer is full (typically 500 items). 但是,在某些情况下,可能需要刷新缓冲区,例如,在关闭的应用程序中使用 SDK 时。However, in some cases, you might want to flush the buffer--for example, if you are using the SDK in an application that shuts down.


// Allow some time for flushing before shutdown.


//Allow some time for flushing before shutting down



服务器遥测通道的函数是异步的。The function is asynchronous for the server telemetry channel.

理想情况下,应在应用程序的关闭活动中使用 flush() 方法。Ideally, flush() method should be used in the shutdown activity of the Application.

经过身份验证的用户Authenticated users

在 Web 应用中,默认按 Cookie 标识用户In a web app, users are (by default) identified by cookies. 如果用户从不同的计算机或浏览器访问应用或删除 Cookie,则可能会多次统计它们。A user might be counted more than once if they access your app from a different machine or browser, or if they delete cookies.

如果用户登录到应用,可以通过在浏览器代码中设置经过身份验证的用户 ID 来获取更准确的计数:If users sign in to your app, you can get a more accurate count by setting the authenticated user ID in the browser code:


// Called when my app has identified the user.
function Authenticated(signInId) {
    var validatedId = signInId.replace(/[,;=| ]+/g, "_");

例如,在 ASP.NET Web MVC 应用程序中:In an ASP.NET web MVC application, for example:


@if (Request.IsAuthenticated)
            .Replace("\\", "\\\\")"
            .replace(/[,;=| ]+/g, "_"));

不需要使用用户的实际登录名。It isn't necessary to use the user's actual sign-in name. 只需使用该用户的唯一 ID 即可。It only has to be an ID that is unique to that user. 该 ID 不能包含空格或任何 ,;=| 字符。It must not include spaces or any of the characters ,;=|.

还可在会话 Cookie 中设置用户 ID 并将其发送到服务器。The user ID is also set in a session cookie and sent to the server. 如果安装了服务器 SDK,则经过身份验证的用户 ID 将作为客户端和服务器遥测上下文属性的一部分发送。If the server SDK is installed, the authenticated user ID is sent as part of the context properties of both client and server telemetry. 可对其进行筛选和搜索。You can then filter and search on it.

如果应用将用户分组到帐户,则还可以传递该帐户的标识符(具有相同的字符限制)。If your app groups users into accounts, you can also pass an identifier for the account (with the same character restrictions).

appInsights.setAuthenticatedUserContext(validatedId, accountId);

指标资源管理器中,可以创建统计“经身份验证的用户”和“用户帐户”的图表。 In Metrics Explorer, you can create a chart that counts Users, Authenticated, and User accounts.

还可以搜索具有特定用户名和帐户的客户端数据点。You can also Search for client data points with specific user names and accounts.

使用属性筛选、搜索和细分数据Filtering, searching, and segmenting your data by using properties

可以将属性和度量值附加到事件(以及指标、页面视图、异常和其他遥测数据)。You can attach properties and measurements to your events (and also to metrics, page views, exceptions, and other telemetry data).

属性 是可以在使用情况报告中用来筛选遥测数据的字符串值。Properties are string values that you can use to filter your telemetry in the usage reports. 例如,如果应用提供多种游戏,可以将游戏的名称附加到每个事件,了解哪些游戏更受欢迎。For example, if your app provides several games, you can attach the name of the game to each event so that you can see which games are more popular.

字符串长度限制为 8192。There's a limit of 8192 on the string length. (如果想要发送大型数据区块,请使用消息参数 TrackTrace。)(If you want to send large chunks of data, use the message parameter of TrackTrace.)

指标 是能够以图形方式呈现的数字值。Metrics are numeric values that can be presented graphically. 例如,可以查看玩家的分数是否逐渐增加。For example, you might want to see if there's a gradual increase in the scores that your gamers achieve. 可以根据连同事件一起发送的属性对图表进行分段,以便获取不同游戏的独立图形或堆积图。The graphs can be segmented by the properties that are sent with the event, so that you can get separate or stacked graphs for different games.

这些值应大于或等于 0,以便正确显示指标值。For metric values to be correctly displayed, they should be greater than or equal to 0.

对属性、属性值和指标的数目使用一些限制There are some limits on the number of properties, property values, and metrics that you can use.


        // String properties:
        {Game: currentGame.name, Difficulty: currentGame.difficulty},
        // Numeric metrics:
        {Score: currentGame.score, Opponents: currentGame.opponentCount}

    ("page name", "http://fabrikam.com/pageurl.html",
        // String properties:
        {Game: currentGame.name, Difficulty: currentGame.difficulty},
        // Numeric metrics:
        {Score: currentGame.score, Opponents: currentGame.opponentCount}


// Set up some properties and metrics:
var properties = new Dictionary <string, string>
    {{"game", currentGame.Name}, {"difficulty", currentGame.Difficulty}};
var metrics = new Dictionary <string, double>
    {{"Score", currentGame.Score}, {"Opponents", currentGame.OpponentCount}};

// Send the event:
telemetry.TrackEvent("WinGame", properties, metrics);


// Set up some properties and metrics:
var properties = {"game": currentGame.Name, "difficulty": currentGame.Difficulty};
var metrics = {"Score": currentGame.Score, "Opponents": currentGame.OpponentCount};

// Send the event:
telemetry.trackEvent({name: "WinGame", properties: properties, measurements: metrics});

Visual BasicVisual Basic

' Set up some properties:
Dim properties = New Dictionary (Of String, String)
properties.Add("game", currentGame.Name)
properties.Add("difficulty", currentGame.Difficulty)

Dim metrics = New Dictionary (Of String, Double)
metrics.Add("Score", currentGame.Score)
metrics.Add("Opponents", currentGame.OpponentCount)

' Send the event:
telemetry.TrackEvent("WinGame", properties, metrics)


Map<String, String> properties = new HashMap<String, String>();
properties.put("game", currentGame.getName());
properties.put("difficulty", currentGame.getDifficulty());

Map<String, Double> metrics = new HashMap<String, Double>();
metrics.put("Score", currentGame.getScore());
metrics.put("Opponents", currentGame.getOpponentCount());

telemetry.trackEvent("WinGame", properties, metrics);


请注意不要在属性中记录个人身份信息。Take care not to log personally identifiable information in properties.

设置属性和指标的替代方法Alternative way to set properties and metrics

如果更方便的话,可以收集不同对象中的事件的参数:If it's more convenient, you can collect the parameters of an event in a separate object:

var event = new EventTelemetry();

event.Name = "WinGame";
event.Metrics["processingTime"] = stopwatch.Elapsed.TotalMilliseconds;
event.Properties["game"] = currentGame.Name;
event.Properties["difficulty"] = currentGame.Difficulty;
event.Metrics["Score"] = currentGame.Score;
event.Metrics["Opponents"] = currentGame.Opponents.Length;



请不要重复使用相同的遥测项实例(本示例中为 event)来调用 Track*() 多次。Don't reuse the same telemetry item instance (event in this example) to call Track*() multiple times. 这可能会导致使用不正确的配置发送遥测数据。This may cause telemetry to be sent with incorrect configuration.

在 Analytics 中自定义度量值和属性Custom measurements and properties in Analytics

Analytics 中,自定义指标和属性显示在每个遥测记录的 customMeasurementscustomDimensions 属性中。In Analytics, custom metrics and properties show in the customMeasurements and customDimensions attributes of each telemetry record.

例如,如果已向请求遥测添加名为“game”的属性,此查询将计算“game”不同值的出现次数,同时显示自定义指标“score”的平均值:For example, if you have added a property named "game" to your request telemetry, this query counts the occurrences of different values of "game", and show the average of the custom metric "score":

| summarize sum(itemCount), avg(todouble(customMeasurements.score)) by tostring(customDimensions.game)

请注意:Notice that:

  • 从 customDimensions 或 customMeasurements JSON 中提取值的时候,会有动态类型,所以必须将其转换为 tostringtodoubleWhen you extract a value from the customDimensions or customMeasurements JSON, it has dynamic type, and so you must cast it tostring or todouble.
  • 考虑到采样的可能性,需要使用 sum(itemCount) 而非 count()To take account of the possibility of sampling, you should use sum(itemCount), not count().

计时事件Timing events

有时,需要绘制图表来呈现执行某个操作花费了多少时间。Sometimes you want to chart how long it takes to perform an action. 例如,你可能想要知道用户在游戏中考虑如何选择时花费了多少时间。For example, you might want to know how long users take to consider choices in a game. 为此,可以使用度量参数。You can use the measurement parameter for this.


var stopwatch = System.Diagnostics.Stopwatch.StartNew();

// ... perform the timed action ...


var metrics = new Dictionary <string, double>
    {{"processingTime", stopwatch.Elapsed.TotalMilliseconds}};

// Set up some properties:
var properties = new Dictionary <string, string>
    {{"signalSource", currentSignalSource.Name}};

// Send the event:
telemetry.TrackEvent("SignalProcessed", properties, metrics);


long startTime = System.currentTimeMillis();

// Perform timed action

long endTime = System.currentTimeMillis();
Map<String, Double> metrics = new HashMap<>();
metrics.put("ProcessingTime", (double)endTime-startTime);

// Setup some properties
Map<String, String> properties = new HashMap<>();
properties.put("signalSource", currentSignalSource.getName());

// Send the event
telemetry.trackEvent("SignalProcessed", properties, metrics);

自定义遥测的默认属性Default properties for custom telemetry

如果想要为编写的一些自定义事件设置默认属性值,可以在 TelemetryClient 实例中设置。If you want to set default property values for some of the custom events that you write, you can set them in a TelemetryClient instance. 这些值将附加到从该客户端发送的每个遥测项。They are attached to every telemetry item that's sent from that client.


using Microsoft.ApplicationInsights.DataContracts;

var gameTelemetry = new TelemetryClient();
gameTelemetry.Context.GlobalProperties["Game"] = currentGame.Name;
// Now all telemetry will automatically be sent with the context property:

Visual BasicVisual Basic

Dim gameTelemetry = New TelemetryClient()
gameTelemetry.Context.GlobalProperties("Game") = currentGame.Name
' Now all telemetry will automatically be sent with the context property:


import com.microsoft.applicationinsights.TelemetryClient;
import com.microsoft.applicationinsights.TelemetryContext;

TelemetryClient gameTelemetry = new TelemetryClient();
TelemetryContext context = gameTelemetry.getContext();
context.getProperties().put("Game", currentGame.Name);



var gameTelemetry = new applicationInsights.TelemetryClient();
gameTelemetry.commonProperties["Game"] = currentGame.Name;

gameTelemetry.TrackEvent({name: "WinGame"});

单个遥测调用可以重写其属性字典中的默认值。Individual telemetry calls can override the default values in their property dictionaries.

对于 JavaScript Web 客户端,请使用 JavaScript 遥测初始化表达式。For JavaScript web clients, use JavaScript telemetry initializers.

若要向所有遥测数据(包括来自标准收集模块的数据)添加属性,请实现 ITelemetryInitializerTo add properties to all telemetry, including the data from standard collection modules, implement ITelemetryInitializer.

采样、筛选和处理遥测数据Sampling, filtering, and processing telemetry

可以先通过编写代码来处理遥测数据,再从 SDK 发送该数据。You can write code to process your telemetry before it's sent from the SDK. 处理包括从标准遥测模块(如 HTTP 请求收集和依赖项收集)发送的数据。The processing includes data that's sent from the standard telemetry modules, such as HTTP request collection and dependency collection.

通过实现 ITelemetryInitializer将属性添加到遥测。Add properties to telemetry by implementing ITelemetryInitializer. 例如,可添加版本号或从其他属性计算得出的值。For example, you can add version numbers or values that are calculated from other properties.

筛选可以先修改或丢弃遥测数据,然后通过实现 ITelemetryProcessor 从 SDK 发送遥测数据。Filtering can modify or discard telemetry before it's sent from the SDK by implementing ITelemetryProcessor. 可以控制要发送或丢弃的项,但必须考虑到这会给指标造成怎样的影响。You control what is sent or discarded, but you have to account for the effect on your metrics. 根据丢弃项的方式,有时你可能无法在相关项之间导航。Depending on how you discard items, you might lose the ability to navigate between related items.

采样是减少从应用发送到门户的数据量的打包解决方案。Sampling is a packaged solution to reduce the volume of data that's sent from your app to the portal. 它不会影响显示的指标。It does so without affecting the displayed metrics. 且不影响通过在相关项(如异常、请求和页面视图)之间导航来诊断问题。And it does so without affecting your ability to diagnose problems by navigating between related items such as exceptions, requests, and page views.

了解详细信息Learn more.

禁用遥测Disabling telemetry

动态停止和启动 收集与传输遥测数据:To dynamically stop and start the collection and transmission of telemetry:


using  Microsoft.ApplicationInsights.Extensibility;

TelemetryConfiguration.Active.DisableTelemetry = true;



若要 禁用选定的标准收集器(例如性能计数器、HTTP 请求或依赖项),请删除或注释掉 ApplicationInsights.config 中的相关行。例如,如果想要发送自己的 TrackRequest 数据,则可以这样做。To disable selected standard collectors--for example, performance counters, HTTP requests, or dependencies--delete or comment out the relevant lines in ApplicationInsights.config. You can do this, for example, if you want to send your own TrackRequest data.


telemetry.config.disableAppInsights = true;

若要 禁用所选的标准收集器(例如,性能计数器、HTTP 请求或依赖项),初始化时请将配置方法链接到 SDK 初始化代码:To disable selected standard collectors--for example, performance counters, HTTP requests, or dependencies--at initialization time, chain configuration methods to your SDK initialization code:


若要在初始化后禁用这些收集器,请使用配置对象:applicationInsights.Configuration.setAutoCollectRequests(false)To disable these collectors after initialization, use the Configuration object: applicationInsights.Configuration.setAutoCollectRequests(false)

开发人员模式Developer mode

在调试期间,通过管道加速遥测会很有效,这样可以立即看到结果。During debugging, it's useful to have your telemetry expedited through the pipeline so that you can see results immediately. 此外,还可以获得其他消息来帮助跟踪任何遥测问题。You also get additional messages that help you trace any problems with the telemetry. 在生产环境中请关闭此模式,因为它可能会拖慢应用。Switch it off in production, because it may slow down your app.


TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = true;

Visual BasicVisual Basic

TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = True


对于 Node.js,可以启用开发人员模式,方法是通过 setInternalLogging 启用内部日志记录,并将 maxBatchSize 设置为 0,从而在收集到遥测数据后立即发送。For Node.js, you can enable developer mode by enabling internal logging via setInternalLogging and setting maxBatchSize to 0, which causes your telemetry to be sent as soon as it is collected.

  .setInternalLogging(true, true)
applicationInsights.defaultClient.config.maxBatchSize = 0;

设置所选自定义遥测的检测密钥Setting the instrumentation key for selected custom telemetry


var telemetry = new TelemetryClient();
telemetry.InstrumentationKey = "---my key---";
// ...

动态检测密钥Dynamic instrumentation key

若要避免混合来自开发、测试和生产环境的遥测,可以创建单独的 Application Insights 资源,并根据环境更改其密钥。To avoid mixing up telemetry from development, test, and production environments, you can create separate Application Insights resources and change their keys, depending on the environment.

无需从配置文件获取检测密钥,可以在代码中设置密钥。Instead of getting the instrumentation key from the configuration file, you can set it in your code. 在初始化方法中设置密钥,如 ASP.NET 服务中的 global.aspx.cs:Set the key in an initialization method, such as global.aspx.cs in an ASP.NET service:


protected void Application_Start()
    TelemetryConfiguration.Active.InstrumentationKey =
        // - for example -


appInsights.config.instrumentationKey = myKey;

在网页中,可能需要通过 Web 服务器的状态设置密钥,而不是以文本方式将它编码到脚本中。In webpages, you might want to set it from the web server's state, rather than coding it literally into the script. 例如,在 ASP.NET 应用中生成的网页中:For example, in a webpage generated in an ASP.NET app:

使用 Razor 的 JavaScriptJavaScript in Razor

<script type="text/javascript">
// Standard Application Insights webpage script:
var appInsights = window.appInsights || function(config){ ...
// Modify this part:
    // Generate from server property:
}) // ...
    String instrumentationKey = "00000000-0000-0000-0000-000000000000";

    if (instrumentationKey != null)


TelemetryClient 具有上下文属性,其中包含与所有遥测数据一起发送的值。TelemetryClient has a Context property, which contains values that are sent along with all telemetry data. 它们通常由标准遥测模块设置,但你也可以自行设置。They are normally set by the standard telemetry modules, but you can also set them yourself. 例如:For example:

telemetry.Context.Operation.Name = "MyOperationName";

如果自行设置这些值,请考虑从 ApplicationInsights.config 中删除相关的代码行,以便值与标准值不会造成混淆。If you set any of these values yourself, consider removing the relevant line from ApplicationInsights.config, so that your values and the standard values don't get confused.

  • Component:应用及其版本。Component: The app and its version.
  • Device:有关正在运行应用的设备的数据。Device: Data about the device where the app is running. (在 Web 应用中,是指从其中发送遥测的服务器或客户端设备。)(In web apps, this is the server or client device that the telemetry is sent from.)
  • InstrumentationKey:Azure 中显示遥测数据的 Application Insights 资源。InstrumentationKey: The Application Insights resource in Azure where the telemetry appears. 通常可从 ApplicationInsights.config 中选择。It's usually picked up from ApplicationInsights.config.
  • 位置:设备的地理位置。Location: The geographic location of the device.
  • Operation:在 Web 应用中,为当前的 HTTP 请求。Operation: In web apps, the current HTTP request. 在其他应用类型中,可将此属性设置为将事件分组在一起。In other app types, you can set this to group events together.
    • ID:一个生成的值,它将不同的事件关联在一起,以便在诊断搜索中检查任何事件时,可以发现相关项。ID: A generated value that correlates different events, so that when you inspect any event in Diagnostic Search, you can find related items.
    • 名称:一个标识符,通常是 HTTP 请求的 URL。Name: An identifier, usually the URL of the HTTP request.
    • SyntheticSource:如果不为 null 或空,则此字符串表示请求的源已标识为机器人或 Web 测试。SyntheticSource: If not null or empty, a string that indicates that the source of the request has been identified as a robot or web test. 默认情况下,该属性会从指标资源管理器的计算中排除。By default, it is excluded from calculations in Metrics Explorer.
  • 属性:与所有遥测数据一起发送的属性。Properties: Properties that are sent with all telemetry data. 可在单个 Track* 调用中重写。It can be overridden in individual Track* calls.
  • 会话一致性:用户的会话。Session: The user's session. ID 设置为生成的值,当用户有一段时间处于非活动状态时,此值会更改。The ID is set to a generated value, which is changed when the user has not been active for a while.
  • 用户:用户信息。User: User information.


每个应用程序(即每个检测密钥)的指标和事件数都有一些限制。There are some limits on the number of metrics and events per application, that is, per instrumentation key. 限制取决于选择的定价计划Limits depend on the pricing plan that you choose.

ResourceResource 默认限制Default limit 注意Note
每日的总数据量Total data per day 100 GB100 GB 可以通过设置一个上限来减少数据。You can reduce data by setting a cap. 如果需要更多数据,可以在门户中最多将上限提高到 1,000 GB。If you need more data, you can increase the limit in the portal, up to 1,000 GB. 容量大于 1,000 GB,将发送电子邮件发送到AIDataCap@microsoft.com。For capacities greater than 1,000 GB, send email to AIDataCap@microsoft.com.
限制Throttling 32,000 事件/秒32,000 events/second 限制按分钟计量。The limit is measured over a minute.
数据保留Data retention 90 天90 days 此资源适用于搜索分析指标资源管理器This resource is for Search, Analytics.
90 天90 days 此资源提供了每个步骤的详细结果。This resource provides detailed results of each step.
最大事件大小Maximum event size 64,00064,000
属性和指标名称长度Property and metric name length 150150 请参阅类型架构See type schemas.
属性值字符串长度Property value string length 8,1928,192 请参阅类型架构See type schemas.
跟踪和异常消息长度Trace and exception message length 32,76832,768 请参阅类型架构See type schemas.
每个应用的可用性测试计数Availability tests count per app 100100

有关详细信息,请参阅关于 Application Insights 中的定价和配额For more information, see About pricing and quotas in Application Insights.

若要避免达到数据速率限制,请使用采样To avoid hitting the data rate limit, use sampling.

若要确定保留数据的时间期限,请参阅数据保留和隐私To determine how long data is kept, see Data retention and privacy.

参考文档Reference docs

SDK 代码SDK code


  • Track_() 调用可能会引发哪些异常?What exceptions might Track_() calls throw?

    无。None. 不需要将它们包装在 try-catch 子句中。You don't need to wrap them in try-catch clauses. 如果 SDK 遇到问题,它会在调试控制台输出中记录消息,如果消息已传入,可在诊断搜索中查看。If the SDK encounters problems, it will log messages in the debug console output and--if the messages get through--in Diagnostic Search.

  • 是否可以使用某个 REST API 从门户获取数据?Is there a REST API to get data from the portal?

    是的,可以使用数据访问 APIYes, the data access API. 提取数据的其他方法包括从 Analytics 导出到 Power BI连续导出Other ways to extract data include export from Analytics to Power BI and continuous export.

后续步骤Next steps