使用 PowerShell 在运行 Windows 的虚拟机中启用 Azure 诊断Use PowerShell to enable Azure Diagnostics in a virtual machine running Windows

Azure 诊断是 Azure 中可对部署的应用程序启用诊断数据收集的功能。Azure Diagnostics is the capability within Azure that enables the collection of diagnostic data on a deployed application. 可以使用诊断扩展从运行 Windows 的 Azure 虚拟机 (VM) 中收集诊断数据(例如应用程序日志或性能计数器)。You can use the diagnostics extension to collect diagnostic data like application logs or performance counters from an Azure virtual machine (VM) that is running Windows.

在使用 Resource Manager 部署模型的情况下启用诊断扩展Enable the diagnostics extension if you use the Resource Manager deployment model

通过 Azure Resource Manager 部署模型创建 Windows VM 时,只需将诊断扩展配置添加到 Resource Manager 模板,即可启用该扩展。You can enable the diagnostics extension while you create a Windows VM through the Azure Resource Manager deployment model by adding the extension configuration to the Resource Manager template. 请参阅 Create a Windows virtual machine with monitoring and diagnostics by using the Azure Resource Manager template(使用 Azure Resource Manager 模板创建具有监视和诊断功能的 Windows 虚拟机)。See Create a Windows virtual machine with monitoring and diagnostics by using the Azure Resource Manager template.

要在通过资源管理器部署模型创建的现有 VM 上启用诊断扩展,可按如下所示使用 Set-AzVMDiagnosticsExtension PowerShell cmdlet。To enable the diagnostics extension on an existing VM that was created through the Resource Manager deployment model, you can use the Set-AzVMDiagnosticsExtension PowerShell cmdlet as shown below.

$vm_resourcegroup = "myvmresourcegroup"
$vm_name = "myvm"
$diagnosticsconfig_path = "DiagnosticsPubConfig.xml"

Set-AzVMDiagnosticsExtension -ResourceGroupName $vm_resourcegroup -VMName $vm_name -DiagnosticsConfigurationPath $diagnosticsconfig_path

$diagnosticsconfig_path 是指向包含 XML 格式诊断配置的文件的路径,如以下示例中所述。$diagnosticsconfig_path is the path to the file that contains the diagnostics configuration in XML, as described in the sample below.

如果诊断配置文件使用某个存储帐户名称指定了 StorageAccount 元素,则 Set-AzVMDiagnosticsExtension 脚本会自动将诊断扩展设置为将诊断数据发送到该存储帐户 。If the diagnostics configuration file specifies a StorageAccount element with a storage account name, then the Set-AzVMDiagnosticsExtension script will automatically set the diagnostics extension to send diagnostic data to that storage account. 为此,存储帐户需位于 VM 所在的同一订阅中。For this to work, the storage account needs to be in the same subscription as the VM.

如果未在诊断配置中指定 StorageAccount,需要将 StorageAccountName 参数传递给 cmdlet。If no StorageAccount was specified in the diagnostics configuration, then you need to pass in the StorageAccountName parameter to the cmdlet. 如果指定了 StorageAccountName 参数,则 cmdlet 会始终使用该参数中指定的存储帐户,而不使用诊断配置文件中指定的存储帐户。If the StorageAccountName parameter is specified, then the cmdlet will always use the storage account that is specified in the parameter and not the one that is specified in the diagnostics configuration file.

如果诊断存储帐户与 VM 属于不同的订阅,则必须将 StorageAccountNameStorageAccountKey 参数显式传递给 cmdlet。If the diagnostics storage account is in a different subscription from the VM, then you need to explicitly pass in the StorageAccountName and StorageAccountKey parameters to the cmdlet. 当诊断存储帐户在同一订阅中时,不需要 StorageAccountKey 参数,因为 cmdlet 可以在启用诊断扩展时自动查询和设置密钥值。The StorageAccountKey parameter is not needed when the diagnostics storage account is in the same subscription, as the cmdlet can automatically query and set the key value when enabling the diagnostics extension. 但是,如果诊断存储帐户在不同的订阅中,则 cmdlet 可能无法自动获取密钥,需要通过 StorageAccountKey 参数显式指定该密钥。However, if the diagnostics storage account is in a different subscription, then the cmdlet might not be able to get the key automatically and you need to explicitly specify the key through the StorageAccountKey parameter.

Set-AzVMDiagnosticsExtension -ResourceGroupName $vm_resourcegroup -VMName $vm_name -DiagnosticsConfigurationPath $diagnosticsconfig_path -StorageAccountName $diagnosticsstorage_name -StorageAccountKey $diagnosticsstorage_key

在 VM 上启用诊断扩展后,可以使用 Get-AzVmDiagnosticsExtension cmdlet 获取当前设置。Once the diagnostics extension is enabled on a VM, you can get the current settings by using the Get-AzVmDiagnosticsExtension cmdlet.

Get-AzVMDiagnosticsExtension -ResourceGroupName $vm_resourcegroup -VMName $vm_name

该 cmdlet 返回 PublicSettings,其中包含诊断配置。The cmdlet returns PublicSettings, which contains the diagnostics configuration. 支持两种类型的配置:WadCfg 和 xmlCfg。There are two kinds of configuration supported, WadCfg and xmlCfg. WadCfg 是 JSON 配置,而 xmlCfg 是 Base64 编码格式的 XML 配置。WadCfg is JSON configuration, and xmlCfg is XML configuration in a Base64-encoded format. 若要读取该 XML,需将其解码。To read the XML, you need to decode it.

$publicsettings = (Get-AzVMDiagnosticsExtension -ResourceGroupName $vm_resourcegroup -VMName $vm_name).PublicSettings
$encodedconfig = (ConvertFrom-Json -InputObject $publicsettings).xmlCfg
$xmlconfig = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($encodedconfig))
Write-Host $xmlconfig

可以使用 Remove-AzVmDiagnosticsExtension cmdlet 从 VM 中删除该诊断扩展。The Remove-AzVmDiagnosticsExtension cmdlet can be used to remove the diagnostics extension from the VM.

在使用经典部署模型的情况下启用诊断扩展Enable the diagnostics extension if you use the classic deployment model

重要

经典 VM 将于 2023 年 3 月 1 日停用。Classic VMs will be retired on March 1, 2023.

如果从 ASM 使用 IaaS 资源,请在 2023 年 3 月 1 日之前完成迁移。If you use IaaS resources from ASM, please complete your migration by March 1, 2023. 我们建议你尽快进行切换,以利用 Azure 资源管理器中的许多增强功能。We encourage you to make the switch sooner to take advantage of the many feature enhancements in Azure Resource Manager.

有关详细信息,请参阅在 2023 年 3 月 1 日之前将 IaaS 资源迁移到 Azure 资源管理器For more information, see Migrate your IaaS resources to Azure Resource Manager by March 1, 2023.

在通过经典部署模型创建的 VM 上,可以使用 Set-AzureVMDiagnosticsExtension cmdlet 启用诊断扩展。You can use the Set-AzureVMDiagnosticsExtension cmdlet to enable a diagnostics extension on a VM that you create through the classic deployment model. 以下示例演示了如何通过经典部署模型创建启用了诊断扩展的新 VM。The following example shows how to create a new VM through the classic deployment model with the diagnostics extension enabled.

$VM = New-AzureVMConfig -Name $VM -InstanceSize Small -ImageName $VMImage
$VM = Add-AzureProvisioningConfig -VM $VM -AdminUsername $Username -Password $Password -Windows
$VM = Set-AzureVMDiagnosticsExtension -DiagnosticsConfigurationPath $Config_Path -VM $VM -StorageContext $Storage_Context
New-AzVM -Location $Location -ServiceName $Service_Name -VM $VM

若要在通过典型部署模型创建的现有 VM 上启用诊断扩展,请先使用 Get-AzureVM cmdlet 获取 VM 配置。To enable the diagnostics extension on an existing VM that was created through the classic deployment model, first use the Get-AzureVM cmdlet to get the VM configuration. 然后,使用 Set-AzureVMDiagnosticsExtension cmdlet 更新 VM 配置,使其包含诊断扩展。Then update the VM configuration to include the diagnostics extension by using the Set-AzureVMDiagnosticsExtension cmdlet. 最后,使用 Update-AzureVM 将更新的配置应用到 VM。Finally, apply the updated configuration to the VM by using Update-AzureVM.

$VM = Get-AzureVM -ServiceName $Service_Name -Name $VM_Name
$VM_Update = Set-AzureVMDiagnosticsExtension  -DiagnosticsConfigurationPath $Config_Path -VM $VM -StorageContext $Storage_Context
Update-AzureVM -ServiceName $Service_Name -Name $VM_Name -VM $VM_Update.VM

诊断配置示例Sample diagnostics configuration

以下 XML 可用于上述脚本的诊断公共配置。The following XML can be used for the diagnostics public configuration with the above scripts. 此示例配置会将各种性能计数器传输给诊断存储帐户,同时还会传输 Windows 事件日志的应用程序、安全和系统通道中的错误,以及诊断基础结构日志中的任何错误。This sample configuration will transfer various performance counters to the diagnostics storage account, along with errors from the application, security, and system channels in the Windows event logs and any errors from the diagnostics infrastructure logs.

需要对该配置进行更新,以便包括以下内容:The configuration needs to be updated to include the following:

  • Metrics 元素的 resourceID 属性需要使用 VM 的资源 ID 进行更新。The resourceID attribute of the Metrics element needs to be updated with the resource ID for the VM.

    • 资源 ID 可以使用以下模式构造:“/subscriptions/{VM 订阅的订阅 ID}/resourceGroups/{VM 的资源组名称}/providers/Microsoft.Compute/virtualMachines/{VM 名称}”。The resource ID can be constructed by using the following pattern: "/subscriptions/{subscription ID for the subscription with the VM}/resourceGroups/{The resourcegroup name for the VM}/providers/Microsoft.Compute/virtualMachines/{The VM Name}".

    • 例如,如果在其中运行 VM 的订阅的订阅 ID 为 11111111-1111-1111-1111-111111111111,资源组的资源组名称为 MyResourceGroup,VM 名称为 MyWindowsVM,则 resourceID 的值为:For example, if the subscription ID for the subscription where the VM is running is 11111111-1111-1111-1111-111111111111, the resource group name for the resource group is MyResourceGroup, and the VM Name is MyWindowsVM, then the value for resourceID would be:

      <Metrics resourceId="/subscriptions/11111111-1111-1111-1111-111111111111/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/virtualMachines/MyWindowsVM" >
      
    • 有关如何根据性能计数器和指标配置生成指标的详细信息,请参阅 Azure Diagnostics metrics table in storage(存储中的 Azure 诊断指标表)。For more information on how metrics are generated based on the performance counters and metrics configuration, see Azure Diagnostics metrics table in storage.

  • 需要使用诊断存储帐户的名称对 StorageAccount 元素进行更新。The StorageAccount element needs to be updated with the name of the diagnostics storage account.

    <?xml version="1.0" encoding="utf-8"?>
    <PublicConfig xmlns="http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration">
        <WadCfg>
          <DiagnosticMonitorConfiguration overallQuotaInMB="4096">
            <DiagnosticInfrastructureLogs scheduledTransferLogLevelFilter="Error"/>
            <PerformanceCounters scheduledTransferPeriod="PT1M">
          <PerformanceCounterConfiguration counterSpecifier="\Processor(_Total)\% Processor Time" sampleRate="PT15S" unit="Percent">
            <annotation displayName="CPU utilization" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\Processor(_Total)\% Privileged Time" sampleRate="PT15S" unit="Percent">
            <annotation displayName="CPU privileged time" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\Processor(_Total)\% User Time" sampleRate="PT15S" unit="Percent">
            <annotation displayName="CPU user time" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\Processor Information(_Total)\Processor Frequency" sampleRate="PT15S" unit="Count">
            <annotation displayName="CPU frequency" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\System\Processes" sampleRate="PT15S" unit="Count">
            <annotation displayName="Processes" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\Process(_Total)\Thread Count" sampleRate="PT15S" unit="Count">
            <annotation displayName="Threads" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\Process(_Total)\Handle Count" sampleRate="PT15S" unit="Count">
            <annotation displayName="Handles" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\Memory\% Committed Bytes In Use" sampleRate="PT15S" unit="Percent">
            <annotation displayName="Memory usage" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\Memory\Available Bytes" sampleRate="PT15S" unit="Bytes">
            <annotation displayName="Memory available" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\Memory\Committed Bytes" sampleRate="PT15S" unit="Bytes">
            <annotation displayName="Memory committed" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\Memory\Commit Limit" sampleRate="PT15S" unit="Bytes">
            <annotation displayName="Memory commit limit" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\Memory\Pool Paged Bytes" sampleRate="PT15S" unit="Bytes">
            <annotation displayName="Memory paged pool" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\Memory\Pool Nonpaged Bytes" sampleRate="PT15S" unit="Bytes">
            <annotation displayName="Memory non-paged pool" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\PhysicalDisk(_Total)\% Disk Time" sampleRate="PT15S" unit="Percent">
            <annotation displayName="Disk active time" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\PhysicalDisk(_Total)\% Disk Read Time" sampleRate="PT15S" unit="Percent">
            <annotation displayName="Disk active read time" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\PhysicalDisk(_Total)\% Disk Write Time" sampleRate="PT15S" unit="Percent">
            <annotation displayName="Disk active write time" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\PhysicalDisk(_Total)\Disk Transfers/sec" sampleRate="PT15S" unit="CountPerSecond">
            <annotation displayName="Disk operations" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\PhysicalDisk(_Total)\Disk Reads/sec" sampleRate="PT15S" unit="CountPerSecond">
            <annotation displayName="Disk read operations" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\PhysicalDisk(_Total)\Disk Writes/sec" sampleRate="PT15S" unit="CountPerSecond">
            <annotation displayName="Disk write operations" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\PhysicalDisk(_Total)\Disk Bytes/sec" sampleRate="PT15S" unit="BytesPerSecond">
            <annotation displayName="Disk speed" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\PhysicalDisk(_Total)\Disk Read Bytes/sec" sampleRate="PT15S" unit="BytesPerSecond">
            <annotation displayName="Disk read speed" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\PhysicalDisk(_Total)\Disk Write Bytes/sec" sampleRate="PT15S" unit="BytesPerSecond">
            <annotation displayName="Disk write speed" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\PhysicalDisk(_Total)\Avg. Disk Queue Length" sampleRate="PT15S" unit="Count">
            <annotation displayName="Disk average queue length" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\PhysicalDisk(_Total)\Avg. Disk Read Queue Length" sampleRate="PT15S" unit="Count">
            <annotation displayName="Disk average read queue length" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\PhysicalDisk(_Total)\Avg. Disk Write Queue Length" sampleRate="PT15S" unit="Count">
            <annotation displayName="Disk average write queue length" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\LogicalDisk(_Total)\% Free Space" sampleRate="PT15S" unit="Percent">
            <annotation displayName="Disk free space (percentage)" locale="en-us"/>
          </PerformanceCounterConfiguration>
          <PerformanceCounterConfiguration counterSpecifier="\LogicalDisk(_Total)\Free Megabytes" sampleRate="PT15S" unit="Count">
            <annotation displayName="Disk free space (MB)" locale="en-us"/>
          </PerformanceCounterConfiguration>
        </PerformanceCounters>
        <Metrics resourceId="(Update with resource ID for the VM)" >
            <MetricAggregation scheduledTransferPeriod="PT1H"/>
            <MetricAggregation scheduledTransferPeriod="PT1M"/>
        </Metrics>
        <WindowsEventLog scheduledTransferPeriod="PT1M">
          <DataSource name="Application!*[System[(Level = 1 or Level = 2)]]"/>
          <DataSource name="Security!*[System[(Level = 1 or Level = 2)]"/>
          <DataSource name="System!*[System[(Level = 1 or Level = 2)]]"/>
        </WindowsEventLog>
          </DiagnosticMonitorConfiguration>
        </WadCfg>
        <StorageAccount>(Update with diagnostics storage account name)</StorageAccount>
    </PublicConfig>
    

后续步骤Next steps