收集 Azure 云服务的性能计数器Collect performance counters for your Azure Cloud Service

使用性能计数器可以跟踪应用程序和主机的运行情况。Performance counters provide a way for you to track how well your application and the host are performing. Windows Server 提供与硬件、应用程序、操作系统等相关的许多不同性能计数器。Windows Server provides many different performance counters related to hardware, applications, the operating system, and more. 通过收集性能计数器并将其发送到 Azure,可以分析此信息以帮助做出更明智的决策。By collecting and sending performance counters to Azure, you can analyze this information to help make better decisions.

发现可用的计数器Discover available counters

性能计数器由两个部分组成:集名称(也称为类别),以及一个或多个计数器。A performance counter is made up of two parts, a set name (also known as a category) and one or more counters. 可以使用 PowerShell 获取可用性能计数器的列表:You can use PowerShell to get a list of available performance counters:

Get-Counter -ListSet * | Select-Object CounterSetName, Paths | Sort-Object CounterSetName

CounterSetName                                  Paths
--------------                                  -----
.NET CLR Data                                   {\.NET CLR Data(*)\SqlClient...
.NET CLR Exceptions                             {\.NET CLR Exceptions(*)\# o...
.NET CLR Interop                                {\.NET CLR Interop(*)\# of C...
.NET CLR Jit                                    {\.NET CLR Jit(*)\# of Metho...
.NET Data Provider for Oracle                   {\.NET Data Provider for Ora...
.NET Data Provider for SqlServer                {\.NET Data Provider for Sql...
.NET Memory Cache 4.0                           {\.NET Memory Cache 4.0(*)\C...
AppV Client Streamed Data Percentage            {\AppV Client Streamed Data ...
ASP.NET                                         {\ASP.NET\Application Restar...
ASP.NET Apps v4.0.30319                         {\ASP.NET Apps v4.0.30319(*)...
ASP.NET State Service                           {\ASP.NET State Service\Stat...
ASP.NET v2.0.50727                              {\ASP.NET v2.0.50727\Applica...
ASP.NET v4.0.30319                              {\ASP.NET v4.0.30319\Applica...
Authorization Manager Applications              {\Authorization Manager Appl...

#... results cut to save space ...

CounterSetName 属性表示集(或类别),可以很好地反映性能计数器与哪些组件相关。The CounterSetName property represents a set (or category), and is a good indicator of what the performance counters are related to. Paths 属性表示某个集的计数器集合。The Paths property represents a collection of counters for a set. 还可以获取 Description 属性来了解有关计数器集的详细信息。You could also get the Description property for more information about the counter set.

若要获取某个集的所有计数器,请使用 CounterSetName 值并扩展 Paths 集合。To get all of the counters for a set, use the CounterSetName value and expand the Paths collection. 每个路径项是可以查询的计数器。Each path item is a counter you can query. 例如,若要获取 Processor 集相关的可用计数器,请扩展 Paths 集合:For example, to get the available counters related to the Processor set, expand the Paths collection:

Get-Counter -ListSet * | Where-Object CounterSetName -eq "Processor" | Select -ExpandProperty Paths

\Processor(*)\% Processor Time
\Processor(*)\% User Time
\Processor(*)\% Privileged Time
\Processor(*)\Interrupts/sec
\Processor(*)\% DPC Time
\Processor(*)\% Interrupt Time
\Processor(*)\DPCs Queued/sec
\Processor(*)\DPC Rate
\Processor(*)\% Idle Time
\Processor(*)\% C1 Time
\Processor(*)\% C2 Time
\Processor(*)\% C3 Time
\Processor(*)\C1 Transitions/sec
\Processor(*)\C2 Transitions/sec
\Processor(*)\C3 Transitions/sec

可将这些单独的计数器路径添加到云服务使用的诊断框架。These individual counter paths can be added to the diagnostics framework your cloud service uses. 有关如何构造性能计数器路径的详细信息,请参阅指定计数器路径For more information about how a performance counter path is constructed, see Specifying a Counter Path.

收集性能计数器Collect a performance counter

可将性能计数器添加到 Azure 诊断或 Application Insights 的云服务。A performance counter can be added to your cloud service for either Azure Diagnostics or Application Insights.

Application InsightsApplication Insights

使用适用于云服务的 Azure Application Insights 可以指定要收集的性能计数器。Azure Application Insights for Cloud Services allows you specify what performance counters you want to collect. Application Insights 添加到项目之后,名为 ApplicationInsights.config 的配置文件将添加到 Visual Studio 项目。After you add Application Insights to your project, a config file named ApplicationInsights.config is added to your Visual Studio project. 此配置文件定义 Application Insights 要收集并发送到 Azure 的信息类型。This config file defines what type of information Application Insights collects and sends to Azure.

打开 ApplicationInsights.config 文件并找到 ApplicationInsights > TelemetryModules 元素。Open the ApplicationInsights.config file and find the ApplicationInsights > TelemetryModules element. 每个 <Add> 子元素定义要收集的一种遥测类型及其配置。Each <Add> child-element defines a type of telemetry to collect, along with its configuration. 性能计数器遥测模块类型为 Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule, Microsoft.AI.PerfCounterCollectorThe performance counter telemetry module type is Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule, Microsoft.AI.PerfCounterCollector. 如果已定义此元素,请不要再次添加它。If this element is already defined, do not add it a second time. 要收集的每个性能计数器在名为 <Counters> 的节点下定义。Each performance counter to collect is defined under a node named <Counters>. 下面是收集驱动器性能计数器的示例:Here is an example that collects drive performance counters:

<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">

  <TelemetryModules>

    <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule, Microsoft.AI.PerfCounterCollector">
      <Counters>
        <Add PerformanceCounter="\LogicalDisk(C:)\Disk Write Bytes/sec" ReportAs="Disk write (C:)" />
        <Add PerformanceCounter="\LogicalDisk(C:)\Disk Read Bytes/sec" ReportAs="Disk read (C:)" />
      </Counters>
    </Add>

  </TelemetryModules>

<!-- ... cut to save space ... -->

每个性能计数器在 <Counters> 下表示为 <Add> 元素。Each performance counter is represented as an <Add> element under <Counters>. PerformanceCounter 属性定义要收集的性能计数器。The PerformanceCounter attribute defines which performance counter to collect. ReportAs 属性是在 Azure 门户中针对性能计数器显示的标题。The ReportAs attribute is the title to display in the Azure portal for the performance counter. 收集的任何性能计数器将在门户中放入名为“自定义”的类别中。 Any performance counter you collect is put into a category named Custom in the portal. 与 Azure 诊断不同,无法设置收集这些性能计数器并将其发送到 Azure 的间隔。Unlike Azure Diagnostics, you cannot set the interval these performance counters are collected and sent to Azure. 使用 Application Insights 时,每隔一分钟收集和发送性能计数器一次。With Application Insights, performance counters are collected and sent every minute.

Application Insights 会自动收集以下性能计数器:Application Insights automatically collects the following performance counters:

  • \Process(??APP_WIN32_PROC??)%处理器时间\Process(??APP_WIN32_PROC??)% Processor Time
  • \Memory\Available Bytes\Memory\Available Bytes
  • .NET CLR Exceptions(??APP_CLR_PROC??)# of Exceps Thrown / sec.NET CLR Exceptions(??APP_CLR_PROC??)# of Exceps Thrown / sec
  • \Process(??APP_WIN32_PROC??)\Private Bytes\Process(??APP_WIN32_PROC??)\Private Bytes
  • \Process(??APP_WIN32_PROC??)\IO Data Bytes/sec\Process(??APP_WIN32_PROC??)\IO Data Bytes/sec
  • \Processor(_Total)% 处理器时间\Processor(_Total)% Processor Time

有关详细信息,请参阅 Application Insights 中的系统性能计数器适用于 Azure 云服务的 Application InsightsFor more information, see System performance counters in Application Insights and Application Insights for Azure Cloud Services.

Azure 诊断Azure Diagnostics

重要

尽管所有这些数据都会聚合到存储帐户中,但门户提供绘制数据图表的本机方法。While all this data is aggregated into the storage account, the portal does not provide a native way to chart the data. 我们强烈建议将另一个诊断服务(如 Application Insights)集成到应用程序中。It is highly recommended that you integrate another diagnostics service, like Application Insights, into your application.

使用适用于云服务的 Azure 诊断扩展可以指定要收集的性能计数器。The Azure Diagnostics extension for Cloud Services allows you specify what performance counters you want to collect. 若要设置 Azure 诊断,请参阅云服务监视概述To set up Azure Diagnostics, see Cloud Service Monitoring Overview.

要收集的性能计数器在 diagnostics.wadcfgx 文件中定义。The performance counters you want to collect are defined in the diagnostics.wadcfgx file. 请在 Visual Studio 中打开此文件(为每个角色定义了此文件),并找到 DiagnosticsConfiguration > PublicConfig > WadCfg > DiagnosticMonitorConfiguration > PerformanceCounters 元素。Open this file (it is defined per role) in Visual Studio and find the DiagnosticsConfiguration > PublicConfig > WadCfg > DiagnosticMonitorConfiguration > PerformanceCounters element. 将新的 PerformanceCounterConfiguration 元素添加为子级。Add a new PerformanceCounterConfiguration element as a child. 此元素有两个属性:counterSpecifiersampleRateThis element has two attributes: counterSpecifier and sampleRate. counterSpecifier 属性定义要收集的系统性能计数器集(请参阅上一部分)。The counterSpecifier attribute defines which system performance counter set (outlined in the previous section) to collect. sampleRate 值指示轮询值的频率。The sampleRate value indicates how often that value is polled. 将会根据父 PerformanceCounters 元素的 scheduledTransferPeriod 属性值,将所有性能计数器作为一个整体传输到 Azure。As a whole, all performance counters are transferred to Azure according to the parent PerformanceCounters element's scheduledTransferPeriod attribute value.

有关 PerformanceCounters 架构元素的详细信息,请参阅 Azure 诊断架构For more information about the PerformanceCounters schema element, see the Azure Diagnostics Schema.

sampleRate 属性定义的时间段使用 XML 持续时间数据类型来指示轮询性能计数器的频率。The period defined by the sampleRate attribute uses the XML duration data type to indicate how often the performance counter is polled. 在以下示例中,频率设置为 PT3M,表示 [P]eriod[T]ime[3][M]inutes:每隔 3 分钟。In the example below, the rate is set to PT3M, which means [P]eriod[T]ime[3][M]inutes: every three minutes.

有关 sampleRatescheduledTransferPeriod 定义方式的详细信息,请参阅 W3 XML 日期和时间日期类型教程中的“持续时间数据类型”部分。 For more information about how the sampleRate and scheduledTransferPeriod are defined, see the Duration Data Type section in the W3 XML Date and Time Date Types tutorial.

<?xml version="1.0" encoding="utf-8"?>
<DiagnosticsConfiguration  xmlns="http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration">
  <PublicConfig>
    <WadCfg>
      <DiagnosticMonitorConfiguration overallQuotaInMB="4096">

        <!-- ... cut to save space ... -->

        <PerformanceCounters scheduledTransferPeriod="PT1M">
          <PerformanceCounterConfiguration counterSpecifier="\Memory\Available MBytes" sampleRate="PT3M" />
          <PerformanceCounterConfiguration counterSpecifier="\Web Service(_Total)\ISAPI Extension Requests/sec" sampleRate="PT3M" />
          <PerformanceCounterConfiguration counterSpecifier="\Web Service(_Total)\Bytes Total/Sec" sampleRate="PT3M" />
          <PerformanceCounterConfiguration counterSpecifier="\ASP.NET Applications(__Total__)\Requests/Sec" sampleRate="PT3M" />
          <PerformanceCounterConfiguration counterSpecifier="\ASP.NET Applications(__Total__)\Errors Total/Sec" sampleRate="PT3M" />
          <PerformanceCounterConfiguration counterSpecifier="\ASP.NET\Requests Queued" sampleRate="PT3M" />
          <PerformanceCounterConfiguration counterSpecifier="\ASP.NET\Requests Rejected" sampleRate="PT3M" />
          <PerformanceCounterConfiguration counterSpecifier="\Processor(_Total)\% Processor Time" sampleRate="PT3M" />

          <!-- This is a new perf counter which will track the C: disk read activity in bytes per second, every minute -->
          <PerformanceCounterConfiguration counterSpecifier="\LogicalDisk(C:)\Disk Read Bytes/sec" sampleRate="PT1M" />

        </PerformanceCounters>
      </DiagnosticMonitorConfiguration>
    </WadCfg>
    
    <!-- ... cut to save space ... -->

  </PublicConfig>
</DiagnosticsConfiguration>

创建新的性能计数器Create a new perf counter

可以在代码中创建和使用新的性能计数器。A new performance counter can be created and used by your code. 创建新性能计数器的代码必须以提升的权限运行,否则会失败。Your code that creates a new performance counter must be running elevated, otherwise it will fail. 云服务 OnStart 启动代码可以创建性能计数器,这需要在权限提升的上下文中运行角色。Your cloud service OnStart startup code can create the performance counter, requiring you to run the role in an elevated context. 或者,可以创建一个以提升的权限运行并可创建性能计数器的启动任务。Or you can create a startup task that runs elevated and creates the performance counter. 有关启动任务的详细信息,请参阅如何配置和运行云服务的启动任务For more information about startup tasks, see How to configure and run startup tasks for a cloud service.

若要将角色配置为以提升的权限运行,请将 <Runtime> 元素添加到 .csdef 文件。To configure your role to run elevated, add a <Runtime> element to the .csdef file.

<ServiceDefinition name="CloudServiceLoadTesting" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition" schemaVersion="2015-04.2.6">
  <WorkerRole name="WorkerRoleWithSBQueue1" vmsize="Large">

    <!-- ... cut to save space ... -->

    <Runtime executionContext="elevated">
      
    </Runtime>

    <!-- ... cut to save space ... -->

  </WorkerRole>
</ServiceDefinition>

只需几行代码就能创建并注册新的性能计数器。You can create and register a new performance counter with a few lines of code. 使用可以创建类别和计数器的 System.Diagnostics.PerformanceCounterCategory.Create 方法重载。Use the System.Diagnostics.PerformanceCounterCategory.Create method overload that creates both the category and the counter. 以下代码首先检查类别是否存在,如果不存在,则创建该类别和计数器。The following code first checks if the category exists, and if missing, creates both the category and the counter.

using System.Diagnostics;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace WorkerRoleWithSBQueue1
{
    public class WorkerRole : RoleEntryPoint
    {
        // Perf counter variable representing times service was used.
        private PerformanceCounter counterServiceUsed;

        public override bool OnStart()
        {
            // ... Other startup code here ...

            // Define the category and counter names.
            string perfCounterCatName = "MyService";
            string perfCounterName = "Times Used";

            // Create the counter if needed. Our counter category only has a single counter.
            // Both the category and counter are created in the same method call.
            if (!PerformanceCounterCategory.Exists(perfCounterCatName))
            {
                PerformanceCounterCategory.Create(perfCounterCatName, "Collects information about the cloud service.", 
                                                  PerformanceCounterCategoryType.SingleInstance, 
                                                  perfCounterName, "How many times the cloud service was used.");
            }

            // Get reference to our counter
            counterServiceUsed = new PerformanceCounter(perfCounterCatName, perfCounterName);
            counterServiceUsed.ReadOnly = false;
            
            return base.OnStart();
        }

        // ... cut class code to save space
    }
}

若要使用计数器,请调用 IncrementIncrementBy 方法。When you want to use the counter, call the Increment or IncrementBy method.

// Increase the counter by 1
counterServiceUsed.Increment();

在应用程序使用自定义计数器后,需要配置 Azure 诊断或 Application Insights 来跟踪该计数器。Now that your application uses your custom counter, you need to configure Azure Diagnostics or Application Insights to track the counter.

Application InsightsApplication Insights

如前所述,Application Insights 的性能计数器在 ApplicationInsights.config 文件中定义。As previously stated, the performance counters for Application Insights are defined in the ApplicationInsights.config file. 打开 ApplicationInsights.config 并找到 ApplicationInsights > TelemetryModules > Add > Counters 元素。Open ApplicationInsights.config and find the ApplicationInsights > TelemetryModules > Add > Counters element. 创建 <Add> 子元素,并将 PerformanceCounter 属性设置为代码中创建的性能计数器的类别和名称。Create an <Add> child element and set the PerformanceCounter attribute to the category and name of the performance counter you created in your code. ReportAs 属性设置为要在门户中显示的友好名称。Set the ReportAs attribute to a friendly name you want to see in the portal.

<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">

  <TelemetryModules>

    <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule, Microsoft.AI.PerfCounterCollector">
      <Counters>
        <!-- ... cut other perf counters to save space ... -->

        <!-- This new perf counter matches the [category name]\[counter name] defined in your code -->
        <Add PerformanceCounter="\MyService\Times Used" ReportAs="Service used counter" />
      </Counters>
    </Add>

  </TelemetryModules>

<!-- ... cut to save space ... -->

Azure 诊断Azure Diagnostics

如前所述,要收集的性能计数器在 diagnostics.wadcfgx 文件中定义。As previously stated, the performance counters you want to collect are defined in the diagnostics.wadcfgx file. 请在 Visual Studio 中打开此文件(为每个角色定义了此文件),并找到 DiagnosticsConfiguration > PublicConfig > WadCfg > DiagnosticMonitorConfiguration > PerformanceCounters 元素。Open this file (it is defined per role) in Visual Studio and find the DiagnosticsConfiguration > PublicConfig > WadCfg > DiagnosticMonitorConfiguration > PerformanceCounters element. 将新的 PerformanceCounterConfiguration 元素添加为子级。Add a new PerformanceCounterConfiguration element as a child. counterSpecifier 属性设置为代码中创建的性能计数器的类别和名称。Set the counterSpecifier attribute to the category and name of the performance counter you created in your code.

<?xml version="1.0" encoding="utf-8"?>
<DiagnosticsConfiguration  xmlns="http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration">
  <PublicConfig>
    <WadCfg>
      <DiagnosticMonitorConfiguration overallQuotaInMB="4096">

        <!-- ... cut to save space ... -->

        <PerformanceCounters scheduledTransferPeriod="PT1M">
          <!-- ... cut other perf counters to save space ... -->
          
          <!-- This new perf counter matches the [category name]\[counter name] defined in your code -->
          <PerformanceCounterConfiguration counterSpecifier="\MyService\Times Used" sampleRate="PT1M" />

        </PerformanceCounters>
      </DiagnosticMonitorConfiguration>
    </WadCfg>
    
    <!-- ... cut to save space ... -->

  </PublicConfig>
</DiagnosticsConfiguration>

详细信息More information