EventCounters 简介EventCounters introduction

EventCounter 是用于发布和使用计数器或统计信息的 .NET/.NET Core 机制。EventCounter is .NET/.NET Core mechanism to publish and consume counters or statistics. 本文档概述了 EventCounters 以及有关如何发布和使用它们的示例。This document gives an overview of EventCounters and examples on how to publish and consume them. 所有 OS 平台(Windows、Linux 和 macOS)都支持 EventCounters。EventCounters are supported in all OS platforms - Windows, Linux, and macOS. 可以将其视为仅在 Windows 系统中受支持的 PerformanceCounters 的等效跨平台。It can be thought of as a cross-platform equivalent for the PerformanceCounters that is only supported in Windows systems.

尽管用户可以根据需要发布任何自定义 EventCounters,但 .NET Core 3.0 运行时默认情况下会发布一组此类计数器。While users can publish any custom EventCounters to meet their needs, the .NET Core 3.0 runtime publishes a set of these counters by default. 本文档将指导你完成在 Azure Application Insights 中收集和查看 EventCounters(系统定义或用户定义)所需的步骤。The document will walk through the steps required to collect and view EventCounters (system defined or user defined) in Azure Application Insights.

使用 Application Insights 收集 EventCountersUsing Application Insights to collect EventCounters

Application Insights 支持使用 EventCounterCollectionModule 收集 EventCounters,该模块是新发布的 nuget 包 Microsoft.ApplicationInsights.EventCounterCollector 的一部分。Application Insights supports collecting EventCounters with its EventCounterCollectionModule, which is part of the newly released nuget package Microsoft.ApplicationInsights.EventCounterCollector. 使用 AspNetCoreWorkerService 时,将自动启用 EventCounterCollectionModuleEventCounterCollectionModule is automatically enabled when using either AspNetCore or WorkerService. EventCounterCollectionModule 会以不可配置的收集频率(60 秒)收集计数器。EventCounterCollectionModule collects counters with a non-configurable collection frequency of 60 seconds. 收集 EventCounters 时,不需要具备特殊的权限。There are no special permissions required to collect EventCounters.

已收集默认计数器Default counters collected

对于在 .NET Core 3.0 中运行的应用,SDK 会自动收集以下计数器。For apps running in .NET Core 3.0, the following counters are collected automatically by the SDK. 计数器的名称将采用“类别|计数器”格式。The name of the counters will be of the form "Category|Counter".

类别Category 计数器Counter
System.Runtime cpu-usage
System.Runtime working-set
System.Runtime gc-heap-size
System.Runtime gen-0-gc-count
System.Runtime gen-1-gc-count
System.Runtime gen-2-gc-count
System.Runtime time-in-gc
System.Runtime gen-0-size
System.Runtime gen-1-size
System.Runtime gen-2-size
System.Runtime loh-size
System.Runtime alloc-rate
System.Runtime assembly-count
System.Runtime exception-count
System.Runtime threadpool-thread-count
System.Runtime monitor-lock-contention-count
System.Runtime threadpool-queue-length
System.Runtime threadpool-completed-items-count
System.Runtime active-timer-count
Microsoft.AspNetCore.Hosting requests-per-second
Microsoft.AspNetCore.Hosting total-requests
Microsoft.AspNetCore.Hosting current-requests
Microsoft.AspNetCore.Hosting failed-requests

备注

Microsoft.AspNetCore.Hosting 类别的计数器仅添加到 ASP.NET Core 应用程序中。Counters of category Microsoft.AspNetCore.Hosting are only added in ASP.NET Core Applications.

自定义要收集的计数器Customizing counters to be collected

以下示例介绍如何添加/删除计数器。The following example shows how to add/remove counters. 使用 AddApplicationInsightsTelemetry()AddApplicationInsightsWorkerService() 启用 Application Insights 遥测收集后,将在应用程序的 ConfigureServices 方法中完成此自定义。This customization would be done in the ConfigureServices method of your application after Application Insights telemetry collection is enabled using either AddApplicationInsightsTelemetry() or AddApplicationInsightsWorkerService(). 下面是 ASP.NET Core 应用程序的示例代码。Following is an example code from an ASP.NET Core application. 对于其他类型的应用程序,请参阅此文档For other type of applications, refer to this document.

    using Microsoft.ApplicationInsights.Extensibility.EventCounterCollector;

    public void ConfigureServices(IServiceCollection services)
    {
        //... other code...

        // The following code shows several customizations done to EventCounterCollectionModule.
        services.ConfigureTelemetryModule<EventCounterCollectionModule>(
            (module, o) =>
            {
                // This removes all default counters.
                module.Counters.Clear();

                // This adds a user defined counter "MyCounter" from EventSource named "MyEventSource"
                module.Counters.Add(new EventCounterCollectionRequest("MyEventSource", "MyCounter"));

                // This adds the system counter "gen-0-size" from "System.Runtime"
                module.Counters.Add(new EventCounterCollectionRequest("System.Runtime", "gen-0-size"));
            }
        );

        // The following code removes EventCounterCollectionModule to disable the module completely.
        var eventCounterModule = services.FirstOrDefault<ServiceDescriptor>
                    (t => t.ImplementationType == typeof(EventCounterCollectionModule));
        if (eventCounterModule != null)
        {
            services.Remove(eventCounterModule);
        }
    }

Metric Explorer 中的事件计数器Event counters in Metric Explorer

若要在 Metric Explorer 中查看 EventCounter 指标,请选择 Application Insights 资源,然后选择基于日志的指标作为指标命名空间。To view EventCounter metrics in Metric Explorer, select Application Insights resource, and chose Log-based metrics as metric namespace. EventCounter 指标随即显示在“自定义”类别下。Then EventCounter metrics get displayed under Custom category.

Application Insights 中报告的事件计数器Event counters reported in Application Insights

Analytics 中的事件计数器Event counters in Analytics

还可以在 Analytics 的“customMetrics”表中搜索和显示事件计数器报表。You can also search and display event counter reports in Analytics, in the customMetrics table.

例如,运行以下查询,以查看收集了哪些计数器并可用于查询:For example, run the following query to see what counters are collected and available to query:

customMetrics | summarize avg(value) by name

Application Insights 中报告的事件计数器Event counters reported in Application Insights

若要在最近一段时间内获取特定计数器(例如:ThreadPool Completed Work Item Count)的图表,请运行以下查询。To get a chart of a specific counter (for example: ThreadPool Completed Work Item Count) over the recent period, run the following query.

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

Application Insights 中的单个计数器的图表Chat of a single counter in Application Insights

与其他遥测一样,customMetrics 同样也具有列 cloud_RoleInstance,指示正在其上运行应用的主机服务器实例的标识。Like other telemetry, customMetrics also has a column cloud_RoleInstance that indicates the identity of the host server instance on which your app is running. 上述查询显示每个实例的计数器值,并可用于比较不同服务器实例的性能。The above query shows the counter value per instance, and can be used to compare performance of different server instances.

警报Alerts

与其他指标一样,可以设置警报以便在事件计数器超出指定的限制时收到警报。Like other metrics, you can set an alert to warn you if an event counter goes outside a limit you specify. 打开“警报”窗格,并单击“添加警报”。Open the Alerts pane and click Add Alert.

常见问题Frequently asked questions

是否能在实时指标中看到 EventCounters?Can I see EventCounters in Live Metrics?

实时指标目前不显示 EventCounters。Live Metrics do not show EventCounters as of today. 使用 Metric Explorer 或 Analytics 来查看遥测数据。Use Metric Explorer or Analytics to see the telemetry.

可以在哪些平台上查看 .NET Core 3.0 计数器的默认列表?Which platforms can I see the default list of .NET Core 3.0 counters?

EventCounter 无需任何特殊权限,并且在支持 .NET Core 3.0 的所有平台中受支持。EventCounter doesn't require any special permissions, and is supported in all platforms .NET Core 3.0 is supported. 这包括:This includes:

  • 操作系统:Windows、Linux 和 macOS。Operating system: Windows, Linux, or macOS.
  • 托管方法:进程内或进程外。Hosting method: In process or out of process.
  • 部署方法:框架依赖或自包含。Deployment method: Framework dependent or self-contained.
  • Web 服务器:IIS(Internet 信息服务器)或 Kestrel。Web server: IIS (Internet Information Server) or Kestrel.
  • 托管平台:Azure 应用服务、Azure VM、Docker、Azure Kubernetes 服务 (AKS) 等的 Web 应用功能。Hosting platform: The Web Apps feature of Azure App Service, Azure VM, Docker, Azure Kubernetes Service (AKS), and so on.

我已从 Azure Web 应用门户启用 Application Insights。I have enabled Application Insights from Azure Web App Portal. 但看不到 EventCounters,这是什么原因?But I can't see EventCounters.?

ASP.NET Core 的 Application Insights 扩展尚不支持此功能。Application Insights extension for ASP.NET Core doesn't yet support this feature. 支持此功能后,本文档会更新。This document will be updated when this feature is supported.

后续步骤Next steps