在 Azure 云服务中启用 Azure 诊断Enabling Azure Diagnostics in Azure Cloud Services

有关 Azure 诊断的背景信息,请参阅 Azure 诊断概述See Azure Diagnostics Overview for a background on Azure Diagnostics.

如何在辅助角色中启用诊断How to Enable Diagnostics in a Worker Role

本演练介绍如何实现使用 .NET EventSource 类发出遥测数据的 Azure 辅助角色。This walkthrough describes how to implement an Azure worker role that emits telemetry data using the .NET EventSource class. Azure Diagnostics 用于收集遥测数据,并将其存储在一个 Azure 存储帐户中。Azure Diagnostics is used to collect the telemetry data and store it in an Azure storage account. 创建辅助角色时,Visual Studio 将在适用于 .NET 2.4 和更低版本的 Azure SDK 中,自动启用 Diagnostics 1.0 作为解决方案的一部分。When creating a worker role, Visual Studio automatically enables Diagnostics 1.0 as part of the solution in Azure SDKs for .NET 2.4 and earlier. 以下说明介绍了创建辅助角色、从解决方案禁用 Diagnostics 1.0,以及在辅助角色中部署 Diagnostics 1.2 或 1.3 的过程。The following instructions describe the process for creating the worker role, disabling Diagnostics 1.0 from the solution, and deploying Diagnostics 1.2 or 1.3 to your worker role.

先决条件Prerequisites

本文假定你具有 Azure 订阅,并要将 Visual Studio 与 Azure SDK 配合使用。This article assumes you have an Azure subscription and are using Visual Studio with the Azure SDK. 如果没有 Azure 订阅,可以注册 免费试用版If you do not have an Azure subscription, you can sign up for the Free Trial. 请确保安装并配置 Azure PowerShell 0.8.7 版或更高版本Make sure to Install and configure Azure PowerShell version 0.8.7 or later.

步骤 1:创建辅助角色Step 1: Create a Worker Role

  1. 启动 Visual StudioLaunch Visual Studio.
  2. 从面向 .NET Framework 4.5 的“云”模板创建一个“Azure 云服务”项目。Create an Azure Cloud Service project from the Cloud template that targets .NET Framework 4.5. 将该项目命名为“WadExample”。Name the project "WadExample" and click Ok.
  3. 选择“辅助角色”并单击“确定” 。Select Worker Role and click Ok. 随后将创建该项目。The project will be created.
  4. 在“解决方案资源管理器”中,双击 WorkerRole1 属性文件。In Solution Explorer, double-click the WorkerRole1 properties file.
  5. 在“配置”选项卡中,取消选中“启用诊断”以禁用 Diagnostics 1.0(Azure SDK 2.4 和更低版本)。In the Configuration tab, un-check Enable Diagnostics to disable Diagnostics 1.0 (Azure SDK 2.4 and earlier).
  6. 生成解决方案以验证无误。Build your solution to verify that you have no errors.

步骤 2:检测代码Step 2: Instrument your code

将 WorkerRole.cs 的内容替换为以下代码。Replace the contents of WorkerRole.cs with the following code. 继承自 EventSource 类的 SampleEventSourceWriter 类实现了四个日志记录方法:SendEnumsMessageMethodSetOtherHighFreqThe class SampleEventSourceWriter, inherited from the EventSource Class, implements four logging methods: SendEnums, MessageMethod, SetOther and HighFreq. WriteEvent 方法的第一个参数定义相关事件的 ID。The first parameter to the WriteEvent method defines the ID for the respective event. Run 方法实现一个无限循环,该循环每隔 10 秒调用 SampleEventSourceWriter 类中实现的每个日志记录方法。The Run method implements an infinite loop that calls each of the logging methods implemented in the SampleEventSourceWriter class every 10 seconds.

using Microsoft.WindowsAzure.ServiceRuntime;
using System;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Net;
using System.Threading;

namespace WorkerRole1
{
sealed class SampleEventSourceWriter : EventSource
{
    public static SampleEventSourceWriter Log = new SampleEventSourceWriter();
    public void SendEnums(MyColor color, MyFlags flags) { if (IsEnabled())  WriteEvent(1, (int)color, (int)flags); }// Cast enums to int for efficient logging.
    public void MessageMethod(string Message) { if (IsEnabled())  WriteEvent(2, Message); }
    public void SetOther(bool flag, int myInt) { if (IsEnabled())  WriteEvent(3, flag, myInt); }
    public void HighFreq(int value) { if (IsEnabled()) WriteEvent(4, value); }

}

enum MyColor
{
    Red,
    Blue,
    Green
}

[Flags]
enum MyFlags
{
    Flag1 = 1,
    Flag2 = 2,
    Flag3 = 4
}

public class WorkerRole : RoleEntryPoint
{
    public override void Run()
    {
        // This is a sample worker implementation. Replace with your logic.
        Trace.TraceInformation("WorkerRole1 entry point called");

        int value = 0;

        while (true)
        {
            Thread.Sleep(10000);
            Trace.TraceInformation("Working");

            // Emit several events every time we go through the loop
            for (int i = 0; i < 6; i++)
            {
                SampleEventSourceWriter.Log.SendEnums(MyColor.Blue, MyFlags.Flag2 | MyFlags.Flag3);
            }

            for (int i = 0; i < 3; i++)
            {
                SampleEventSourceWriter.Log.MessageMethod("This is a message.");
                SampleEventSourceWriter.Log.SetOther(true, 123456789);
            }

            if (value == int.MaxValue) value = 0;
            SampleEventSourceWriter.Log.HighFreq(value++);
        }
    }

    public override bool OnStart()
    {
        // Set the maximum number of concurrent connections
        ServicePointManager.DefaultConnectionLimit = 12;

        // For information on handling configuration changes
        // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

        return base.OnStart();
    }
}
}

步骤 3:部署辅助角色Step 3: Deploy your Worker Role

Warning

为现有角色启用诊断时,将禁用部署包时已设置的所有扩展。When you enable diagnostics for an existing role, any extensions that you have already set are disabled when the package is deployed. 其中包括:These include:

  • Microsoft Monitoring Agent 诊断Microsoft Monitoring Agent Diagnostics
  • Microsoft Azure 安全监视Microsoft Azure Security Monitoring
  • Microsoft AntimalwareMicrosoft Antimalware
  • Microsoft Monitoring AgentMicrosoft Monitoring Agent
  • Microsoft 服务探查器代理Microsoft Service Profiler Agent
  • Microsoft Azure 域扩展Windows Azure Domain Extension
  • Microsoft Azure 诊断扩展Windows Azure Diagnostics Extension
  • Microsoft Azure 远程桌面扩展Windows Azure Remote Desktop Extension
  • Microsoft Azure 日志收集器Windows Azure Log Collector

部署更新的角色后,可以通过 Azure 门户或 PowerShell 重置扩展。You can reset your extensions via the Azure portal or PowerShell after you deploy the updated role.

  1. 通过选择解决方案资源管理器中的 WadExample 项目,然后在“生成”菜单中选择“发布”,在 Visual Studio 中将辅助角色部署到 Azure。Deploy your worker role to Azure from within Visual Studio by selecting the WadExample project in the Solution Explorer then Publish from the Build menu.
  2. 选择订阅。Choose your subscription.
  3. 在“Azure 发布设置”对话框中,选择“新建...”。In the Azure Publish Settings dialog select Create New….
  4. 在“创建云服务和存储帐户”对话框中输入一个“名称”(例如“WadExample”),然后选择区域或地缘组。In the Create Cloud Service and Storage Account dialog enter a Name (for example, "WadExample") and select a region or affinity group.
  5. 将“环境”设置为“暂存”。Set the Environment to Staging.
  6. 适当地修改任何其他设置,然后单击“发布”。Modify any other Settings as appropriate and click Publish.
  7. 完成部署后,在 Azure 门户中验证云服务是否处于“正在运行”状态。After deployment has completed, verify in the Azure portal that your cloud service is in a Running state.

步骤 4:创建 Diagnostics 配置文件并安装扩展Step 4: Create your Diagnostics configuration file and install the extension

  1. 通过执行以下 PowerShell 命令下载公共配置文件架构定义:Download the public configuration file schema definition by executing the following PowerShell command:

    (Get-AzureServiceAvailableExtension -ExtensionName 'PaaSDiagnostics' -ProviderNamespace 'Microsoft.Azure.Diagnostics').PublicConfigurationSchema | Out-File -Encoding utf8 -FilePath 'WadConfig.xsd'
    
  2. 通过右键单击 WorkerRole1 项目并选择“添加” -> “新建项...”,将 XML 文件添加到 WorkerRole1 项目中Add an XML file to your WorkerRole1 project by right-clicking on the WorkerRole1 project and select Add -> New Item… -> “Visual C# 项” -> “数据” -> “XML 文件”。 -> *Visual C# items* -> *Data* -> *XML File*. 将该文件命名为“WadExample.xml”。Name the file "WadExample.xml".

    CloudServices_diag_add_xml

  3. 将 WadConfig.xsd 与配置文件相关联。Associate the WadConfig.xsd with the configuration file. 确保 WadExample.xml 编辑器窗口是活动的窗口。Make sure the WadExample.xml editor window is the active window. F4 打开“属性”窗口。Press F4 to open the Properties window. 在“属性”窗口中单击“架构”属性。Click the Schemas property in the Properties window. 在“架构”属性中Click the 单击“...”。in the Schemas property. 在“架构”属性中单击“...” Click the Add… button and navigate to the location where you saved the XSD file and select the file WadConfig.xsd. 单击 “确定”Click OK.

  4. 将 WadExample.xml 配置文件的内容替换为以下 XML 并保存该文件。Replace the contents of the WadExample.xml configuration file with the following XML and save the file. 此配置文件定义两个要收集的性能计数器:一个对应于 CPU 使用率,另一个对应于内存使用率。This configuration file defines a couple performance counters to collect: one for CPU utilization and one for memory utilization. 配置将定义对应于 SampleEventSourceWriter 类中方法的四个事件。Then the configuration defines the four events corresponding to the methods in the SampleEventSourceWriter class.

<?xml version="1.0" encoding="utf-8"?>
<PublicConfig xmlns="http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration">
  <WadCfg>
    <DiagnosticMonitorConfiguration overallQuotaInMB="25000">
      <PerformanceCounters scheduledTransferPeriod="PT1M">
        <PerformanceCounterConfiguration counterSpecifier="\Processor(_Total)\% Processor Time" sampleRate="PT1M" unit="percent" />
        <PerformanceCounterConfiguration counterSpecifier="\Memory\Committed Bytes" sampleRate="PT1M" unit="bytes"/>
      </PerformanceCounters>
      <EtwProviders>
        <EtwEventSourceProviderConfiguration provider="SampleEventSourceWriter" scheduledTransferPeriod="PT5M">
          <Event id="1" eventDestination="EnumsTable"/>
          <Event id="2" eventDestination="MessageTable"/>
          <Event id="3" eventDestination="SetOtherTable"/>
          <Event id="4" eventDestination="HighFreqTable"/>
          <DefaultEvents eventDestination="DefaultTable" />
        </EtwEventSourceProviderConfiguration>
      </EtwProviders>
    </DiagnosticMonitorConfiguration>
  </WadCfg>
</PublicConfig>

步骤 5:在辅助角色上安装 DiagnosticsStep 5: Install Diagnostics on your Worker Role

用于在 Web 或辅助角色上管理 Diagnostics 的 PowerShell cmdlet 为:Set-AzureServiceDiagnosticsExtension、Get-AzureServiceDiagnosticsExtension 和 Remove-AzureServiceDiagnosticsExtension。The PowerShell cmdlets for managing Diagnostics on a web or worker role are: Set-AzureServiceDiagnosticsExtension, Get-AzureServiceDiagnosticsExtension, and Remove-AzureServiceDiagnosticsExtension.

  1. 打开 Azure PowerShell。Open Azure PowerShell.

  2. 执行脚本以在辅助角色上安装 Diagnostics(将 StorageAccountKey 替换为 wadexample 存储帐户的存储帐户密钥,并将 config_path 替换为 WadExample.xml 文件的路径):Execute the script to install Diagnostics on your worker role (replace StorageAccountKey with the storage account key for your wadexample storage account and config_path with the path to the WadExample.xml file):

    $storage_name = "wadexample"
    $key = "<StorageAccountKey>"
    $config_path="c:\users\<user>\documents\visual studio 2013\Projects\WadExample\WorkerRole1\WadExample.xml"
    $service_name="wadexample"
    $storageContext = New-AzureStorageContext -StorageAccountName $storage_name -StorageAccountKey $key 
    Set-AzureServiceDiagnosticsExtension -StorageContext $storageContext -DiagnosticsConfigurationPath $config_path -ServiceName $service_name -Slot Staging -Role WorkerRole1
    

步骤 6:查看遥测数据Step 6: Look at your telemetry data

在 Visual Studio 的“服务器资源管理器”中,导航到 wadexample 存储帐户。In the Visual Studio Server Explorer, navigate to the wadexample storage account. 在云服务运行约 5 分钟后,应该会看到表 WADEnumsTable、WADHighFreqTable、WADMessageTable、WADPerformanceCountersTable 和 WADSetOtherTable。After the cloud service has been running about five (5) minutes, you should see the tables WADEnumsTable, WADHighFreqTable, WADMessageTable, WADPerformanceCountersTable and WADSetOtherTable. 双击其中一个表即可查看已收集的遥测数据。Double-click one of the tables to view the telemetry that has been collected.

CloudServices_diag_tables

配置文件架构Configuration File Schema

诊断配置文件定义启动诊断代理时用于初始化诊断配置设置的值。The Diagnostics configuration file defines values that are used to initialize diagnostic configuration settings when the diagnostics agent starts. 有关有效值和示例,请参阅 最新架构参考See the latest schema reference for valid values and examples.

故障排除Troubleshooting

如果遇到问题,请参阅 Azure 诊断疑难解答,获取有关常见问题的帮助。If you have trouble, see Troubleshooting Azure Diagnostics for help with common problems.

后续步骤Next Steps

若要更改你收集的数据、排查问题或者了解有关诊断的一般信息,请参阅有关 Azure 虚拟机的诊断文章列表See a list of related Azure virtual-machine diagnostic articles to change the data you are collecting, troubleshoot problems or learn more about diagnostics in general.