实时指标流:以 1 秒的延迟进行监视和诊断Live Metrics Stream: Monitor & Diagnose with 1-second latency

使用 Application Insights 中的实时指标流(也称为 QuickPulse)来监视生产环境中的实时 Web 应用。Monitor your live, in-production web application by using Live Metrics Stream (also known as QuickPulse) from Application Insights. 选择并筛选指标和性能计数器进行实时监视,且服务不会受到任何干扰。Select and filter metrics and performance counters to watch in real time, without any disturbance to your service. 从失败请求和异常的样本中检查堆栈跟踪。Inspect stack traces from sample failed requests and exceptions. 实时指标流与探查器快照调试程序一同为实时网站提供了功能强大的非入侵式诊断工具。Together with Profiler and Snapshot debugger, Live Metrics Stream provides a powerful and non-invasive diagnostic tool for your live web site.

使用实时指标流可实现以下操作:With Live Metrics Stream, you can:

  • 通过监视性能和故障计数,在修补程序发布时对其进行验证。Validate a fix while it is released, by watching performance and failure counts.
  • 监视负载测试的效果,实时诊断问题。Watch the effect of test loads, and diagnose issues live.
  • 通过选择和筛选想要监视的指标,重点处理特定的测试会话或筛选出已知问题。Focus on particular test sessions or filter out known issues, by selecting and filtering the metrics you want to watch.
  • 发生异常时获取异常跟踪。Get exception traces as they happen.
  • 试用筛选器,查找最相关的 KPI。Experiment with filters to find the most relevant KPIs.
  • 实时监视任何 Windows 性能计数器。Monitor any Windows performance counter live.
  • 轻松识别有问题的服务器,并筛选出只与该服务器相关的所有 KPI/实时源。Easily identify a server that is having issues, and filter all the KPI/live feed to just that server.

“实时指标”选项卡

目前 ASP.NET、ASP.NET Core、Azure Functions、Java 和 Node.js 应用支持实时指标。Live Metrics are currently supported for ASP.NET, ASP.NET Core, Azure Functions, Java, and Node.js apps.

入门Get started

  1. 遵循语言特定的准则来启用实时指标。Follow language specific guidelines to enable Live Metrics.

  2. Azure 门户中,打开应用的 Application Insights 资源,然后打开实时流。In the Azure portal, open the Application Insights resource for your app, and then open Live Stream.

  3. 如果可能在筛选器中使用客户名称等敏感数据,请确保控制通道的安全Secure the control channel if you might use sensitive data such as customer names in your filters.

使用适用于所有 .NET 应用程序的代码启用 LiveMetricsEnable LiveMetrics using code for any .NET application

即使在按照 .NET 应用程序的推荐说明加入时默认会启用 LiveMetrics,但以下内容说明了如何手动设置实时指标。Even though LiveMetrics is enabled by default when onboarding using recommended instructions for .NET Applications, the following shows how to setup Live Metrics manually.

  1. 安装 NuGet 包 Microsoft.ApplicationInsights.PerfCounterCollectorInstall the NuGet package Microsoft.ApplicationInsights.PerfCounterCollector
  2. 下面的控制台应用代码示例显示了如何设置实时指标。The following sample console app code shows setting up Live Metrics.
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 setup 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 stream.
                // CPU/Memory Performance counter is also shown
                // automatically without any additional steps.
                client.TrackDependency("My dependency", "target", "http://sample",
                    DateTimeOffset.Now, TimeSpan.FromMilliseconds(300), true);
                client.TrackRequest("My Request", DateTimeOffset.Now,
                    TimeSpan.FromMilliseconds(230), "200", true);
                Task.Delay(1000).Wait();
            }
        }
    }
}

尽管上面的示例适用于控制台应用,但在所有 .NET 应用程序中都可以使用相同的代码。While the above sample is for a console app, the same code can be used in any .NET applications. 如果启用了自动收集遥测的任何其他 TelemetryModules,请务必确保用于初始化这些模块的相同配置也用于实时指标模块。If any other TelemetryModules are enabled which auto-collects telemetry, it is important to ensure the same configuration used for initializing those modules is used for Live Metrics module as well.

实时指标流与指标资源管理器、Analytics 有何差异?How does Live Metrics Stream differ from Metrics Explorer and Analytics?

实时流Live Stream 指标资源管理器和 AnalyticsMetrics Explorer and Analytics
延迟Latency 在一秒内显示数据Data displayed within one second 在几分钟聚合Aggregated over minutes
无保留期No retention 当数据在图表上显示时会得到保留,不显示时将被丢弃。Data persists while it's on the chart, and is then discarded 数据会保留 90 天Data retained for 90 days
按需On demand 仅“实时指标”窗格处于打开状态时才会流式处理数据Data is only streamed while the Live Metrics pane is open 每当安装并启用 SDK 时会发送数据Data is sent whenever the SDK is installed and enabled
免费Free 实时流数据不收取费用There is no charge for Live Stream data 遵从定价中的标准Subject to pricing
采样Sampling 传输所有选择的指标和计数器。All selected metrics and counters are transmitted. 对失败和堆栈跟踪进行采样。Failures and stack traces are sampled. 可能会对事件进行采样Events may be sampled
控制通道Control channel 筛选器的控制信号会发送到 SDK。Filter control signals are sent to the SDK. 建议确保此通道的安全。We recommend you secure this channel. 通信为单向通信,即通向门户Communication is one way, to the portal

选择和筛选指标Select and filter your metrics

(适用于 ASP.NET、ASP.NET Core 和 Azure Functions (v2)。)(Available with ASP.NET, ASP.NET Core, and Azure Functions (v2).)

可以通过在门户中针对任何 Application Insights 遥测数据应用任意筛选器来实时监视自定义 KPI。You can monitor custom KPI live by applying arbitrary filters on any Application Insights telemetry from the portal. 单击筛选器控件(将鼠标悬停在任何图表上时会显示)。Click the filter control that shows when you mouse-over any of the charts. 下图绘制了一个自定义请求计数 KPI,其中的数据已按“URL”和“持续时间”属性进行筛选。The following chart is plotting a custom Request count KPI with filters on URL and Duration attributes. 使用“流预览”部分(显示与在任意时间点指定的条件匹配的实时遥测源)验证筛选器。Validate your filters with the Stream Preview section that shows a live feed of telemetry that matches the criteria you have specified at any point in time.

筛选请求速率

可以监视与“计数”不同的值。You can monitor a value different from Count. 可用的选项取决于流的类型,这可能是任何 Application Insights 遥测数据:请求、依赖项、异常、跟踪、事件或指标。The options depend on the type of stream, which could be any Application Insights telemetry: requests, dependencies, exceptions, traces, events, or metrics. 它也可能是自己的自定义度量值It can be your own custom measurement:

针对请求速率的查询生成器(使用自定义指标)

除了 Application Insights 遥测数据以外,还可以监视任何 Windows 性能计数器:从流选项中选择该类型,并提供性能计数器的名称。In addition to Application Insights telemetry, you can also monitor any Windows performance counter by selecting that from the stream options, and providing the name of the performance counter.

实时指标分别在以下两个点上聚合:在每个服务器本地,并在所有服务器上。Live metrics are aggregated at two points: locally on each server, and then across all servers. 可以通过在相应的下拉列表中选择其他选项来更改默认选项。You can change the default at either by selecting other options in the respective drop-downs.

样本遥测数据:自定义实时诊断事件Sample Telemetry: Custom Live Diagnostic Events

默认情况下,事件实时源显示已失败的请求和依赖项调用、异常、事件与跟踪的样本。By default, the live feed of events shows samples of failed requests and dependency calls, exceptions, events, and traces. 单击筛选器图标可以查看在任意时间点应用的条件。Click the filter icon to see the applied criteria at any point in time.

“筛选器”按钮

与使用指标时一样,可以将任意条件指定为任何 Application Insights 遥测类型。As with metrics, you can specify any arbitrary criteria to any of the Application Insights telemetry types. 在本示例中,我们将选择特定的请求失败和事件。In this example, we are selecting specific request failures, and events.

查询生成器

备注

目前,对于基于异常消息的条件,请使用外部异常消息。Currently, for Exception message-based criteria, use the outermost exception message. 在前面的示例中,若要筛选出具有内部异常消息“客户端已断开连接”(追随“<--”分隔符查找)的良性异常,In the preceding example, to filter out the benign exception with inner exception message (follows the "<--" delimiter) "The client disconnected." 请使用不包含“读取请求内容时出错”条件的消息。use a message not-contains "Error reading request content" criteria.

单击实时源中的某个项可查看其详细信息。See the details of an item in the live feed by clicking it. 可以通过单击“暂停”、向下滚动或单击某个项来暂停源。You can pause the feed either by clicking Pause or simply scrolling down, or clicking an item. 在实时源处于暂停状态时,滚回到顶部后,或者单击收集的项的计数器时,该实时源会恢复。Live feed will resume after you scroll back to the top, or by clicking the counter of items collected while it was paused.

屏幕截图显示了“遥测示例”窗口,其中选择了异常且窗口底部显示了异常详细信息。

按服务器实例筛选Filter by server instance

如果要监视特定服务器角色实例,则可以按服务器进行筛选。If you want to monitor a particular server role instance, you can filter by server. 要进行筛选,请在“服务器”下选择服务器名称。To filter select the server name under Servers.

采样的实时失败

确保控制通道的安全Secure the control channel

备注

目前,只能使用基于代码的监视设置经过身份验证的通道,而不能使用无代码附加对服务器进行身份验证。Currently, you can only set up an authenticated channel using code based monitoring and cannot authenticate servers using codeless attach.

在实时指标门户中指定的自定义筛选器条件将发回到 Application Insights SDK 中的“实时指标”组件。The custom filters criteria you specify in Live Metrics portal are sent back to the Live Metrics component in the Application Insights SDK. 筛选器可能包含 customerID 等敏感信息。The filters could potentially contain sensitive information such as customerIDs. 可以使用机密 API 密钥以及检测密钥来保护通道的安全。You can make the channel secure with a secret API key in addition to the instrumentation key.

创建 API 密钥Create an API Key

“API 密钥”>“创建 API 密钥” “创建 API 密钥”选项卡。依次选择“对 SDK 控制通道进行身份验证”、“生产密钥”API key > Create API key Create API Key tab. Select "authenticate SDK control channel" then "generate key"

将 API 密钥添加到配置中Add API key to Configuration

ASP.NETASP.NET

在 applicationinsights.config 文件中,将 AuthenticationApiKey 添加到 QuickPulseTelemetryModule:In the applicationinsights.config file, add the AuthenticationApiKey to the QuickPulseTelemetryModule:

<Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryModule, Microsoft.AI.PerfCounterCollector">
      <AuthenticationApiKey>YOUR-API-KEY-HERE</AuthenticationApiKey>
</Add>

ASP.NET CoreASP.NET Core

对于 ASP.NET Core 应用程序,请遵照以下说明进行操作。For ASP.NET Core applications, follow the instructions below.

如下所述修改 startup.cs 文件的 ConfigureServicesModify ConfigureServices of your Startup.cs file as follows:

添加以下命名空间。Add the following namespace.

using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse;

然后按如下所示修改 ConfigureServices 方法。Then modify ConfigureServices method as below.

public void ConfigureServices(IServiceCollection services)
{
    // existing code which include services.AddApplicationInsightsTelemetry() to enable Application Insights.
    services.ConfigureTelemetryModule<QuickPulseTelemetryModule> ((module, o) => module.AuthenticationApiKey = "YOUR-API-KEY-HERE");
}

有关配置 ASP.NET Core 应用程序的详细信息,请参阅有关在 ASP.NET Core 中配置遥测模块的指南。More information on configuring ASP.NET Core applications can be found in our guidance on configuring telemetry modules in ASP.NET Core.

WorkerServiceWorkerService

对于 WorkerService 应用程序,请按照下面的说明进行操作。For WorkerService applications, follow the instructions below.

添加以下命名空间。Add the following namespace.

using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse;

接下来,在 services.AddApplicationInsightsTelemetryWorkerService 调用前添加以下行。Next, add the following line before the call services.AddApplicationInsightsTelemetryWorkerService.

    services.ConfigureTelemetryModule<QuickPulseTelemetryModule> ((module, o) => module.AuthenticationApiKey = "YOUR-API-KEY-HERE");

有关配置 WorkerService 应用程序的详细信息,请参阅有关在 WorkerServices 中配置遥测模块的指南。More information on configuring WorkerService applications can be found in our guidance on configuring telemetry modules in WorkerServices.

Azure 函数应用Azure Function Apps

对于使用 API 密钥保护通道的 Azure 函数应用 (v2),可以通过一个环境变量来实现。For Azure Function Apps (v2), securing the channel with an API key can be accomplished with an environment variable.

从 Application Insights 资源中创建一个 API 密钥,并转到你的函数应用的“设置”>“配置”。Create an API key from within your Application Insights resource and go to Settings > Configuration for your Function App. 选择“新建应用程序设置”,并输入名称 APPINSIGHTS_QUICKPULSEAUTHAPIKEY 和与你的 API 密钥对应的值。Select New application setting and enter a name of APPINSIGHTS_QUICKPULSEAUTHAPIKEY and a value that corresponds to your API key.

但是,如果认识并信任所有连接的服务器,则可以尝试使用不包含经过身份验证的通道的自定义筛选器。However, if you recognize and trust all the connected servers, you can try the custom filters without the authenticated channel. 可以使用此选项六个月。This option is available for six months. 每建立一个新的会话或者新服务器联机时,都需要进行这种替代。This override is required once every new session, or when a new server comes online.

实时指标身份验证选项

备注

在筛选条件中输入 CustomerID 等潜在的敏感信息之前,我们强烈建议设置经过身份验证的通道。We strongly recommend that you set up the authenticated channel before entering potentially sensitive information like CustomerID in the filter criteria.

支持的功能表Supported features table

语言Language 基本指标Basic Metrics 性能指标Performance metrics 自定义筛选Custom filtering 样本遥测数据Sample telemetry CPU 按进程划分CPU split by process
.NET Framework.NET Framework 支持 (V2.7.2+)Supported (V2.7.2+) 支持 (V2.7.2+)Supported (V2.7.2+) 支持 (V2.7.2+)Supported (V2.7.2+) 支持 (V2.7.2+)Supported (V2.7.2+) 支持 (V2.7.2+)Supported (V2.7.2+)
.NET Core(目标=.NET Framework).NET Core (target=.NET Framework) 支持 (V2.4.1+)Supported (V2.4.1+) 支持 (V2.4.1+)Supported (V2.4.1+) 支持 (V2.4.1+)Supported (V2.4.1+) 支持 (V2.4.1+)Supported (V2.4.1+) 支持 (V2.4.1+)Supported (V2.4.1+)
.NET Core(目标=.NET Core).NET Core (target=.NET Core) 支持 (V2.4.1+)Supported (V2.4.1+) 支持*Supported* 支持 (V2.4.1+)Supported (V2.4.1+) 支持 (V2.4.1+)Supported (V2.4.1+) 不支持Not Supported
Azure Functions v2Azure Functions v2 支持Supported 支持Supported 支持Supported 支持Supported 不支持Not Supported
JavaJava 支持 (V2.0.0+)Supported (V2.0.0+) 支持 (V2.0.0+)Supported (V2.0.0+) 不支持Not Supported 不支持Not Supported 不支持Not Supported
Node.jsNode.js 支持 (V1.3.0+)Supported (V1.3.0+) 支持 (V1.3.0+)Supported (V1.3.0+) 不支持Not Supported 支持 (V1.3.0+)Supported (V1.3.0+) 不支持Not Supported

基本指标包括请求、依赖项和异常率。Basic metrics include request, dependency, and exception rate. 性能指标(性能计数器)包括内存和 CPU。Performance metrics (performance counters) include memory and CPU. 示例遥测显示了有关失败的请求和依赖项、异常、事件和跟踪的详细信息流。Sample telemetry shows a stream of detailed information for failed requests and dependencies, exceptions, events, and traces.

* PerfCounters 支持在不针对 .NET Framework 的 .NET Core 版本之间略有不同:* PerfCounters support varies slightly across versions of .NET Core that do not target the .NET Framework:

  • 在适用于 Windows 的 Azure 应用服务中运行时,支持 PerfCounters 指标。PerfCounters metrics are supported when running in Azure App Service for Windows. (AspNetCore SDK 版本 2.4.1 或更高版本)(AspNetCore SDK Version 2.4.1 or higher)
  • 当应用在任何 Windows 计算机(VM、云服务或本地等)上运行时(AspNetCore SDK 版本 2.7.1 或更高版本),支持 PerfCounters,但针对 .NET Core 2.0 或更高版本的应用除外。PerfCounters are supported when app is running in ANY Windows machines (VM or Cloud Service or On-prem etc.) (AspNetCore SDK Version 2.7.1 or higher), but for apps targeting .NET Core 2.0 or higher.
  • 当应用以最新版本(即 AspNetCore SDK 2.8.0 或更高版本)在任意位置(Linux、Windows、用于 Linux 的应用服务、容器等)运行时,支持 PerfCounters,但仅适用于面向 .NET Core 2.0 或更高版本的应用。PerfCounters are supported when app is running ANYWHERE (Linux, Windows, app service for Linux, containers, etc.) in the latest versions (i.e. AspNetCore SDK Version 2.8.0 or higher), but only for apps targeting .NET Core 2.0 or higher.

后续步骤Next steps