Azure Key Vault 日志记录Azure Key Vault logging


本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

在创建一个或多个 Key Vault 之后,可能需要监视 Key Vault 的访问方式、时间和访问者。After you create one or more key vaults, you'll likely want to monitor how and when your key vaults are accessed, and by whom. 为此,可以启用 Azure Key Vault 日志记录,以便在提供的 Azure 存储帐户中保存信息。You can do this by enabling logging for Azure Key Vault, which saves information in an Azure storage account that you provide. 系统会自动为指定的存储帐户创建名为 insights-logs-auditevent 的新容器。A new container named insights-logs-auditevent is automatically created for your specified storage account. 可以使用此同一个存储帐户来收集多个 Key Vault 的日志。You can use this same storage account for collecting logs for multiple key vaults.

最多在执行 Key Vault 操作 10 分钟后,就能访问其日志记录信息。You can access your logging information 10 minutes (at most) after the key vault operation. 但大多数情况下不用等待这么长时间。In most cases, it will be quicker than this. 存储帐户中的日志完全由你管理:It's up to you to manage your logs in your storage account:

  • 请使用标准的 Azure 访问控制方法限制可访问日志的人员,以此保护日志。Use standard Azure access control methods to secure your logs by restricting who can access them.
  • 删除不想继续保留在存储帐户中的日志。Delete logs that you no longer want to keep in your storage account.

借助本教程开始使用 Azure 密钥保管库日志记录。Use this tutorial to help you get started with Azure Key Vault logging. 你将创建一个存储帐户,启用日志记录,并解释收集的日志信息。You'll create a storage account, enable logging, and interpret the collected log information.


本教程不包含有关如何创建密钥保管库、密钥或机密的说明。This tutorial does not include instructions for how to create key vaults, keys, or secrets. 有关信息,请参阅什么是 Azure 密钥保管库?For this information, see What is Azure Key Vault?. 或者,有关跨平台 Azure CLI 的说明,请参阅此对应教程Or, for cross-platform Azure CLI instructions, see this equivalent tutorial.

本文提供有关更新诊断日志记录的 Azure PowerShell 说明。This article provides Azure PowerShell instructions for updating diagnostic logging. 也可以使用 Azure 门户的“诊断日志”部分的 Azure Monitor 来更新诊断日志记录。 You can also update diagnostic logging by using Azure Monitor in the Diagnostic logs section of the Azure portal.

有关 Key Vault的概述信息,请参阅什么是 Azure Key Vault?For overview information about Key Vault, see What is Azure Key Vault?. 有关 Key Vault 可用位置的信息,请参阅定价页For information about where Key Vault is available, see the pricing page.


若要完成本教程,必须具备以下项目:To complete this tutorial, you must have the following:

  • 正在使用的现有密钥保管库。An existing key vault that you have been using.
  • Azure PowerShell,最低版本为 1.0.0。Azure PowerShell, minimum version of 1.0.0. 要安装 Azure PowerShell 并将其与 Azure 订阅相关联,请参阅如何安装和配置 Azure PowerShellTo install Azure PowerShell and associate it with your Azure subscription, see How to install and configure Azure PowerShell. 如果已安装了 Azure PowerShell,但不知道版本,请在 Azure PowerShell 控制台中输入 $PSVersionTable.PSVersionIf you have already installed Azure PowerShell and don't know the version, from the Azure PowerShell console, enter $PSVersionTable.PSVersion.
  • 足够的 Azure 存储用于保存密钥保管库日志。Sufficient storage on Azure for your Key Vault logs.

连接到 Key Vault 订阅Connect to your key vault subscription

设置密钥日志记录的第一步是将 Azure PowerShell 指向要记录的 Key Vault。The first step in setting up key logging is to point Azure PowerShell to the key vault that you want to log.

使用以下命令启动 Azure PowerShell 会话,并登录 Azure 帐户:Start an Azure PowerShell session and sign in to your Azure account by using the following command:

Connect-AzAccount -EnvironmentName AzureChinaCloud

在弹出的浏览器窗口中,输入 Azure 帐户用户名和密码。In the pop-up browser window, enter your Azure account user name and password. Azure PowerShell 将获取与此帐户关联的所有订阅。Azure PowerShell gets all the subscriptions that are associated with this account. PowerShell 默认使用第一个订阅。By default, PowerShell uses the first one.

可能需要指定用于创建 Key Vault 的订阅。You might have to specify the subscription that you used to create your key vault. 输入以下命令以查看帐户的订阅:Enter the following command to see the subscriptions for your account:


然后,若要指定与要记录的 Key Vault 关联的订阅,请输入:Then, to specify the subscription that's associated with the key vault you'll be logging, enter:

Set-AzContext -SubscriptionId <subscription ID>

将 PowerShell 指向正确的订阅是一个重要步骤,尤其是在有多个订阅与帐户关联的情况下。Pointing PowerShell to the right subscription is an important step, especially if you have multiple subscriptions associated with your account. 有关配置 Azure PowerShell 的详细信息,请参阅 如何安装和配置 Azure PowerShellFor more information about configuring Azure PowerShell, see How to install and configure Azure PowerShell.

为日志创建存储帐户Create a storage account for your logs

尽管可以使用现有的存储帐户来保存日志,但我们将专门创建一个存储帐户来保存 Key Vault 日志。Although you can use an existing storage account for your logs, we'll create a storage account that will be dedicated to Key Vault logs. 为方便起见,在稍后遇到必须指定此帐户的情况时,我们会将详细信息存储到名为 sa的变量中。For convenience for when we have to specify this later, we'll store the details in a variable named sa.

为了进一步简化管理,我们还使用了包含 Key Vault 的同一个资源组。For additional ease of management, we'll also use the same resource group as the one that contains the key vault. 入门教程中,此资源组的名称为 ContosoResourceGroup,我们将继续使用“东亚”位置。From the getting-started tutorial, this resource group is named ContosoResourceGroup, and we'll continue to use the East Asia location. 在适当的情况下,请将这些值替换为自己的值:Replace these values with your own, as applicable:

 $sa = New-AzStorageAccount -ResourceGroupName ContosoResourceGroup -Name contosokeyvaultlogs -Type Standard_LRS -Location 'East Asia'


如果你决定使用现有存储帐户,该帐户必须使用与 Key Vault 相同的订阅。If you decide to use an existing storage account, it must use the same subscription as your key vault. 该帐户还必须使用 Azure 资源管理器部署模型,而不是经典部署模型。And it must use the Azure Resource Manager deployment model, rather than the classic deployment model.

标识用于保存日志的密钥保管库Identify the key vault for your logs

入门教程中,Key Vault 名称为 ContosoKeyVaultIn the getting-started tutorial, the key vault name was ContosoKeyVault. 我们将继续使用该名称,并将详细信息存储在名为 kv 的变量中:We'll continue to use that name and store the details in a variable named kv:

$kv = Get-AzKeyVault -VaultName 'ContosoKeyVault'

启用日志记录Enable logging

为了启用 Key Vault 日志记录,我们将使用 Set-AzDiagnosticSetting cmdlet 并配合针对新存储帐户和 Key Vault 创建的变量。To enable logging for Key Vault, we'll use the Set-AzDiagnosticSetting cmdlet, together with the variables that we created for the new storage account and the key vault. 还将 -Enabled 标志设置为 $true,并将类别设置为 AuditEvent(Key Vault 日志记录的唯一类别):We'll also set the -Enabled flag to $true and set the category to AuditEvent (the only category for Key Vault logging):

Set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -Enabled $true -Category AuditEvent

输出如下所示:The output looks like this:

StorageAccountId   : /subscriptions/<subscription-GUID>/resourceGroups/ContosoResourceGroup/providers/Microsoft.Storage/storageAccounts/ContosoKeyVaultLogs
ServiceBusRuleId   :
StorageAccountName :
    Enabled           : True
    Category          : AuditEvent
    Enabled : False
    Days    : 0

此输出确认 Key Vault 日志记录现已启用,会将信息保存到存储帐户。This output confirms that logging is now enabled for your key vault, and it will save information to your storage account.

还可以选择性地为日志设置保留期策略,以便自动删除较旧的日志。Optionally, you can set a retention policy for your logs such that older logs are automatically deleted. 例如,通过将 -RetentionEnabled 标志设置为 $true 来设置保留期策略,并将 -RetentionInDays 参数设置为 90,以便自动删除 90 天以上的日志。For example, set retention policy by setting the -RetentionEnabled flag to $true, and set the -RetentionInDays parameter to 90 so that logs older than 90 days are automatically deleted.

Set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -Enabled $true -Category AuditEvent -RetentionEnabled $true -RetentionInDays 90

记录的内容:What's logged:

  • 所有已经过身份验证的 REST API 请求,包括由于访问权限、系统错误或错误请求而发生的失败请求。All authenticated REST API requests, including failed requests as a result of access permissions, system errors, or bad requests.
  • 对 Key Vault 本身执行的操作,包括创建、删除、设置 Key Vault 访问策略,以及更新 Key Vault 属性(例如标记)。Operations on the key vault itself, including creation, deletion, setting key vault access policies, and updating key vault attributes such as tags.
  • 针对 Key Vault 中的密钥和机密执行的操作,包括:Operations on keys and secrets in the key vault, including:
    • 创建、修改或删除这些密钥或机密。Creating, modifying, or deleting these keys or secrets.
    • 签名、验证、加密、解密、包装和解包密钥、获取机密,以及列出密钥和机密(及其版本)。Signing, verifying, encrypting, decrypting, wrapping and unwrapping keys, getting secrets, and listing keys and secrets (and their versions).
  • 导致出现 401 响应的未经身份验证的请求。Unauthenticated requests that result in a 401 response. 示例包括不包含持有者令牌、格式不正确或已过期,或者包含无效令牌的请求。Examples are requests that don't have a bearer token, that are malformed or expired, or that have an invalid token.

访问日志Access your logs

Key Vault 日志存储在提供的存储帐户的 insights-logs-auditevent 容器中。Key Vault logs are stored in the insights-logs-auditevent container in the storage account that you provided. 若要查看这些日志,必须下载 Blob。To view the logs, you have to download blobs.

首先,请为容器名称创建一个变量。First, create a variable for the container name. 本演练的剩余部分将使用此变量。You'll use this variable throughout the rest of the walkthrough.

$container = 'insights-logs-auditevent'

若要列出此容器中的所有 Blob,请输入:To list all the blobs in this container, enter:

Get-AzStorageBlob -Container $container -Context $sa.Context

输出与下面类似:The output looks similar to this:

Container Uri:





可从此输出中看出,blob 遵循以下命名约定:resourceId=<ARM resource ID>/y=<year>/m=<month>/d=<day of month>/h=<hour>/m=<minute>/filename.jsonAs you can see from this output, the blobs follow a naming convention: resourceId=<ARM resource ID>/y=<year>/m=<month>/d=<day of month>/h=<hour>/m=<minute>/filename.json

日期和时间值使用 UTC。The date and time values use UTC.

由于可以使用相同的存储帐户来收集多个资源的日志,Blob 名称中的完整资源 ID 适合用于仅访问或下载所需 Blob。Because you can use the same storage account to collect logs for multiple resources, the full resource ID in the blob name is useful to access or download just the blobs that you need. 但在这样做之前,让我们先了解如何下载所有 Blob。But before we do that, we'll first cover how to download all the blobs.

创建一个文件夹用于下载 Blob。Create a folder to download the blobs. 例如:For example:

New-Item -Path 'C:\Users\username\ContosoKeyVaultLogs' -ItemType Directory -Force

然后获取所有 blob 的列表:Then get a list of all blobs:

$blobs = Get-AzStorageBlob -Container $container -Context $sa.Context

通过 Get-AzStorageBlobContent 以管道传送此列表,将 Blob 下载到目标文件夹:Pipe this list through Get-AzStorageBlobContent to download the blobs to the destination folder:

$blobs | Get-AzStorageBlobContent -Destination C:\Users\username\ContosoKeyVaultLogs'

运行第二个命令时,blob 名称中的 / 分隔符会在目标文件夹下创建完整的文件夹结构 。When you run this second command, the / delimiter in the blob names creates a full folder structure under the destination folder. 你将使用此结构下载 Blob 并将其存储为文件。You'll use this structure to download and store the blobs as files.

若要选择性地下载 Blob,请使用通配符。To selectively download blobs, use wildcards. 例如:For example:

  • 如果有多个密钥保管库,并只想要下载其中名为 CONTOSOKEYVAULT3 的密钥保管库的日志:If you have multiple key vaults and want to download logs for just one key vault, named CONTOSOKEYVAULT3:

    Get-AzStorageBlob -Container $container -Context $sa.Context -Blob '*/VAULTS/CONTOSOKEYVAULT3
  • 如果有多个资源组,并只想要下载其中某个资源组的日志,请使用 -Blob '*/RESOURCEGROUPS/<resource group name>/*'If you have multiple resource groups and want to download logs for just one resource group, use -Blob '*/RESOURCEGROUPS/<resource group name>/*':

    Get-AzStorageBlob -Container $container -Context $sa.Context -Blob '*/RESOURCEGROUPS/CONTOSORESOURCEGROUP3/*'
  • 如果要下载 2019 年 1 月份的所有日志,请使用 -Blob '*/year=2019/m=01/*'If you want to download all the logs for the month of January 2019, use -Blob '*/year=2019/m=01/*':

    Get-AzStorageBlob -Container $container -Context $sa.Context -Blob '*/year=2016/m=01/*'

现在已准备就绪,可以开始查看日志中的内容。You're now ready to start looking at what's in the logs. 但在开始之前,应该了解另外两个命令:But before we move on to that, you should know two more commands:

  • 若要查询密钥保管库资源的诊断设置状态:Get-AzDiagnosticSetting -ResourceId $kv.ResourceIdTo query the status of diagnostic settings for your key vault resource: Get-AzDiagnosticSetting -ResourceId $kv.ResourceId
  • 若要禁用密钥保管库资源的日志记录: Set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -Enabled $false -Category AuditEventTo disable logging for your key vault resource: Set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -Enabled $false -Category AuditEvent

解释 Key Vault 日志Interpret your Key Vault logs

每个 Blob 存储为文本,并格式化为 JSON Blob。Individual blobs are stored as text, formatted as a JSON blob. 让我们看一个示例日志项。Let's look at an example log entry. 运行以下命令:Run this command:

Get-AzKeyVault -VaultName 'contosokeyvault'`

该命令将返回类似于下面的日志项:It returns a log entry similar to this one:

                "time": "2016-01-05T01:32:01.2691226Z",
                "operationName": "VaultGet",
                "operationVersion": "2015-06-01",
                "category": "AuditEvent",
                "resultType": "Success",
                "resultSignature": "OK",
                "resultDescription": "",
                "durationMs": "78",
                "callerIpAddress": "",
                "correlationId": "",
                "identity": {"claim":{"":"d9da5048-2737-4770-bd64-XXXXXXXXXXXX","":"","appid":"1950a258-227b-4e31-a9cf-XXXXXXXXXXXX"}},
                "properties": {"clientInfo":"azure-resource-manager/2.0","requestUri":"","id":"","httpStatusCode":200}

下表列出了字段的名称和描述:The following table lists the field names and descriptions:

字段名称Field name 说明Description
timetime 日期和时间 (UTC)。Date and time in UTC.
resourceIdresourceId Azure 资源管理器资源 ID。Azure Resource Manager resource ID. 对于密钥保管库日志而言,这始终是密钥保管库资源 ID。For Key Vault logs, this is always the Key Vault resource ID.
operationNameoperationName 下一份表格中所述操作的名称。Name of the operation, as documented in the next table.
operationVersionoperationVersion 客户端请求的 REST API 版本。REST API version requested by the client.
categorycategory 结果的类型。Type of result. 对于 Key Vault 日志而言,AuditEvent 是唯一可用值。For Key Vault logs, AuditEvent is the single, available value.
resultTyperesultType REST API 请求的结果。Result of the REST API request.
resultSignatureresultSignature HTTP 状态。HTTP status.
resultDescriptionresultDescription 有关结果的其他描述(如果有)。Additional description about the result, when available.
durationMsdurationMs 为 REST API 请求提供服务所花费的时间,以毫秒为单位。Time it took to service the REST API request, in milliseconds. 此时间不包括网络延迟,因此在客户端上测得的时间可能与此时间不匹配。This does not include the network latency, so the time you measure on the client side might not match this time.
callerIpAddresscallerIpAddress 发出请求的客户端的 IP 地址。IP address of the client that made the request.
correlationIdcorrelationId 一个可选 GUID,客户端可传递此 GUID 来使客户端日志与服务端 (Key Vault) 日志相关联。An optional GUID that the client can pass to correlate client-side logs with service-side (Key Vault) logs.
identityidentity 在 REST API 请求中提供的令牌中的标识。Identity from the token that was presented in the REST API request. 与通过 Azure PowerShell cmdlet 发出请求一样,这通常是“用户”、“服务主体”,或者“用户+应用 ID”的组合。This is usually a "user," a "service principal," or the combination "user+appId," as in the case of a request that results from an Azure PowerShell cmdlet.
propertiesproperties 此字段根据操作 (operationName) 包含不同的信息。Information that varies based on the operation (operationName). 在大多数情况下,此字段包含客户端信息(客户端传递的用户代理字符串)、具体 REST API 请求 URI 和 HTTP 状态代码。In most cases, this field contains client information (the user agent string passed by the client), the exact REST API request URI, and the HTTP status code. 此外,在根据请求(例如,KeyCreateVaultGet)返回对象时,此字段还将包含密钥 URI(“id”形式)、保管库 URI 或机密 URI。In addition, when an object is returned as a result of a request (for example, KeyCreate or VaultGet), it also contains the key URI (as "id"), vault URI, or secret URI.

operationName 字段值采用 ObjectVerb 格式。The operationName field values are in ObjectVerb format. 例如:For example:

  • 所有 Key Vault 操作采用 Vault<action> 格式,例如 VaultGetVaultCreateAll key vault operations have the Vault<action> format, such as VaultGet and VaultCreate.
  • 所有密钥操作采用 Key<action> 格式,例如 KeySignKeyListAll key operations have the Key<action> format, such as KeySign and KeyList.
  • 所有机密操作采用 Secret<action> 格式,例如 SecretGetSecretListVersionsAll secret operations have the Secret<action> format, such as SecretGet and SecretListVersions.

下表列出了 operationName 值和对应的 REST API 命令:The following table lists the operationName values and corresponding REST API commands:

operationNameoperationName REST API 命令REST API command
身份验证Authentication 通过 Azure Active Directory 终结点进行身份验证Authenticate via Azure Active Directory endpoint
VaultGetVaultGet 获取有关密钥保管库的信息Get information about a key vault
VaultPutVaultPut 创建或更新密钥保管库Create or update a key vault
VaultDeleteVaultDelete 删除密钥保管库Delete a key vault
VaultPatchVaultPatch 更新密钥保管库Update a key vault
VaultListVaultList 列出资源组中的所有密钥保管库List all key vaults in a resource group
KeyCreateKeyCreate 创建密钥Create a key
KeyGetKeyGet 获取有关密钥的信息Get information about a key
KeyImportKeyImport 将密钥导入保管库Import a key into a vault
KeyBackupKeyBackup 备份密钥Back up a key
KeyDeleteKeyDelete 删除密钥Delete a key
KeyRestoreKeyRestore 还原密钥Restore a key
KeySignKeySign 使用密钥签名Sign with a key
KeyVerifyKeyVerify 使用密钥验证Verify with a key
KeyWrapKeyWrap 包装密钥Wrap a key
KeyUnwrapKeyUnwrap 解包密钥Unwrap a key
KeyEncryptKeyEncrypt 使用密钥加密Encrypt with a key
KeyDecryptKeyDecrypt 使用密钥解密Decrypt with a key
KeyUpdateKeyUpdate 更新密钥Update a key
KeyListKeyList 列出保管库中的密钥List the keys in a vault
KeyListVersionsKeyListVersions 列出密钥的版本List the versions of a key
SecretSetSecretSet 创建机密Create a secret
SecretGetSecretGet 获取机密Get a secret
SecretUpdateSecretUpdate 更新机密Update a secret
SecretDeleteSecretDelete 删除机密Delete a secret
SecretListSecretList 列出保管库中的机密List secrets in a vault
SecretListVersionsSecretListVersions 列出机密的版本List versions of a secret

使用 Azure Monitor 日志Use Azure Monitor logs

可以使用 Azure Monitor 日志中的 Key Vault 解决方案查看 Key Vault AuditEvent 日志。You can use the Key Vault solution in Azure Monitor logs to review Key Vault AuditEvent logs. 在 Azure Monitor 日志中,可以使用日志查询来分析数据并获取所需的信息。In Azure Monitor logs, you use log queries to analyze data and get the information you need.

有关详细信息,包括如何进行设置,请参阅 Azure Monitor 日志中的Azure Key Vault 解决方案For more information, including how to set this up, see Azure Key Vault solution in Azure Monitor logs. 如果需要从 Azure Monitor 日志预览版提供的旧 Key Vault 解决方案进行迁移,且之前在该方案中,首先将日志路由到了 Azure 存储帐户,并将 Azure Monitor 日志配置为了从此处读取,则本文也可提供指导。This article also contains instructions if you need to migrate from the old Key Vault solution that was offered during the Azure Monitor logs preview, where you first routed your logs to an Azure storage account and configured Azure Monitor logs to read from there.

后续步骤Next steps

有关在 .NET Web 应用程序中使用 Azure Key Vault 的教程,请参阅从 Web 应用程序使用 Azure Key VaultFor a tutorial that uses Azure Key Vault in a .NET web application, see Use Azure Key Vault from a web application.

有关编程参考,请参阅 Azure 密钥保管库开发人员指南For programming references, see the Azure Key Vault developer's guide.

有关 Azure Key Vault 的 Azure PowerShell 1.0 cmdlet 列表,请参阅 Azure Key Vault cmdletFor a list of Azure PowerShell 1.0 cmdlets for Azure Key Vault, see Azure Key Vault cmdlets.

有关使用 Azure Key Vault 进行密钥轮换和日志审核的教程,请参阅为 Key Vault 设置端到端密钥转换和审核For a tutorial on key rotation and log auditing with Azure Key Vault, see Set up Key Vault with end-to-end key rotation and auditing.